turbo-design 1.3.8__py3-none-any.whl → 1.3.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of turbo-design might be problematic. Click here for more details.

Files changed (48) hide show
  1. {turbo_design-1.3.8.dist-info → turbo_design-1.3.9.dist-info}/METADATA +2 -1
  2. turbo_design-1.3.9.dist-info/RECORD +46 -0
  3. {turbo_design-1.3.8.dist-info → turbo_design-1.3.9.dist-info}/WHEEL +1 -1
  4. turbodesign/__init__.py +57 -4
  5. turbodesign/agf.py +346 -0
  6. turbodesign/arrayfuncs.py +31 -1
  7. turbodesign/bladerow.py +237 -155
  8. turbodesign/compressor_math.py +374 -0
  9. turbodesign/compressor_spool.py +837 -0
  10. turbodesign/coolant.py +18 -6
  11. turbodesign/deviation/__init__.py +5 -0
  12. turbodesign/deviation/axial_compressor.py +3 -0
  13. turbodesign/deviation/carter_deviation.py +79 -0
  14. turbodesign/deviation/deviation_base.py +20 -0
  15. turbodesign/deviation/fixed_deviation.py +42 -0
  16. turbodesign/enums.py +5 -6
  17. turbodesign/flow_math.py +159 -0
  18. turbodesign/inlet.py +126 -56
  19. turbodesign/isentropic.py +59 -15
  20. turbodesign/loss/__init__.py +3 -1
  21. turbodesign/loss/compressor/OTAC_README.md +39 -0
  22. turbodesign/loss/compressor/__init__.py +54 -0
  23. turbodesign/loss/compressor/diffusion.py +61 -0
  24. turbodesign/loss/compressor/lieblein.py +1 -0
  25. turbodesign/loss/compressor/otac.py +799 -0
  26. turbodesign/loss/compressor/references/schobeiri-2012-shock-loss-model-for-transonic-and-supersonic-axial-compressors-with-curved-blades.pdf +0 -0
  27. turbodesign/loss/fixedpolytropic.py +27 -0
  28. turbodesign/loss/fixedpressureloss.py +30 -0
  29. turbodesign/loss/losstype.py +2 -30
  30. turbodesign/loss/turbine/TD2.py +25 -29
  31. turbodesign/loss/turbine/__init__.py +0 -1
  32. turbodesign/loss/turbine/ainleymathieson.py +6 -5
  33. turbodesign/loss/turbine/craigcox.py +6 -5
  34. turbodesign/loss/turbine/fixedefficiency.py +8 -7
  35. turbodesign/loss/turbine/kackerokapuu.py +7 -5
  36. turbodesign/loss/turbine/traupel.py +17 -16
  37. turbodesign/outlet.py +81 -22
  38. turbodesign/passage.py +98 -63
  39. turbodesign/row_factory.py +129 -0
  40. turbodesign/solve_radeq.py +9 -10
  41. turbodesign/{td_math.py → turbine_math.py} +126 -175
  42. turbodesign/turbine_spool.py +984 -0
  43. turbo_design-1.3.8.dist-info/RECORD +0 -33
  44. turbodesign/compressorspool.py +0 -60
  45. turbodesign/loss/turbine/fixedpressureloss.py +0 -25
  46. turbodesign/rotor.py +0 -38
  47. turbodesign/spool.py +0 -317
  48. turbodesign/turbinespool.py +0 -543
@@ -0,0 +1,837 @@
1
+ # type: ignore[arg-type, reportUnknownArgumentType]
2
+ from __future__ import annotations
3
+ from turtle import down, up
4
+ from typing import Dict, List, Union, Optional, Tuple
5
+ import json
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+ import matplotlib.pyplot as plt
10
+
11
+ from cantera.composite import Solution
12
+ from scipy.interpolate import interp1d
13
+ from scipy.optimize import minimize_scalar
14
+
15
+ # --- Project-local imports
16
+ from .bladerow import BladeRow, interpolate_streamline_quantities
17
+ from .enums import RowType, LossType
18
+ from .loss.turbine import TD2
19
+ from .passage import Passage
20
+ from .inlet import Inlet
21
+ from .outlet import Outlet, OutletType
22
+ from .compressor_math import rotor_calc, stator_calc, polytropic_efficiency
23
+ from .flow_math import compute_massflow, compute_streamline_areas, compute_power
24
+ from .turbine_math import (
25
+ inlet_calc,
26
+ compute_gas_constants,
27
+ compute_reynolds,
28
+ )
29
+ from .solve_radeq import adjust_streamlines, radeq
30
+ from pyturbo.helper import convert_to_ndarray
31
+
32
+ # Default fraction of the stator-to-stator pressure rise attributed to a rotor
33
+ DEFAULT_ROTOR_PRESSURE_FRACTION = 0.5
34
+
35
+ class CompressorSpool:
36
+ """Used to design compressors
37
+
38
+ This class (formerly named *Spool*) encapsulates both the generic geometry/plotting
39
+ utilities from the original base spool and the turbine-solving logic that lived
40
+ in the turbine-specific spool implementation.
41
+
42
+ Notes on differences vs. the two-class design:
43
+ - `field(default_factory=...)` was previously used on a non-dataclass attribute
44
+ (`t_streamline`). Here it's handled in `__init__` to avoid a silent bug.
45
+ - `fluid` defaults to `Solution('air.yaml')` if not provided.
46
+ - All turbine-specific methods (initialize/solve/massflow balancing/etc.) are
47
+ preserved here. If you ever add a *CompressorSpool* in the future, consider
48
+ splitting turbine/compressor behaviors behind a strategy/solver object.
49
+ """
50
+
51
+ # Class-level defaults (avoid mutable defaults here!)
52
+ rows: List[BladeRow]
53
+ massflow: float
54
+ rpm: float
55
+
56
+ # Types/attributes documented for linters; values set in __init__
57
+ passage: Passage
58
+ t_streamline: npt.NDArray
59
+ num_streamlines: int
60
+
61
+ _fluid: Solution
62
+ _adjust_streamlines: bool
63
+
64
+ def __init__(
65
+ self,
66
+ passage: Passage,
67
+ massflow: float,
68
+ inlet: Inlet,
69
+ outlet: Outlet,
70
+ rows: List[BladeRow],
71
+ num_streamlines: int = 3,
72
+ fluid: Optional[Solution] = None,
73
+ rpm: float = -1,
74
+ rotor_pressure_fraction: float = DEFAULT_ROTOR_PRESSURE_FRACTION,
75
+ ) -> None:
76
+ """Initialize a compressor spool
77
+
78
+ Args:
79
+ passage: Passage defining hub and shroud
80
+ massflow: massflow at spool inlet
81
+ inlet: Inlet object
82
+ outlet: Outlet object
83
+ rows: List of blade rows between inlet and outlet
84
+ num_streamlines: number of streamlines used through the meridional passage
85
+ fluid: cantera gas solution; defaults to air.yaml if None
86
+ rpm: RPM for the entire spool. Individual rows can override later.
87
+ rotor_pressure_fraction: Fraction of total pressure rise in rotors (0.0 to 1.0)
88
+ """
89
+ self.passage = passage
90
+ self.massflow = massflow
91
+ self.inlet = inlet
92
+ self.outlet = outlet
93
+ self.rows = rows
94
+ self.num_streamlines = num_streamlines
95
+ self._fluid = fluid if fluid is not None else Solution("air.yaml")
96
+ self.rpm = rpm
97
+ self.rotor_pressure_fraction = float(np.clip(rotor_pressure_fraction, 0.0, 1.0))
98
+
99
+ # Previously this used dataclasses.field on a non-dataclass; do it explicitly
100
+ self.t_streamline = np.zeros((10,), dtype=float)
101
+ self._adjust_streamlines = True
102
+
103
+ # Assign IDs, RPMs, and axial chords where appropriate
104
+ for i, br in enumerate(self._all_rows()):
105
+ br.id = i
106
+ if not isinstance(br, (Outlet)):
107
+ br.rpm = rpm
108
+ br.axial_chord = br.hub_location * self.passage.hub_length
109
+ # Freeze any configured P0_ratio targets for later use (diagnostics may overwrite P0_ratio).
110
+ if getattr(br, "P0_ratio_target", 0.0) == 0 and getattr(br, "P0_ratio", 0.0) != 0:
111
+ br.P0_ratio_target = br.P0_ratio
112
+ if isinstance(br, BladeRow) and br.row_type == RowType.Rotor:
113
+ setattr(br, "rotor_pressure_fraction", getattr(br, "rotor_pressure_fraction", self.rotor_pressure_fraction))
114
+
115
+ # Propagate initial fluid to rows
116
+ for br in self._all_rows():
117
+ br.fluid = self._fluid
118
+
119
+ def _all_rows(self) -> List[BladeRow]:
120
+ """Convenience to iterate inlet + interior rows + outlet."""
121
+ return [self.inlet, *self.rows, self.outlet]
122
+
123
+ @property
124
+ def blade_rows(self) -> List[BladeRow]:
125
+ """Backwards-compatible combined row list."""
126
+ return self._all_rows()
127
+
128
+ def set_rotor_pressure_fraction(self, value: float) -> None:
129
+ """Update default pressure split fraction for all rotor rows."""
130
+ self.rotor_pressure_fraction = float(np.clip(value, 0.0, 1.0))
131
+ for row in self.rows:
132
+ if row.row_type == RowType.Rotor:
133
+ setattr(row, "rotor_pressure_fraction", self.rotor_pressure_fraction)
134
+
135
+ # ------------------------------
136
+ # Properties
137
+ # ------------------------------
138
+ @property
139
+ def fluid(self) -> Optional[Solution]:
140
+ return self._fluid
141
+
142
+ @fluid.setter
143
+ def fluid(self, newFluid: Solution) -> None:
144
+ """Change the gas used in the spool and cascade to rows."""
145
+ self._fluid = newFluid
146
+ for br in self._all_rows():
147
+ br.fluid = self._fluid
148
+
149
+ @property
150
+ def adjust_streamlines(self) -> bool:
151
+ return self._adjust_streamlines
152
+
153
+ @adjust_streamlines.setter
154
+ def adjust_streamlines(self, val: bool) -> None:
155
+ self._adjust_streamlines = val
156
+
157
+ # ------------------------------
158
+ # Row utilities
159
+ # ------------------------------
160
+ def set_blade_row_rpm(self, index: int, rpm: float) -> None:
161
+ self.rows[index].rpm = rpm
162
+
163
+ def set_blade_row_type(self, blade_row_index: int, rowType: RowType) -> None:
164
+ self.rows[blade_row_index].row_type = rowType
165
+
166
+ def set_blade_row_exit_angles(
167
+ self,
168
+ radius: Dict[int, List[float]],
169
+ beta: Dict[int, List[float]],
170
+ IsSupersonic: bool = False,
171
+ ) -> None:
172
+ """Set intended exit flow angles for rows (useful when geometry is fixed)."""
173
+ for k, v in radius.items():
174
+ self.rows[k].radii_geom = v
175
+ for k, v in beta.items():
176
+ self.rows[k].beta_geom = v
177
+ self.rows[k].beta_fixed = True
178
+ for br in self._all_rows():
179
+ br.solution_type = "supersonic" if IsSupersonic else "subsonic"
180
+
181
+ # ------------------------------
182
+ # Streamline setup/geometry
183
+ # ------------------------------
184
+ def initialize_streamlines(self) -> None:
185
+ """Initialize streamline storage per row and compute curvature."""
186
+ for row in self._all_rows():
187
+ row.phi = np.zeros((self.num_streamlines,))
188
+ row.rm = np.zeros((self.num_streamlines,))
189
+ row.r = np.zeros((self.num_streamlines,))
190
+ row.m = np.zeros((self.num_streamlines,))
191
+
192
+ t_radial = np.array([0.5]) if self.num_streamlines == 1 else np.linspace(0, 1, self.num_streamlines)
193
+ self.calculate_streamline_curvature(row, t_radial)
194
+
195
+ if self.num_streamlines == 1:
196
+ area = self.passage.get_area(row.hub_location)
197
+ row.total_area = area
198
+ row.area = np.array([area])
199
+
200
+ # Ensure a loss model exists on blade rows
201
+ if not isinstance(row, (Inlet, Outlet)) and row.loss_function is None:
202
+ row.loss_function = TD2()
203
+
204
+ # With radii known, couple blade geometry (pitch/chord/stagger) if specified
205
+ for row in self._all_rows():
206
+ if isinstance(row, BladeRow) and row.row_type not in (RowType.Inlet, RowType.Outlet):
207
+ try:
208
+ row.synchronize_blade_geometry()
209
+ except Exception:
210
+ pass
211
+
212
+ def calculate_streamline_curvature(
213
+ self, row: BladeRow, t_radial: Union[List[float], npt.NDArray]
214
+ ) -> None:
215
+ """Interpolate passage curvature metrics onto a blade row.
216
+
217
+ Args:
218
+ row: BladeRow to populate with phi, rm, r, and m along streamlines.
219
+ t_radial: Parametric hub-to-shroud locations (0–1) at which to sample curvature.
220
+ """
221
+ for i, tr in enumerate(t_radial):
222
+ t_s, x_s, r_s = self.passage.get_streamline(tr)
223
+ phi, rm, r = self.passage.streamline_curvature(x_s, r_s)
224
+ row.phi[i] = float(interp1d(t_s, phi)(row.hub_location))
225
+ row.rm[i] = float(interp1d(t_s, rm)(row.hub_location))
226
+ row.r[i] = float(interp1d(t_s, r)(row.hub_location))
227
+ row.m[i] = float(
228
+ interp1d(t_s, self.passage.get_m(tr, resolution=len(t_s)))(row.hub_location)
229
+ )
230
+ chord = np.asarray(row.chord, dtype=float)
231
+ mean_chord = float(np.mean(chord)) if chord.size else 0.0
232
+ if row.num_blades and mean_chord != 0:
233
+ mean_r = float(np.mean(row.r))
234
+ pitch = 2 * np.pi * mean_r / row.num_blades
235
+ row.pitch_to_chord = pitch / mean_chord
236
+
237
+ # ------------------------------
238
+ # initialization/solve
239
+ # ------------------------------
240
+ def initialize(self) -> None:
241
+ """Initialize massflow and thermodynamic state through rows (compressor).
242
+
243
+ Sets inlet totals, interpolates geometry, propagates gas properties, and
244
+ runs per-row calcs to seed the solver.
245
+ """
246
+ rows = self._all_rows()
247
+
248
+ # Inlet
249
+ W0 = self.massflow
250
+ inlet: Inlet = self.inlet
251
+ if self.fluid:
252
+ inlet.__initialize_fluid__(self.fluid) # type: ignore[arg-type]
253
+ else:
254
+ inlet.__initialize_fluid__( # type: ignore[call-arg]
255
+ R=rows[1].R,
256
+ gamma=rows[1].gamma,
257
+ Cp=rows[1].Cp,
258
+ )
259
+
260
+ inlet.total_massflow = W0
261
+ inlet.total_massflow_no_coolant = W0
262
+ inlet.massflow = np.array([W0]) if self.num_streamlines == 1 else np.linspace(0, 1, self.num_streamlines) * W0
263
+
264
+ inlet.__interpolate_quantities__(self.num_streamlines) # type: ignore[attr-defined]
265
+ inlet.__initialize_velocity__(self.passage, self.num_streamlines) # type: ignore[attr-defined]
266
+ interpolate_streamline_quantities(inlet, self.passage, self.num_streamlines)
267
+
268
+ compute_gas_constants(inlet, self.fluid)
269
+ inlet_calc(inlet)
270
+
271
+ for row in rows:
272
+ interpolate_streamline_quantities(row, self.passage, self.num_streamlines)
273
+
274
+ # Pass T0, P0 to downstream rows
275
+ for i in range(1, len(rows) - 1):
276
+ upstream = rows[i - 1]
277
+ downstream = rows[i + 1] if i + 1 < len(rows) else None
278
+
279
+ row = rows[i]
280
+ if row.coolant is not None:
281
+ T0c = row.coolant.T0
282
+ P0c = row.coolant.P0
283
+ W0c = row.coolant.massflow_percentage * self.massflow
284
+ Cpc = row.coolant.Cp
285
+ else:
286
+ T0c = 100
287
+ P0c = 0
288
+ W0c = 0
289
+ Cpc = 0
290
+
291
+ T0 = upstream.T0
292
+ P0 = upstream.P0
293
+ Cp = upstream.Cp
294
+
295
+ T0 = (W0 * Cp * T0 + W0c * Cpc * T0c) / (Cpc * W0c + Cp * W0)
296
+ P0 = (W0 * Cp * P0 + W0c * Cpc * P0c) / (Cpc * W0c + Cp * W0)
297
+ Cp = (W0 * Cp + W0c * Cpc) / (W0c + W0) if (W0c + W0) != 0 else Cp
298
+
299
+ if row.row_type == RowType.Stator:
300
+ T0 = upstream.T0
301
+ else:
302
+ T0 = upstream.T0 - row.power / (Cp * (W0 + W0c))
303
+
304
+ W0 += W0c
305
+ row.T0 = T0
306
+ row.P0 = P0
307
+ row.Cp = Cp
308
+ row.total_massflow = W0
309
+ row.massflow = np.array([row.total_massflow]) if self.num_streamlines == 1 else np.linspace(0, 1, self.num_streamlines) * row.total_massflow
310
+
311
+ # Pass gas constants
312
+ row.rho = upstream.rho
313
+ row.gamma = upstream.gamma
314
+ row.R = upstream.R
315
+
316
+ total_area, streamline_area = compute_streamline_areas(row)
317
+ row.total_area = total_area
318
+ row.area = streamline_area
319
+ if row.row_type == RowType.Stator or row.row_type == RowType.IGV:
320
+ if row.row_type == RowType.IGV:
321
+ row.P0_is = upstream.P0
322
+ stator_calc(row, upstream, calculate_vm=True) # type: ignore[arg-type]
323
+ elif row.row_type == RowType.Rotor:
324
+ # Align rotor ideal P0 target with downstream stator if provided (stage-level target)
325
+ if downstream and downstream.row_type == RowType.Stator:
326
+ downstream.P0 = upstream.P0*downstream.P0_ratio
327
+ downstream.Yp = downstream.loss_function(row, upstream)
328
+ downstream.P0_is = downstream.P0 + downstream.Yp * (upstream.P0-upstream.P)
329
+ row.P0_ratio = downstream.P0_ratio
330
+ else:
331
+ row.P0 = row.P0_ratio * upstream.P0
332
+ rotor_calc(row, upstream,calculate_vm=True)
333
+ compute_power(row, upstream, is_compressor=True)
334
+
335
+ def solve(self) -> None:
336
+ """Run streamline initialization and solve the compressor flow field.
337
+
338
+ The solution method is determined by the outlet configuration:
339
+ - If outlet.outlet_type is massflow_static_pressure: use angle matching
340
+ - Otherwise: use pressure balance
341
+ """
342
+ self.initialize_streamlines()
343
+ self.initialize()
344
+
345
+ if self.outlet.outlet_type == OutletType.massflow_static_pressure:
346
+ print("Using angle matching mode: blade exit angles will be adjusted to match specified massflow")
347
+ self._angle_match()
348
+ else:
349
+ print("Using pressure balance mode: blade exit angles are fixed, total pressures will be adjusted")
350
+ self.balance_pressure()
351
+
352
+ def solve_angle_match(self) -> None:
353
+ """Explicit angle-matching solve by temporarily setting outlet type."""
354
+ prev_type = self.outlet.outlet_type
355
+ prev_massflow = getattr(self.outlet, 'total_massflow', None)
356
+ try:
357
+ if prev_massflow is None:
358
+ self.outlet.total_massflow = self.massflow
359
+ self.outlet.outlet_type = OutletType.massflow_static_pressure
360
+ self.solve()
361
+ finally:
362
+ self.outlet.outlet_type = prev_type
363
+ if prev_massflow is None and hasattr(self.outlet, 'total_massflow'):
364
+ delattr(self.outlet, 'total_massflow')
365
+
366
+ def solve_balance_pressure(self) -> None:
367
+ """Explicit pressure-balance solve by temporarily setting outlet type."""
368
+ prev_type = self.outlet.outlet_type
369
+ try:
370
+ self.outlet.outlet_type = OutletType.total_pressure
371
+ self.solve()
372
+ finally:
373
+ self.outlet.outlet_type = prev_type
374
+
375
+ def overall_pressure_ratio(self) -> float:
376
+ """Compute overall total pressure ratio (inlet to last internal row)."""
377
+ rows = self._all_rows()
378
+ if len(rows) < 2:
379
+ return 1.0
380
+ return float(np.mean(np.mean(rows[-2].P0 / self.inlet.P0) ))
381
+
382
+ def overall_polytropic_efficiency(self) -> float:
383
+ """Compute overall polytropic efficiency from inlet to last internal row."""
384
+ rows = self._all_rows()
385
+ if len(rows) < 2:
386
+ return 0.0
387
+ pi = float(np.mean(rows[-2].P0) / np.mean(self.inlet.P0))
388
+ tau = float(np.mean(rows[-2].T0)/np.mean(self.inlet.T0))
389
+ gamma = float(np.mean(self.inlet.gamma)) if hasattr(self.inlet, "gamma") else 1.4
390
+ if tau <= 0 or abs(np.log(tau)) < 1e-12 or pi <= 1.0:
391
+ return 0.0
392
+ return ((gamma - 1.0) / gamma) * np.log(pi) / np.log(tau)
393
+
394
+ def solve_massflow_for_pressure_ratio(self, target_pr: float, bounds: tuple[float, float], meanline: bool = False) -> tuple[float, float]:
395
+ """Solve inlet massflow to hit a target overall total-pressure ratio.
396
+
397
+ Args:
398
+ target_pr: desired overall P0 ratio (inlet / last internal row).
399
+ bounds: (lower, upper) bounds for massflow during search.
400
+ meanline: if True, force a single streamline and disable streamline adjustment.
401
+
402
+ Returns:
403
+ Tuple of (converged massflow, achieved pressure ratio).
404
+ """
405
+ if meanline:
406
+ self.num_streamlines = 1
407
+ self._adjust_streamlines = False
408
+
409
+ lower, upper = bounds
410
+ if lower <= 0 or upper <= 0 or lower >= upper:
411
+ raise ValueError("Massflow bounds must be positive and (lower < upper).")
412
+
413
+ def objective(mdot: float) -> float:
414
+ self.massflow = mdot
415
+ self.solve()
416
+ achieved = self.overall_pressure_ratio()
417
+ return (achieved - target_pr) ** 2
418
+
419
+ res = minimize_scalar(objective, bounds=bounds, method="bounded")
420
+ self.massflow = float(res.x)
421
+ self.solve()
422
+ achieved = self.overall_pressure_ratio()
423
+ return self.massflow, achieved
424
+
425
+ def balance_pressure(self) -> None:
426
+ """Balance Pressure assumes we know:
427
+ 1. The blade angles
428
+ 2. Total Pressure Ratio
429
+ 3. Massflow
430
+
431
+ We find the static pressures in between the blade rows such that massflow is balanced.
432
+ Implemented by marching rows (compressor mode) without guessing pressure ratios.
433
+ """
434
+ rows = self._all_rows()
435
+
436
+ print("Looping to converge massflow (compressor)")
437
+ loop_iter = 0
438
+ max_iter = 10
439
+ prev_err = 1e9
440
+ while loop_iter < max_iter:
441
+ for i in range(1, len(rows) - 1):
442
+ row = rows[i]
443
+ upstream = rows[i - 1]
444
+ downstream = rows[i + 1] if i + 1 < len(rows) else None
445
+
446
+ if row.row_type == RowType.Inlet:
447
+ row.Yp = 0
448
+ continue
449
+
450
+ if row.row_type == RowType.Rotor:
451
+ rotor_calc(row, upstream, calculate_vm=True)
452
+ if self.num_streamlines > 1:
453
+ row = radeq(row, upstream, downstream)
454
+ compute_gas_constants(row, self.fluid)
455
+ rotor_calc(row, upstream, calculate_vm=False)
456
+ elif row.row_type == RowType.Stator or row.row_type == RowType.IGV:
457
+ if row.row_type == RowType.IGV:
458
+ row.P0_is = upstream.P0
459
+ stator_calc(row, upstream, calculate_vm=True)
460
+ if self.num_streamlines > 1:
461
+ row = radeq(row, upstream, downstream)
462
+ compute_gas_constants(row, self.fluid)
463
+ stator_calc(row, upstream, calculate_vm=False)
464
+
465
+ compute_gas_constants(row, self.fluid)
466
+ compute_power(row, upstream, is_compressor=True)
467
+
468
+ target = rows[1].total_massflow_no_coolant
469
+ self.inlet.massflow = np.array([target]) if self.num_streamlines == 1 else np.linspace(0, 1, self.num_streamlines) * target
470
+ self.inlet.total_massflow_no_coolant = rows[1].total_massflow_no_coolant
471
+ self.inlet.total_massflow = rows[1].total_massflow_no_coolant
472
+ self.inlet.calculated_massflow = self.inlet.total_massflow_no_coolant
473
+ inlet_calc(self.inlet)
474
+
475
+ # if self.adjust_streamlines:
476
+ # adjust_streamlines(rows[:-1], self.passage, np.linspace(0, 1, self.num_streamlines))
477
+
478
+ self.outlet.transfer_quantities(rows[-2])
479
+ self.outlet.P = self.outlet.get_static_pressure(self.outlet.percent_hub_shroud)
480
+
481
+ err = self._massflow_std(rows[1:-1])
482
+ loop_iter += 1
483
+ print(f"Loop {loop_iter} massflow convergence error:{err}")
484
+
485
+ denom = max(err, 1e-6)
486
+ if abs((err - prev_err) / denom) <= 0.05:
487
+ break
488
+ prev_err = err
489
+
490
+ compute_reynolds(rows, self.passage)
491
+
492
+ @staticmethod
493
+ def _massflow_std(blade_rows: List[BladeRow]) -> float:
494
+ """Compute standard deviation of massflow across rows for diagnostics."""
495
+ totals = []
496
+ for row in blade_rows:
497
+ if hasattr(row, "total_massflow_no_coolant"):
498
+ totals.append(row.total_massflow_no_coolant)
499
+ elif len(getattr(row, "massflow", [])) > 0:
500
+ totals.append(row.massflow[-1])
501
+ return float(np.std(totals)) if totals else 0.0
502
+ # ------------------------------
503
+ # Massflow / angle matching
504
+ # ------------------------------
505
+ def _angle_match(self) -> None:
506
+ """Match massflow between streamtubes by tweaking exit angles."""
507
+ blade_rows = self._all_rows()
508
+ for _ in range(3):
509
+ for i, row in enumerate(blade_rows):
510
+ # Only adjust blade rows; skip inlet/outlet and other utility rows
511
+ if row.row_type not in (RowType.Rotor, RowType.Stator):
512
+ continue
513
+
514
+ upstream = blade_rows[i - 1] if i > 0 else blade_rows[i]
515
+ downstream = blade_rows[i + 1] if i < len(blade_rows) - 1 else None
516
+
517
+ if row.row_type == RowType.Stator:
518
+ bounds = [0, 80]
519
+ elif row.row_type == RowType.Rotor:
520
+ bounds = [-80, 0]
521
+ else:
522
+ bounds = [0, 0]
523
+
524
+ for j in range(1, self.num_streamlines):
525
+ res = minimize_scalar(
526
+ match_massflow_objective,
527
+ bounds=bounds,
528
+ args=(j, row, upstream, downstream, self.fluid),
529
+ tol=1e-3,
530
+ method="bounded",
531
+ )
532
+ if row.row_type == RowType.Rotor:
533
+ row.beta2[j] = np.radians(res.x)
534
+ row.beta2[0] = 1 / (len(row.beta2) - 1) * row.beta2[1:].sum()
535
+ elif row.row_type == RowType.Stator:
536
+ row.alpha2[j] = np.radians(res.x)
537
+ row.alpha2[0] = 1 / (len(row.alpha2) - 1) * row.alpha2[1:].sum()
538
+ compute_gas_constants(upstream, self.fluid)
539
+ compute_gas_constants(row, self.fluid)
540
+ compute_massflow(row)
541
+ compute_power(row, upstream, is_compressor=True)
542
+
543
+
544
+
545
+ # ------------------------------
546
+ # Export / Plotting
547
+ # ------------------------------
548
+ def export_properties(self, filename: str = "compressor_spool.json") -> None:
549
+ """Export compressor spool properties and blade row data to JSON file.
550
+
551
+ Exports comprehensive compressor design data including blade row properties,
552
+ streamline coordinates, efficiency metrics, pressure ratios, stage loading,
553
+ and power calculations for each stage. Useful for post-processing and result
554
+ archiving.
555
+
556
+ Args:
557
+ filename: Output JSON file path (default: "compressor_spool.json")
558
+
559
+ Returns:
560
+ None. Writes JSON file to specified path.
561
+
562
+ Example:
563
+ >>> spool.export_properties("r35_compressor_results.json")
564
+ """
565
+ blade_rows = self._all_rows()
566
+ blade_rows_out = []
567
+ degree_of_reaction = []
568
+ total_total_efficiency = []
569
+ total_static_efficiency = []
570
+ stage_loading = []
571
+ euler_power = []
572
+ enthalpy_power = []
573
+ x_streamline = np.zeros((self.num_streamlines, len(blade_rows)))
574
+ r_streamline = np.zeros((self.num_streamlines, len(blade_rows)))
575
+ massflow = []
576
+
577
+ for indx, row in enumerate(blade_rows):
578
+ blade_rows_out.append(row.to_dict())
579
+ if row.row_type == RowType.Rotor:
580
+ degree_of_reaction.append(
581
+ (
582
+ (blade_rows[indx - 1].P - row.P)
583
+ / (blade_rows[indx - 2].P - row.P)
584
+ ).mean()
585
+ )
586
+ total_total_efficiency.append(row.eta_total)
587
+ total_static_efficiency.append(row.eta_static)
588
+ stage_loading.append(row.stage_loading)
589
+ euler_power.append(row.euler_power)
590
+ enthalpy_power.append(row.power)
591
+ if row.row_type not in (RowType.Inlet, RowType.Outlet):
592
+ massflow.append(row.massflow[-1])
593
+
594
+ for j, p in enumerate(row.percent_hub_shroud):
595
+ t, x, r = self.passage.get_streamline(p)
596
+ x_streamline[j, indx] = float(interp1d(t, x)(row.percent_hub))
597
+ r_streamline[j, indx] = float(interp1d(t, r)(row.percent_hub))
598
+
599
+ Pratio_Total_Total = np.mean(self.inlet.P0 / blade_rows[-2].P0)
600
+ Pratio_Total_Static = np.mean(self.inlet.P0 / blade_rows[-2].P)
601
+ flow_fn_massflow = float(np.mean(massflow)) if massflow else 0.0
602
+ FlowFunction = flow_fn_massflow * np.sqrt(self.inlet.T0.mean()) * float(np.mean(self.inlet.P0)) / 1000
603
+ CorrectedSpeed = self.rpm * np.pi / 30 / np.sqrt(self.inlet.T0.mean())
604
+ EnergyFunction = (
605
+ (self.inlet.T0 - blade_rows[-2].T0)
606
+ * 0.5
607
+ * (self.inlet.Cp + blade_rows[-2].Cp)
608
+ / self.inlet.T0
609
+ )
610
+ EnergyFunction = np.mean(EnergyFunction)
611
+
612
+ # English-unit conversions
613
+ massflow_kg_s = float(np.mean(massflow)) if massflow else 0.0
614
+ massflow_lbm_s = massflow_kg_s / 0.45359237
615
+ euler_power_hp = [p / 745.7 for p in euler_power]
616
+ enthalpy_power_hp = [p / 745.7 for p in enthalpy_power]
617
+
618
+ data = {
619
+ "blade_rows": blade_rows_out,
620
+ "massflow": massflow_kg_s,
621
+ "massflow_lbm_s": massflow_lbm_s,
622
+ "rpm": self.rpm,
623
+ "r_streamline": r_streamline.tolist(),
624
+ "x_streamline": x_streamline.tolist(),
625
+ "rhub": self.passage.rhub_pts.tolist(),
626
+ "rshroud": self.passage.rshroud_pts.tolist(),
627
+ "xhub": self.passage.xhub_pts.tolist(),
628
+ "xshroud": self.passage.xshroud_pts.tolist(),
629
+ "num_streamlines": self.num_streamlines,
630
+ "euler_power": euler_power,
631
+ "euler_power_hp": euler_power_hp,
632
+ "enthalpy_power": enthalpy_power,
633
+ "enthalpy_power_hp": enthalpy_power_hp,
634
+ "total-total_efficiency": total_total_efficiency,
635
+ "total-static_efficiency": total_static_efficiency,
636
+ "stage_loading": stage_loading,
637
+ "degree_of_reaction": degree_of_reaction,
638
+ "Pratio_Total_Total": float(Pratio_Total_Total),
639
+ "Pratio_Total_Static": float(Pratio_Total_Static),
640
+ "FlowFunction": float(FlowFunction),
641
+ "CorrectedSpeed": float(CorrectedSpeed),
642
+ "EnergyFunction": float(EnergyFunction),
643
+ "eta_polytropic_overall": float(self.overall_polytropic_efficiency()),
644
+ "units": {
645
+ "massflow": {"metric": "kg/s", "english": "lbm/s"},
646
+ "rpm": {"metric": "rpm", "english": "rpm"},
647
+ "euler_power": {"metric": "W", "english": "hp"},
648
+ "enthalpy_power": {"metric": "W", "english": "hp"},
649
+ "Pratio_Total_Total": {"metric": "—", "english": "—"},
650
+ "Pratio_Total_Static": {"metric": "—", "english": "—"},
651
+ "FlowFunction": {"metric": "kg/s·K^0.5·Pa", "english": "lbm/s·R^0.5·psf"},
652
+ "CorrectedSpeed": {"metric": "rad/s·K^-0.5", "english": "rad/s·R^-0.5"},
653
+ "EnergyFunction": {"metric": "—", "english": "—"},
654
+ },
655
+ }
656
+
657
+ class NumpyEncoder(json.JSONEncoder):
658
+ def default(self, obj): # type: ignore[override]
659
+ if isinstance(obj, np.ndarray):
660
+ return obj.tolist()
661
+ return super().default(obj)
662
+
663
+ with open(filename, "w") as f:
664
+ json.dump(data, f, indent=4, cls=NumpyEncoder)
665
+
666
+ def plot(self) -> None:
667
+ """Plot hub/shroud and streamlines."""
668
+ blade_rows = self._all_rows()
669
+ plt.figure(num=1, clear=True, dpi=150, figsize=(15, 10))
670
+ plt.plot(
671
+ self.passage.xhub_pts,
672
+ self.passage.rhub_pts,
673
+ label="hub",
674
+ linestyle="solid",
675
+ linewidth=2,
676
+ color="black",
677
+ )
678
+ plt.plot(
679
+ self.passage.xshroud_pts,
680
+ self.passage.rshroud_pts,
681
+ label="shroud",
682
+ linestyle="solid",
683
+ linewidth=2,
684
+ color="black",
685
+ )
686
+
687
+ hub_length = np.sum(
688
+ np.sqrt(np.diff(self.passage.xhub_pts) ** 2 + np.diff(self.passage.rhub_pts) ** 2)
689
+ )
690
+ x_streamline = np.zeros((self.num_streamlines, len(self.blade_rows)))
691
+ r_streamline = np.zeros((self.num_streamlines, len(self.blade_rows)))
692
+ for i in range(len(blade_rows)):
693
+ x_streamline[:, i] = blade_rows[i].x
694
+ r_streamline[:, i] = blade_rows[i].r
695
+
696
+ for i in range(1, len(blade_rows) - 1):
697
+ plt.plot(x_streamline[:, i], r_streamline[:, i], "--b", linewidth=1.5)
698
+
699
+ for i, row in enumerate(blade_rows):
700
+ plt.plot(row.x, row.r, linestyle="dashed", linewidth=1.5, color="blue", alpha=0.4)
701
+ plt.plot(x_streamline[:, i], r_streamline[:, i], "or")
702
+
703
+ if i == 0:
704
+ pass
705
+ else:
706
+ upstream = blade_rows[i - 1]
707
+ if upstream.row_type == RowType.Inlet:
708
+ cut_line1, _, _ = self.passage.get_cutting_line(
709
+ (row.hub_location * hub_length + (0.5 * row.blade_to_blade_gap * row.axial_chord) - row.axial_chord)
710
+ / hub_length
711
+ )
712
+ else:
713
+ cut_line1, _, _ = self.passage.get_cutting_line(
714
+ (upstream.hub_location * hub_length) / hub_length
715
+ )
716
+ cut_line2, _, _ = self.passage.get_cutting_line(
717
+ (row.hub_location * hub_length - (0.5 * row.blade_to_blade_gap * row.axial_chord)) / hub_length
718
+ )
719
+
720
+ if row.row_type == RowType.Stator:
721
+ x1, r1 = cut_line1.get_point(np.linspace(0, 1, 10))
722
+ plt.plot(x1, r1, "m")
723
+ x2, r2 = cut_line2.get_point(np.linspace(0, 1, 10))
724
+ plt.plot(x2, r2, "m")
725
+ x_text = (x1 + x2) / 2
726
+ r_text = (r1 + r2) / 2
727
+ plt.text(x_text.mean(), r_text.mean(), "Stator", fontdict={"fontsize": "xx-large"})
728
+ elif row.row_type == RowType.Rotor:
729
+ x1, r1 = cut_line1.get_point(np.linspace(0, 1, 10))
730
+ plt.plot(x1, r1, color="brown")
731
+ x2, r2 = cut_line2.get_point(np.linspace(0, 1, 10))
732
+ plt.plot(x2, r2, color="brown")
733
+ x_text = (x1 + x2) / 2
734
+ r_text = (r1 + r2) / 2
735
+ plt.text(x_text.mean(), r_text.mean(), "Rotor", fontdict={"fontsize": "xx-large"})
736
+
737
+ plt.axis("scaled")
738
+ plt.savefig("Meridional.png", transparent=False, dpi=150)
739
+ plt.show()
740
+
741
+ def plot_velocity_triangles(self) -> None:
742
+ """Plot velocity triangles for each blade row (turbines).
743
+ """
744
+ blade_rows = self._all_rows()
745
+ prop = dict(arrowstyle="-|>,head_width=0.4,head_length=0.8", shrinkA=0, shrinkB=0)
746
+
747
+ for j in range(self.num_streamlines):
748
+ x_start = 0.0
749
+ y_max = 0.0
750
+ y_min = 0.0
751
+ plt.figure(num=1, clear=True)
752
+ for i in range(1, len(blade_rows) - 1):
753
+ row = blade_rows[i]
754
+ x_end = x_start + row.Vm.mean()
755
+ dx = x_end - x_start
756
+
757
+ Vt = row.Vt[j]
758
+ Wt = row.Wt[j]
759
+ U = row.U[j]
760
+
761
+ y_max = max(y_max, Vt, Wt)
762
+ y_min = min(y_min, Vt, Wt)
763
+
764
+ # V
765
+ plt.annotate("", xy=(x_end, Vt), xytext=(x_start, 0), arrowprops=prop)
766
+ plt.text((x_start + x_end) / 2, Vt / 2 * 1.1, "V", fontdict={"fontsize": "xx-large"})
767
+
768
+ # W
769
+ plt.annotate("", xy=(x_end, Wt), xytext=(x_start, 0), arrowprops=prop)
770
+ plt.text((x_start + x_end) / 2, Wt / 2 * 1.1, "W", fontdict={"fontsize": "xx-large"})
771
+
772
+ if abs(Vt) > abs(Wt):
773
+ plt.annotate("", xy=(x_end, Wt), xytext=(x_end, 0), arrowprops=prop) # Wt
774
+ plt.text(x_end + dx * 0.1, Wt / 2, "Wt", fontdict={"fontsize": "xx-large"})
775
+
776
+ plt.annotate("", xy=(x_end, U + Wt), xytext=(x_end, Wt), arrowprops=prop) # U
777
+ plt.text(x_end + dx * 0.1, (Wt + U) / 2, "U", fontdict={"fontsize": "xx-large"})
778
+ else:
779
+ plt.annotate("", xy=(x_end, Vt), xytext=(x_end, 0), arrowprops=prop) # Vt
780
+ plt.text(x_end + dx * 0.1, Vt / 2, "Vt", fontdict={"fontsize": "xx-large"})
781
+
782
+ plt.annotate("", xy=(x_end, Wt + U), xytext=(x_end, Wt), arrowprops=prop) # U
783
+ plt.text(x_end + dx * 0.1, Wt + U / 2, "U", fontdict={"fontsize": "xx-large"})
784
+
785
+ y = y_min if -np.sign(Vt) > 0 else y_max
786
+ plt.text((x_start + x_end) / 2, -np.sign(Vt) * y * 0.95, row.row_type.name, fontdict={"fontsize": "xx-large"})
787
+ x_start += row.Vm[j]
788
+ plt.axis([0, x_end + dx, y_min, y_max])
789
+ plt.ylabel("Tangental Velocity [m/s]")
790
+ plt.xlabel("Vm [m/s]")
791
+ plt.title(f"Velocity Triangles for Streamline {j}")
792
+ plt.savefig(f"streamline_{j:04d}.png", transparent=False, dpi=150)
793
+
794
+
795
+ def outlet_pressure(percents: List[float], inletP0: float, outletP: float) -> npt.NDArray:
796
+ """Linearly interpolate total pressure values along the spool."""
797
+ percents_arr = convert_to_ndarray(percents)
798
+ return inletP0 + (outletP - inletP0) * percents_arr
799
+
800
+
801
+ def match_massflow_objective(exit_angle: float, index: int, row: BladeRow, upstream: BladeRow, downstream: Optional[BladeRow] = None, fluid: Optional[Solution] = None) -> float:
802
+ """Objective for adjusting exit angle to match a target massflow slice."""
803
+ if row.row_type not in (RowType.Rotor, RowType.Stator):
804
+ return 0.0
805
+
806
+ lt = getattr(row, "loss_function", None)
807
+ loss_type = getattr(lt, "loss_type", None)
808
+
809
+ if loss_type == LossType.Pressure and callable(lt):
810
+ row.Yp = lt(row, upstream) # type: ignore[arg-type]
811
+
812
+ if row.row_type == RowType.Rotor:
813
+ row.beta2[index] = np.radians(exit_angle)
814
+ rotor_calc(row, upstream)
815
+ elif row.row_type == RowType.Stator:
816
+ row.alpha2[index] = np.radians(exit_angle)
817
+ stator_calc(row, upstream)
818
+
819
+ if fluid is not None:
820
+ compute_gas_constants(upstream, fluid)
821
+ compute_gas_constants(row, fluid)
822
+
823
+ compute_massflow(row)
824
+ compute_power(row, upstream)
825
+
826
+ # drive radial distribution of massflow linearly by index using upstream total as target
827
+ target_total = None
828
+ for candidate in ("total_massflow_no_coolant", "total_massflow"):
829
+ val = getattr(upstream, candidate, None)
830
+ if val is not None and val != 0:
831
+ target_total = val
832
+ break
833
+ if target_total is None:
834
+ target_total = row.total_massflow if getattr(row, "total_massflow", 0) != 0 else row.massflow[-1]
835
+
836
+ target = target_total * index / max(len(row.massflow) - 1, 1)
837
+ return float(np.abs(target - row.massflow[index]))