blocksim 0.1.0__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.
blocksim/atmosphere.py ADDED
@@ -0,0 +1,150 @@
1
+ """
2
+ The standard atmosphere: one implementation, in both unit systems.
3
+
4
+ Three atmospheres had grown up in the library and they disagreed. The
5
+ two-layer fit in `aerospace` stopped at 20 km; the layered ISA inside
6
+ `propulsion.FlightCondition` ran to 47 km; and at 15 km they differed
7
+ by 9% in density -- enough that the answer depended on which module you
8
+ happened to import. This is the layered one, lifted out.
9
+
10
+ T, p, rho, a = standard_atmosphere(altitude_m)
11
+
12
+ The 1976 US Standard Atmosphere as a stack of layers, each with a base
13
+ altitude, a base temperature and a lapse rate. Pressure integrates
14
+ hydrostatically through them: a linear-lapse layer gives a power law, an
15
+ isothermal one an exponential. That is the whole model, and carrying it
16
+ properly rather than fitting a curve through it is what makes it right
17
+ above the tropopause.
18
+
19
+ `dT` offsets the temperature column without touching the pressure
20
+ column, which is the standard convention for a hot or cold day: ISA+15
21
+ is a rating point, not a different atmosphere.
22
+
23
+ What this is *not*
24
+ ------------------
25
+ `f16.atmosphere_imperial` stays where it is and is not routed through
26
+ here. It is the fit Stevens & Lewis publish with the F-16 model --
27
+ temperature frozen above 35,000 ft, density from a single power law --
28
+ and reproducing their numbers is the point of that model. Replacing its
29
+ atmosphere would make the F-16 more correct and less faithful, which is
30
+ the wrong trade for a reference implementation.
31
+
32
+ `astro.ExponentialAtmosphere` also stays: a single scale height above
33
+ 200 km is a different model for a different job, and the ISA does not
34
+ reach there anyway.
35
+ """
36
+
37
+ import numpy as np
38
+
39
+ __all__ = [
40
+ "GAMMA_AIR",
41
+ "P_SEA_LEVEL",
42
+ "R_AIR",
43
+ "T_SEA_LEVEL",
44
+ "density_slug_ft3",
45
+ "standard_atmosphere",
46
+ "standard_atmosphere_imperial",
47
+ ]
48
+
49
+ #: sea-level static pressure, Pa, and temperature, K
50
+ #: Reference sea-level pressure in Pa.
51
+ P_SEA_LEVEL = 101325.0
52
+ #: Reference sea-level temperature in K.
53
+ T_SEA_LEVEL = 288.15
54
+ #: specific gas constant for dry air, J/(kg K), and its ratio of heats
55
+ #: Specific gas constant of air in J/(kg K).
56
+ R_AIR = 287.05287
57
+ #: Ratio of specific heats for air (dimensionless).
58
+ GAMMA_AIR = 1.4
59
+
60
+ _G = 9.80665
61
+
62
+ #: (base altitude m, base temperature K, lapse rate K/m) per layer,
63
+ #: from the 1976 US Standard Atmosphere. The base temperatures are the
64
+ #: ones the lapse rates imply, so the column is continuous.
65
+ LAYERS = (
66
+ (0.0, 288.15, -0.0065), # troposphere
67
+ (11000.0, 216.65, 0.0), # tropopause
68
+ (20000.0, 216.65, 0.001), # lower stratosphere
69
+ (32000.0, 228.65, 0.0028), # upper stratosphere
70
+ (47000.0, 270.65, 0.0), # stratopause
71
+ )
72
+ #: the model is not carried past here
73
+ CEILING_M = 51000.0
74
+
75
+ FT_PER_M = 1.0 / 0.3048
76
+ SLUG_FT3_PER_KG_M3 = 1.0 / 515.378818393
77
+ PSF_PER_PA = 1.0 / 47.880259
78
+
79
+
80
+ def standard_atmosphere(altitude_m, dT=0.0):
81
+ """(temperature K, pressure Pa, density kg/m^3, speed of sound m/s).
82
+
83
+ `altitude_m` is **geopotential** altitude, which is the coordinate a
84
+ layer table is written in: it is the one where gravity is constant,
85
+ and that is what makes the power law within a layer exact rather
86
+ than fitted. Geometric altitude is larger -- by 19 m at 11 km, 345 m
87
+ at 47 km -- and passing it here instead moves every layer boundary
88
+ and costs about 5% in density near the stratopause. Libraries that
89
+ take geometric altitude, `ambiance` among them, convert internally
90
+ and usually expose the converted value; `examples/atmosphere` checks
91
+ this column against one of them and measures what the mix-up costs.
92
+
93
+ `dT` shifts the temperature -- and through it the density and the
94
+ speed of sound -- while the pressure column stays standard, which is
95
+ what a "hot day" rating means.
96
+
97
+ Below sea level and above `CEILING_M` the altitude is clamped: the
98
+ model has nothing to say there, and extrapolating a lapse rate into
99
+ the mesosphere would produce numbers rather than an answer.
100
+ """
101
+ altitude = float(np.clip(altitude_m, 0.0, CEILING_M))
102
+
103
+ pressure = P_SEA_LEVEL
104
+ temperature = T_SEA_LEVEL
105
+ for index, (base, base_temperature, lapse) in enumerate(LAYERS):
106
+ top = LAYERS[index + 1][0] if index + 1 < len(LAYERS) else CEILING_M
107
+ height = min(altitude, top) - base
108
+ if height > 0.0:
109
+ if lapse == 0.0:
110
+ pressure *= np.exp(-_G * height / (R_AIR * base_temperature))
111
+ else:
112
+ pressure *= (1.0 + lapse * height / base_temperature) ** (
113
+ -_G / (lapse * R_AIR)
114
+ )
115
+ if altitude <= top:
116
+ temperature = base_temperature + lapse * max(height, 0.0)
117
+ break
118
+
119
+ temperature += dT
120
+ density = pressure / (R_AIR * temperature)
121
+ return (
122
+ temperature,
123
+ pressure,
124
+ density,
125
+ float(np.sqrt(GAMMA_AIR * R_AIR * temperature)),
126
+ )
127
+
128
+
129
+ def standard_atmosphere_imperial(altitude_ft, dT=0.0):
130
+ """The same column in (Rankine, psf, slug/ft^3, ft/s).
131
+
132
+ `altitude_ft` is geopotential feet, for the same reason as above.
133
+
134
+ For an aerodynamic deck written in imperial units -- which is most
135
+ of them -- rather than making every caller carry its own conversions.
136
+ """
137
+ temperature, pressure, density, speed = standard_atmosphere(
138
+ float(altitude_ft) / FT_PER_M, dT=dT
139
+ )
140
+ return (
141
+ temperature * 1.8,
142
+ pressure * PSF_PER_PA,
143
+ density * SLUG_FT3_PER_KG_M3,
144
+ speed * FT_PER_M,
145
+ )
146
+
147
+
148
+ def density_slug_ft3(altitude_ft, dT=0.0):
149
+ """Density alone, imperial -- the one an aero deck asks for most."""
150
+ return standard_atmosphere_imperial(altitude_ft, dT=dT)[2]
blocksim/auxiliar.py ADDED
@@ -0,0 +1,218 @@
1
+ import numpy as np
2
+
3
+ __all__ = ["check_signal_similarity", "check_signal_similirarity2"]
4
+
5
+
6
+ def check_signal_similarity(t1, y1, t2, y2, rtol=1e-5, atol=1e-8):
7
+ """
8
+ Compares two time-series signals to determine if they are similar within a tolerance.
9
+ Interpolates y2 onto the timebase of t1 for accurate point-by-point comparison.
10
+
11
+ Args:
12
+ t1 (array_like): Time array for the first signal.
13
+ y1 (array_like): Data array for the first signal.
14
+ t2 (array_like): Time array for the second signal.
15
+ y2 (array_like): Data array for the second signal.
16
+ rtol (float): Relative tolerance parameter (default: 1e-5).
17
+ atol (float): Absolute tolerance parameter (default: 1e-8).
18
+
19
+ Returns:
20
+ bool: True if the signals are similar, False otherwise.
21
+ """
22
+ t1, y1 = np.asarray(t1), np.asarray(y1)
23
+ t2, y2 = np.asarray(t2), np.asarray(y2)
24
+
25
+ # Handle 2D signals from SimulationResult (shape (1, N) or (n_signals, N))
26
+ # by squeezing any singleton signal dimension, but keep at least 1D.
27
+ if y1.ndim > 1 and y1.shape[0] == 1:
28
+ y1 = np.squeeze(y1, axis=0)
29
+ if y2.ndim > 1 and y2.shape[0] == 1:
30
+ y2 = np.squeeze(y2, axis=0)
31
+
32
+ # 1. Find the overlapping time window
33
+ t_start = max(t1[0], t2[0])
34
+ t_end = min(t1[-1], t2[-1])
35
+
36
+ if t_start >= t_end:
37
+ raise ValueError("The two signals have no overlapping time regions to compare.")
38
+
39
+ # 2. Extract the points of signal 1 that fall within the overlapping window
40
+ mask = (t1 >= t_start) & (t1 <= t_end)
41
+ t_common = t1[mask]
42
+ y1_common = y1[..., mask]
43
+
44
+ # 3. Interpolate signal 2 onto the common timebase
45
+ # np.interp performs fast linear interpolation for 1D arrays;
46
+ # for multidimensional arrays, interpolate row-by-row.
47
+ if y2.ndim == 1:
48
+ y2_interp = np.interp(t_common, t2, y2)
49
+ else:
50
+ flat_y2 = y2.reshape((-1, y2.shape[-1]))
51
+ interpolated = np.vstack([np.interp(t_common, t2, row) for row in flat_y2])
52
+ y2_interp = interpolated.reshape(y2.shape[:-1] + (len(t_common),))
53
+
54
+ # 4. Compare the arrays using numpy's built-in floating point comparison
55
+ # Equation used by allclose: absolute(a - b) <= (atol + rtol * absolute(b))
56
+ return bool(np.allclose(y1_common, y2_interp, rtol=rtol, atol=atol))
57
+
58
+
59
+ def check_signal_similirarity2(
60
+ t1,
61
+ y1,
62
+ t2,
63
+ y2,
64
+ *,
65
+ rtol=1e-5,
66
+ atol=1e-8,
67
+ time_tol=1e-9,
68
+ axis=-1,
69
+ duplicate="last",
70
+ ):
71
+ """
72
+ Compare two time signals y1(t1) and y2(t2).
73
+
74
+ Parameters
75
+ ----------
76
+ t1, t2:
77
+ 1D numpy arrays with sample times.
78
+
79
+ y1, y2:
80
+ Signal arrays. The time axis is given by `axis`.
81
+
82
+ Common shapes:
83
+ y.shape == (n_samples,)
84
+ y.shape == (n_signals, n_samples) with axis=-1
85
+ y.shape == (n_samples, n_signals) with axis=0
86
+
87
+ rtol, atol:
88
+ Relative and absolute value tolerances, same idea as np.allclose.
89
+
90
+ time_tol:
91
+ Tolerance used when checking start/end times and duplicate times.
92
+
93
+ axis:
94
+ Axis of y1/y2 corresponding to time.
95
+
96
+ duplicate:
97
+ How to handle repeated time samples:
98
+ "last" -> keep last sample at repeated time
99
+ "first" -> keep first sample at repeated time
100
+ "error" -> repeated times are invalid
101
+
102
+ For hybrid simulations with event resets, "last" is often useful
103
+ because t_event^- and t_event^+ may have the same timestamp.
104
+
105
+ Returns
106
+ -------
107
+ bool
108
+ True if the two signals are similar within tolerance.
109
+ """
110
+
111
+ t1, y1 = _prepare_time_signal(
112
+ t1, y1, axis=axis, duplicate=duplicate, time_tol=time_tol
113
+ )
114
+ t2, y2 = _prepare_time_signal(
115
+ t2, y2, axis=axis, duplicate=duplicate, time_tol=time_tol
116
+ )
117
+
118
+ if y1.shape[:-1] != y2.shape[:-1]:
119
+ return False
120
+
121
+ if len(t1) < 2 or len(t2) < 2:
122
+ return False
123
+
124
+ if not np.isclose(t1[0], t2[0], atol=time_tol, rtol=0.0):
125
+ return False
126
+
127
+ if not np.isclose(t1[-1], t2[-1], atol=time_tol, rtol=0.0):
128
+ return False
129
+
130
+ # Compare on the union of both time grids.
131
+ t_start = max(t1[0], t2[0])
132
+ t_end = min(t1[-1], t2[-1])
133
+
134
+ grid = np.union1d(t1, t2)
135
+ grid = grid[(grid >= t_start - time_tol) & (grid <= t_end + time_tol)]
136
+
137
+ y1i = _interp_signal(t1, y1, grid)
138
+ y2i = _interp_signal(t2, y2, grid)
139
+
140
+ return bool(np.allclose(y1i, y2i, rtol=rtol, atol=atol))
141
+
142
+
143
+ def _prepare_time_signal(t, y, *, axis, duplicate, time_tol):
144
+ t = np.asarray(t, dtype=float)
145
+ y = np.asarray(y, dtype=float)
146
+
147
+ if t.ndim != 1:
148
+ raise ValueError("time array must be 1D")
149
+
150
+ if y.shape[axis] != len(t):
151
+ raise ValueError(
152
+ f"time length {len(t)} does not match signal shape {y.shape} on axis {axis}"
153
+ )
154
+
155
+ if not np.all(np.isfinite(t)):
156
+ raise ValueError("time array contains NaN or Inf")
157
+
158
+ if not np.all(np.isfinite(y)):
159
+ raise ValueError("signal array contains NaN or Inf")
160
+
161
+ # Move time axis to the last axis.
162
+ y = np.moveaxis(y, axis, -1)
163
+
164
+ # Sort by time.
165
+ order = np.argsort(t)
166
+ t = t[order]
167
+ y = y[..., order]
168
+
169
+ # Collapse duplicate or almost-duplicate times.
170
+ t_new = []
171
+ y_new = []
172
+
173
+ i = 0
174
+ while i < len(t):
175
+ j = i + 1
176
+
177
+ while j < len(t) and abs(t[j] - t[i]) <= time_tol:
178
+ j += 1
179
+
180
+ if j - i > 1:
181
+ if duplicate == "error":
182
+ raise ValueError(f"duplicate time value near t={t[i]}")
183
+ elif duplicate == "first":
184
+ idx = i
185
+ elif duplicate == "last":
186
+ idx = j - 1
187
+ else:
188
+ raise ValueError("duplicate must be 'last', 'first', or 'error'")
189
+ else:
190
+ idx = i
191
+
192
+ t_new.append(t[idx])
193
+ y_new.append(y[..., idx])
194
+ i = j
195
+
196
+ t = np.asarray(t_new)
197
+ y = np.stack(y_new, axis=-1)
198
+
199
+ if np.any(np.diff(t) <= 0):
200
+ raise ValueError(
201
+ "time array must be strictly increasing after duplicate handling"
202
+ )
203
+
204
+ return t, y
205
+
206
+
207
+ def _interp_signal(t, y, grid):
208
+ """
209
+ Interpolate a signal whose time axis is the last axis.
210
+ """
211
+ if y.ndim == 1:
212
+ return np.interp(grid, t, y)
213
+
214
+ flat = y.reshape((-1, y.shape[-1]))
215
+
216
+ interpolated = np.vstack([np.interp(grid, t, row) for row in flat])
217
+
218
+ return interpolated.reshape(y.shape[:-1] + (len(grid),))