dust-sctoolbox 0.0.1__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 dust-sctoolbox might be problematic. Click here for more details.
- dust_sctoolbox/SCanalysis.py +753 -0
- dust_sctoolbox/parsing.py +176 -0
- dust_sctoolbox/run_dust.py +39 -0
- dust_sctoolbox/run_sctoolbox.py +23 -0
- dust_sctoolbox/write_dust.py +1095 -0
- dust_sctoolbox-0.0.1.dist-info/METADATA +174 -0
- dust_sctoolbox-0.0.1.dist-info/RECORD +10 -0
- dust_sctoolbox-0.0.1.dist-info/WHEEL +5 -0
- dust_sctoolbox-0.0.1.dist-info/entry_points.txt +2 -0
- dust_sctoolbox-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import h5py
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .parsing import read_integral_loads
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def compute_motion_angle(time, analysis_type, ampl, omega, u_inf, alpha_0=0.0, beta_0=0.0):
|
|
11
|
+
"""Compute the aerodynamic angle history for a prescribed motion."""
|
|
12
|
+
phase = omega * time
|
|
13
|
+
alpha_0_rad = np.deg2rad(alpha_0)
|
|
14
|
+
beta_0_rad = np.deg2rad(beta_0)
|
|
15
|
+
|
|
16
|
+
if analysis_type == 'pitching':
|
|
17
|
+
angle = alpha_0_rad + ampl * np.sin(phase)
|
|
18
|
+
label = 'Pitch angle'
|
|
19
|
+
elif analysis_type == 'rolling':
|
|
20
|
+
angle = ampl * np.sin(phase)
|
|
21
|
+
label = 'Roll angle'
|
|
22
|
+
elif analysis_type == 'yawing':
|
|
23
|
+
angle = beta_0_rad + ampl * np.sin(phase)
|
|
24
|
+
label = 'Yaw angle'
|
|
25
|
+
elif analysis_type in ('plunging', 'lateral'):
|
|
26
|
+
if u_inf == 0:
|
|
27
|
+
raise ValueError(f"u_inf must be non-zero for {analysis_type} motion")
|
|
28
|
+
induced_velocity = ampl * omega * np.cos(phase)
|
|
29
|
+
mean_angle = alpha_0_rad if analysis_type == 'plunging' else beta_0_rad
|
|
30
|
+
angle = (
|
|
31
|
+
mean_angle - induced_velocity / u_inf
|
|
32
|
+
if analysis_type == 'plunging'
|
|
33
|
+
else mean_angle + induced_velocity / u_inf
|
|
34
|
+
)
|
|
35
|
+
label = 'Induced angle of attack' if analysis_type == 'plunging' else 'Induced sideslip angle'
|
|
36
|
+
elif analysis_type == 'phugoid':
|
|
37
|
+
if u_inf == 0:
|
|
38
|
+
raise ValueError("u_inf must be non-zero for phugoid motion")
|
|
39
|
+
angle_amplitude = ampl * omega / u_inf
|
|
40
|
+
angle = alpha_0_rad + angle_amplitude * np.sin(phase)
|
|
41
|
+
label = 'Pitch angle'
|
|
42
|
+
elif analysis_type == 'lateral_phugoid':
|
|
43
|
+
if u_inf == 0:
|
|
44
|
+
raise ValueError("u_inf must be non-zero for lateral_phugoid motion")
|
|
45
|
+
angle_amplitude = ampl * omega / u_inf
|
|
46
|
+
angle = beta_0_rad + angle_amplitude * np.sin(-phase)
|
|
47
|
+
label = 'Yaw angle'
|
|
48
|
+
else:
|
|
49
|
+
raise ValueError(f"Unsupported analysis_type for hysteresis plot: {analysis_type}")
|
|
50
|
+
|
|
51
|
+
return np.rad2deg(angle), label
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def motion_amplitude_rad(analysis_type, ampl, omega, u_inf):
|
|
55
|
+
"""Return the equivalent angular-motion amplitude in radians."""
|
|
56
|
+
if analysis_type in ('rolling', 'pitching', 'yawing'):
|
|
57
|
+
return abs(ampl)
|
|
58
|
+
if analysis_type in ('plunging', 'lateral', 'phugoid', 'lateral_phugoid'):
|
|
59
|
+
if u_inf <= 0:
|
|
60
|
+
raise ValueError(f"u_inf must be positive for {analysis_type} motion")
|
|
61
|
+
return abs(ampl * omega / u_inf)
|
|
62
|
+
raise ValueError(f"Unsupported analysis_type for stability derivatives: {analysis_type}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def motion_derivative_name(analysis_type):
|
|
66
|
+
"""Map a supported motion type to its stability-derivative variable."""
|
|
67
|
+
derivative_names = {
|
|
68
|
+
'rolling': 'p',
|
|
69
|
+
'pitching': 'q',
|
|
70
|
+
'yawing': 'r',
|
|
71
|
+
'phugoid': 'q',
|
|
72
|
+
'lateral_phugoid': 'r',
|
|
73
|
+
'plunging': 'alpha_dot',
|
|
74
|
+
'lateral': 'beta_dot',
|
|
75
|
+
}
|
|
76
|
+
try:
|
|
77
|
+
return derivative_names[analysis_type]
|
|
78
|
+
except KeyError as error:
|
|
79
|
+
raise ValueError(f"Unsupported analysis_type for stability derivatives: {analysis_type}") from error
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def calculate_stability_derivatives(
|
|
83
|
+
time,
|
|
84
|
+
force_coefficients,
|
|
85
|
+
moment_coefficients,
|
|
86
|
+
analysis_type,
|
|
87
|
+
ampl,
|
|
88
|
+
omega,
|
|
89
|
+
u_inf,
|
|
90
|
+
reference_length,
|
|
91
|
+
dt=None,
|
|
92
|
+
):
|
|
93
|
+
"""Calculate dynamic derivatives from loads at consecutive center crossings."""
|
|
94
|
+
period = 2 * np.pi / abs(omega)
|
|
95
|
+
if time.size < 2:
|
|
96
|
+
raise ValueError("At least two load samples are required for stability derivatives")
|
|
97
|
+
|
|
98
|
+
sample_intervals = np.diff(time)
|
|
99
|
+
sample_dt = float(np.median(sample_intervals)) if dt is None else dt
|
|
100
|
+
if sample_dt <= 0 or not np.allclose(sample_intervals, sample_dt, rtol=1e-5, atol=1e-10):
|
|
101
|
+
raise ValueError("Integral-load samples must have a uniform positive time step")
|
|
102
|
+
|
|
103
|
+
sampled_period = time[-1] - time[0]
|
|
104
|
+
represented_period = sampled_period + sample_dt
|
|
105
|
+
if abs(represented_period - period) > sample_dt + 1e-9:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"Integral-load history covers approximately {represented_period:g} s, "
|
|
108
|
+
f"not one period ({period:g} s)"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
half_period = period / 2
|
|
112
|
+
crossing_tolerance = 1e-9 * max(1.0, abs(time[0]), abs(time[-1]), period)
|
|
113
|
+
crossing_window_tolerance = max(crossing_tolerance, sample_dt / 2)
|
|
114
|
+
crossing_number_tolerance = crossing_window_tolerance / half_period
|
|
115
|
+
first_crossing_number = int(np.ceil(time[0] / half_period - crossing_number_tolerance))
|
|
116
|
+
last_crossing_number = int(np.floor(time[-1] / half_period + crossing_number_tolerance))
|
|
117
|
+
if last_crossing_number - first_crossing_number < 1:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
"Integral-load history does not contain two consecutive "
|
|
120
|
+
"mean-position crossings"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
comparison_times = (
|
|
124
|
+
last_crossing_number * half_period - half_period,
|
|
125
|
+
last_crossing_number * half_period,
|
|
126
|
+
)
|
|
127
|
+
rate_reference_time = comparison_times[0]
|
|
128
|
+
if analysis_type in ('plunging', 'lateral'):
|
|
129
|
+
comparison_times = tuple(
|
|
130
|
+
target_time - period / 4 for target_time in comparison_times
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def interpolate_coefficients(coefficients, target_time):
|
|
134
|
+
"""Interpolate coefficient values at an exact crossing time."""
|
|
135
|
+
right_index = int(np.searchsorted(time, target_time, side='left'))
|
|
136
|
+
if right_index < time.size and abs(time[right_index] - target_time) <= crossing_tolerance:
|
|
137
|
+
return coefficients[right_index]
|
|
138
|
+
if target_time < time[0] and time[0] - target_time <= sample_dt / 2:
|
|
139
|
+
return coefficients[0]
|
|
140
|
+
if target_time > time[-1] and target_time - time[-1] <= sample_dt / 2:
|
|
141
|
+
return coefficients[-1]
|
|
142
|
+
left_index = right_index - 1
|
|
143
|
+
if left_index < 0 or right_index >= time.size:
|
|
144
|
+
raise ValueError("Mean-position crossing falls outside the integral-load history")
|
|
145
|
+
weight = (
|
|
146
|
+
(target_time - time[left_index])
|
|
147
|
+
/ (time[right_index] - time[left_index])
|
|
148
|
+
)
|
|
149
|
+
return coefficients[left_index] + weight * (
|
|
150
|
+
coefficients[right_index] - coefficients[left_index]
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if u_inf <= 0 or reference_length <= 0:
|
|
154
|
+
raise ValueError("u_inf and reference_length must be positive")
|
|
155
|
+
amplitude = motion_amplitude_rad(analysis_type, ampl, omega, u_inf)
|
|
156
|
+
derivative_name = motion_derivative_name(analysis_type)
|
|
157
|
+
if amplitude == 0:
|
|
158
|
+
raise ValueError("Oscillation amplitude must be non-zero for stability derivatives")
|
|
159
|
+
|
|
160
|
+
# Account for the generalized-rate phase of each supported motion.
|
|
161
|
+
if analysis_type in ('rolling', 'pitching', 'yawing', 'plunging', 'lateral'):
|
|
162
|
+
rate_scale = ampl * omega
|
|
163
|
+
elif analysis_type == 'phugoid':
|
|
164
|
+
rate_scale = ampl
|
|
165
|
+
else:
|
|
166
|
+
rate_scale = -ampl
|
|
167
|
+
first_crossing_rate = rate_scale * np.cos(omega * rate_reference_time)
|
|
168
|
+
|
|
169
|
+
reduced_frequency = reference_length * abs(omega) / u_inf
|
|
170
|
+
denominator = 2 * reduced_frequency * amplitude
|
|
171
|
+
first_force_coefficients = interpolate_coefficients(force_coefficients, comparison_times[0])
|
|
172
|
+
second_force_coefficients = interpolate_coefficients(force_coefficients, comparison_times[1])
|
|
173
|
+
first_moment_coefficients = interpolate_coefficients(moment_coefficients, comparison_times[0])
|
|
174
|
+
second_moment_coefficients = interpolate_coefficients(moment_coefficients, comparison_times[1])
|
|
175
|
+
if first_crossing_rate < 0:
|
|
176
|
+
force_difference = second_force_coefficients - first_force_coefficients
|
|
177
|
+
moment_difference = second_moment_coefficients - first_moment_coefficients
|
|
178
|
+
else:
|
|
179
|
+
force_difference = first_force_coefficients - second_force_coefficients
|
|
180
|
+
moment_difference = first_moment_coefficients - second_moment_coefficients
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
derivative_sign = -1 if analysis_type in ('plunging', 'lateral') else 1
|
|
184
|
+
force_derivatives = derivative_sign * force_difference / denominator
|
|
185
|
+
moment_derivatives = derivative_sign * moment_difference / denominator
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
comparison_indices = tuple(
|
|
189
|
+
int(np.argmin(np.abs(time - comparison_time)))
|
|
190
|
+
for comparison_time in comparison_times
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
'force_derivatives': force_derivatives,
|
|
195
|
+
'moment_derivatives': moment_derivatives,
|
|
196
|
+
'reduced_frequency': reduced_frequency,
|
|
197
|
+
'motion_amplitude_rad': amplitude,
|
|
198
|
+
'derivative_name': derivative_name,
|
|
199
|
+
'half_period_index': comparison_indices[0],
|
|
200
|
+
'comparison_indices': comparison_indices,
|
|
201
|
+
'comparison_times': comparison_times,
|
|
202
|
+
'sample_dt': sample_dt,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def write_stability_derivatives(history, derivatives_file, metadata):
|
|
207
|
+
"""Write calculated dynamic stability derivatives and run metadata."""
|
|
208
|
+
headers = [
|
|
209
|
+
'# Dynamic stability derivatives',
|
|
210
|
+
f"# Model: {metadata['model']}",
|
|
211
|
+
f"# Analysis type: {metadata['analysis_type']}",
|
|
212
|
+
f"# Motion amplitude: {metadata['amplitude']} {metadata['amplitude_units']}",
|
|
213
|
+
f"# Angular frequency: {metadata['omega']} rad/s",
|
|
214
|
+
f"# V_inf: {metadata['u_inf']} m/s",
|
|
215
|
+
f"# rho: {metadata['rho']} kg/m^3",
|
|
216
|
+
f"# q_inf: {metadata['dynamic_pressure']} Pa",
|
|
217
|
+
f"# S_ref: {metadata['reference_area']} m^2",
|
|
218
|
+
f"# L_ref: {metadata['reference_length']} m",
|
|
219
|
+
f"# Reduced frequency k: {history['reduced_frequency']}",
|
|
220
|
+
f"# Oscillation angle amplitude: {history['motion_amplitude_rad']} rad",
|
|
221
|
+
f"# Simulation interval: {metadata.get('t_start', 0.0)} to {metadata['tend']} s",
|
|
222
|
+
f"# Load component: {metadata['component']}; reference tag: {metadata['reference_tag']}",
|
|
223
|
+
f"# Derivative variable: {history['derivative_name']}",
|
|
224
|
+
'# Quantity\tDerivative',
|
|
225
|
+
]
|
|
226
|
+
quantities = ('x', 'y', 'z')
|
|
227
|
+
rows = [
|
|
228
|
+
f"dCF{axis}/d{history['derivative_name']}\t{value:.10e}"
|
|
229
|
+
for axis, value in zip(quantities, history['force_derivatives'])
|
|
230
|
+
]
|
|
231
|
+
rows.extend(
|
|
232
|
+
f"dCM{axis}/d{history['derivative_name']}\t{value:.10e}"
|
|
233
|
+
for axis, value in zip(quantities, history['moment_derivatives'])
|
|
234
|
+
)
|
|
235
|
+
with open(derivatives_file, 'w') as output_file:
|
|
236
|
+
output_file.write('\n'.join(headers + rows) + '\n')
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def write_stability_derivatives_hdf5(history, derivatives_file, metadata):
|
|
240
|
+
"""Write dynamic derivatives and run metadata as an HDF5 file."""
|
|
241
|
+
with h5py.File(derivatives_file, 'w') as output_file:
|
|
242
|
+
derivatives = np.concatenate((
|
|
243
|
+
np.asarray(history['force_derivatives'], dtype=float),
|
|
244
|
+
np.asarray(history['moment_derivatives'], dtype=float),
|
|
245
|
+
))
|
|
246
|
+
derivative_name = history['derivative_name']
|
|
247
|
+
output_file.create_dataset(
|
|
248
|
+
'derivatives',
|
|
249
|
+
data=derivatives,
|
|
250
|
+
)
|
|
251
|
+
output_file.create_dataset(
|
|
252
|
+
'derivative_names',
|
|
253
|
+
data=np.asarray(
|
|
254
|
+
[f'dCF{axis}/d{derivative_name}' for axis in 'xyz']
|
|
255
|
+
+ [f'dCM{axis}/d{derivative_name}' for axis in 'xyz'],
|
|
256
|
+
dtype=h5py.string_dtype(encoding='utf-8'),
|
|
257
|
+
),
|
|
258
|
+
)
|
|
259
|
+
attributes = {
|
|
260
|
+
key: value
|
|
261
|
+
for key, value in metadata.items()
|
|
262
|
+
if isinstance(value, (str, bytes, int, float, np.integer, np.floating))
|
|
263
|
+
}
|
|
264
|
+
attributes.update({
|
|
265
|
+
'derivative_name': history['derivative_name'],
|
|
266
|
+
'reduced_frequency': float(history['reduced_frequency']),
|
|
267
|
+
'motion_amplitude_rad': float(history['motion_amplitude_rad']),
|
|
268
|
+
'comparison_indices': np.asarray(history['comparison_indices'], dtype=int),
|
|
269
|
+
'comparison_times_s': np.asarray(history['comparison_times'], dtype=float),
|
|
270
|
+
'sample_dt_s': float(history['sample_dt']),
|
|
271
|
+
})
|
|
272
|
+
for key, value in attributes.items():
|
|
273
|
+
output_file.attrs[key] = value
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def run_static_analysis(
|
|
277
|
+
loads_files,
|
|
278
|
+
parameter_name,
|
|
279
|
+
parameter_values,
|
|
280
|
+
velocity_vectors,
|
|
281
|
+
rho,
|
|
282
|
+
reference_area,
|
|
283
|
+
reference_length,
|
|
284
|
+
output_dir,
|
|
285
|
+
metadata,
|
|
286
|
+
):
|
|
287
|
+
|
|
288
|
+
"""Compute coefficient derivatives from two steady load cases."""
|
|
289
|
+
|
|
290
|
+
if len(loads_files) != 2 or len(parameter_values) != 2 or len(velocity_vectors) != 2:
|
|
291
|
+
raise ValueError("Static finite-difference analysis requires exactly two cases")
|
|
292
|
+
if rho <= 0 or reference_area <= 0 or reference_length <= 0:
|
|
293
|
+
raise ValueError("rho, reference_area and reference_length must be positive")
|
|
294
|
+
|
|
295
|
+
final_loads = []
|
|
296
|
+
for loads_file in loads_files:
|
|
297
|
+
sample = read_integral_loads(loads_file)
|
|
298
|
+
final_loads.append(np.concatenate((sample['forces'][-1], sample['moments'][-1])))
|
|
299
|
+
|
|
300
|
+
velocity_vectors = np.asarray(velocity_vectors, dtype=float)
|
|
301
|
+
speeds = np.linalg.norm(velocity_vectors, axis=1)
|
|
302
|
+
if np.any(speeds <= 0):
|
|
303
|
+
raise ValueError("Static cases must have positive freestream speed")
|
|
304
|
+
|
|
305
|
+
dynamic_pressures = 0.5 * rho * speeds**2
|
|
306
|
+
coefficients = np.asarray(final_loads, dtype=float)
|
|
307
|
+
coefficients[:, :3] /= (dynamic_pressures * reference_area)[:, None]
|
|
308
|
+
coefficients[:, 3:] /= (dynamic_pressures * reference_area * reference_length)[:, None]
|
|
309
|
+
|
|
310
|
+
parameter_values = np.asarray(parameter_values, dtype=float)
|
|
311
|
+
delta_parameter = parameter_values[1] - parameter_values[0]
|
|
312
|
+
if parameter_name in ('alpha', 'beta'):
|
|
313
|
+
delta_parameter = np.deg2rad(delta_parameter)
|
|
314
|
+
parameter_label = f'{parameter_name} [deg]'
|
|
315
|
+
derivative_variable = parameter_name
|
|
316
|
+
elif parameter_name == 'V_inf':
|
|
317
|
+
parameter_label = 'V_inf [m/s]'
|
|
318
|
+
derivative_variable = 'V_inf'
|
|
319
|
+
elif parameter_name == 'collective':
|
|
320
|
+
parameter_label = 'Blade collective [deg]'
|
|
321
|
+
derivative_variable = 'collective'
|
|
322
|
+
elif parameter_name == 'rot_rate':
|
|
323
|
+
parameter_label = 'Rotor rate [rad/s]'
|
|
324
|
+
derivative_variable = 'rot_rate'
|
|
325
|
+
elif parameter_name == 'hinge_amplitude':
|
|
326
|
+
parameter_label = 'Hinge amplitude'
|
|
327
|
+
derivative_variable = 'hinge_amplitude'
|
|
328
|
+
else:
|
|
329
|
+
raise ValueError(f"Unsupported static parameter: {parameter_name}")
|
|
330
|
+
if delta_parameter == 0:
|
|
331
|
+
raise ValueError("Static perturbation amplitude must be non-zero")
|
|
332
|
+
|
|
333
|
+
derivative_values = (coefficients[1] - coefficients[0]) / delta_parameter
|
|
334
|
+
force_derivatives = derivative_values[:3]
|
|
335
|
+
moment_derivatives = derivative_values[3:]
|
|
336
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
337
|
+
result_name = metadata.get('result_name', f"static_{parameter_name}")
|
|
338
|
+
history_file = os.path.join(output_dir, result_name + '_coefficient_history.txt')
|
|
339
|
+
model_name = os.path.basename(os.path.normpath(metadata.get('model', result_name)))
|
|
340
|
+
plot_file = os.path.join(output_dir, model_name + '_loads.png')
|
|
341
|
+
|
|
342
|
+
derivative_units = (
|
|
343
|
+
'per degree for blade collective'
|
|
344
|
+
if parameter_name == 'collective'
|
|
345
|
+
else 'per rad/s for rotor rate'
|
|
346
|
+
if parameter_name == 'rot_rate'
|
|
347
|
+
else 'per hinge-amplitude unit'
|
|
348
|
+
if parameter_name == 'hinge_amplitude'
|
|
349
|
+
else 'per rad for alpha/beta; per m/s for V_inf'
|
|
350
|
+
)
|
|
351
|
+
headers = [
|
|
352
|
+
f"# Static finite-difference analysis: {parameter_name}",
|
|
353
|
+
f"# Model: {metadata['model']}",
|
|
354
|
+
f"# Analysis type: {metadata['analysis_type']}",
|
|
355
|
+
f"# rho: {rho} kg/m^3",
|
|
356
|
+
f"# S_ref: {reference_area} m^2",
|
|
357
|
+
f"# L_ref: {reference_length} m",
|
|
358
|
+
f"# Load component: {metadata['component']}; reference tag: {metadata['reference_tag']}",
|
|
359
|
+
f"# Baseline velocity vector: {metadata['baseline_velocity']} m/s",
|
|
360
|
+
f"# Perturbed velocity vector: {metadata['perturbed_velocity']} m/s",
|
|
361
|
+
f"# Baseline alpha/beta: {metadata['baseline_alpha_deg']} / {metadata['baseline_beta_deg']} deg",
|
|
362
|
+
f"# Perturbed alpha/beta: {metadata['perturbed_alpha_deg']} / {metadata['perturbed_beta_deg']} deg",
|
|
363
|
+
f'# Derivative units: {derivative_units}',
|
|
364
|
+
*(
|
|
365
|
+
[
|
|
366
|
+
f"# Controlled rotor reference: {metadata['rotor_reference']}",
|
|
367
|
+
*(
|
|
368
|
+
[
|
|
369
|
+
f"# Baseline blade collective: {metadata['baseline_collective']} deg",
|
|
370
|
+
f"# Perturbed blade collective: {metadata['perturbed_collective']} deg",
|
|
371
|
+
]
|
|
372
|
+
if parameter_name == 'collective'
|
|
373
|
+
else [
|
|
374
|
+
f"# Baseline rotor rate: {metadata['baseline_rot_rate']} rad/s",
|
|
375
|
+
f"# Perturbed rotor rate: {metadata['perturbed_rot_rate']} rad/s",
|
|
376
|
+
]
|
|
377
|
+
),
|
|
378
|
+
]
|
|
379
|
+
if parameter_name in ('collective', 'rot_rate')
|
|
380
|
+
else []
|
|
381
|
+
),
|
|
382
|
+
*(
|
|
383
|
+
[
|
|
384
|
+
f"# Controlled component file: {metadata['component_path']}",
|
|
385
|
+
f"# Controlled hinge tag: {metadata['hinge_tag']}",
|
|
386
|
+
f"# Baseline hinge amplitude: {metadata['baseline_hinge_amplitude']}",
|
|
387
|
+
f"# Perturbed hinge amplitude: {metadata['perturbed_hinge_amplitude']}",
|
|
388
|
+
f"# Hinge amplitude units: {metadata['amplitude_units']}",
|
|
389
|
+
]
|
|
390
|
+
if parameter_name == 'hinge_amplitude'
|
|
391
|
+
else []
|
|
392
|
+
),
|
|
393
|
+
'# Case table columns: case, parameter, V_inf_m_s, CFx, CFy, CFz, CMx, CMy, CMz',
|
|
394
|
+
]
|
|
395
|
+
data_rows = [
|
|
396
|
+
f"{case}\t{parameter_values[index]:.10e}\t{speeds[index]:.10e}\t"
|
|
397
|
+
+ '\t'.join(f'{value:.10e}' for value in coefficients[index])
|
|
398
|
+
for index, case in enumerate(('baseline', 'perturbed'))
|
|
399
|
+
]
|
|
400
|
+
derivative_rows = [
|
|
401
|
+
f'dCF{axis}/d{derivative_variable}\t{value:.10e}'
|
|
402
|
+
for axis, value in zip('xyz', force_derivatives)
|
|
403
|
+
]
|
|
404
|
+
derivative_rows.extend(
|
|
405
|
+
f'dCM{axis}/d{derivative_variable}\t{value:.10e}'
|
|
406
|
+
for axis, value in zip('xyz', moment_derivatives)
|
|
407
|
+
)
|
|
408
|
+
with open(history_file, 'w') as output_file:
|
|
409
|
+
output_file.write('\n'.join(headers + data_rows + ['# Finite-difference derivatives'] + derivative_rows) + '\n')
|
|
410
|
+
|
|
411
|
+
figure, axes = plt.subplots(2, 1, sharex=True, figsize=(9, 7))
|
|
412
|
+
force_colors = ('#0077B6', '#F77F00', '#2A9D8F')
|
|
413
|
+
moment_colors = ('#D1495B', '#6A4C93', '#8F5D28')
|
|
414
|
+
for index, label in enumerate(('CFx', 'CFy', 'CFz')):
|
|
415
|
+
axes[0].plot(parameter_values, coefficients[:, index], marker='o', label=label, color=force_colors[index])
|
|
416
|
+
axes[0].set_ylabel('Force coefficient')
|
|
417
|
+
axes[0].legend()
|
|
418
|
+
axes[0].grid(True)
|
|
419
|
+
for index, label in enumerate(('CMx', 'CMy', 'CMz')):
|
|
420
|
+
axes[1].plot(parameter_values, coefficients[:, index + 3], marker='o', label=label, color=moment_colors[index])
|
|
421
|
+
axes[1].set_xlabel(parameter_label)
|
|
422
|
+
axes[1].set_ylabel('Moment coefficient')
|
|
423
|
+
axes[1].legend()
|
|
424
|
+
axes[1].grid(True)
|
|
425
|
+
figure.suptitle(
|
|
426
|
+
f"{metadata['model']} | static {parameter_name} finite difference\n"
|
|
427
|
+
f"rho={rho:g} kg/m^3, S_ref={reference_area:g} m^2, "
|
|
428
|
+
f"L_ref={reference_length:g} m",
|
|
429
|
+
fontsize=11,
|
|
430
|
+
)
|
|
431
|
+
figure.tight_layout()
|
|
432
|
+
figure.subplots_adjust(top=0.88)
|
|
433
|
+
figure.savefig(plot_file, dpi=150)
|
|
434
|
+
plt.close(figure)
|
|
435
|
+
|
|
436
|
+
return {
|
|
437
|
+
'force_derivatives': force_derivatives,
|
|
438
|
+
'moment_derivatives': moment_derivatives,
|
|
439
|
+
'derivative_name': derivative_variable,
|
|
440
|
+
'history_file': history_file,
|
|
441
|
+
'plot_file': plot_file,
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def run_zero_attitude_analysis(
|
|
446
|
+
loads_file,
|
|
447
|
+
velocity_vector,
|
|
448
|
+
rho,
|
|
449
|
+
reference_area,
|
|
450
|
+
reference_length,
|
|
451
|
+
output_dir,
|
|
452
|
+
metadata,
|
|
453
|
+
):
|
|
454
|
+
"""Compute and save aerodynamic coefficients for zero-attitude loads."""
|
|
455
|
+
if rho <= 0 or reference_area <= 0 or reference_length <= 0:
|
|
456
|
+
raise ValueError("rho, reference_area and reference_length must be positive")
|
|
457
|
+
|
|
458
|
+
load_history = read_integral_loads(loads_file)
|
|
459
|
+
velocity_vector = np.asarray(velocity_vector, dtype=float)
|
|
460
|
+
speed = float(np.linalg.norm(velocity_vector))
|
|
461
|
+
if speed <= 0:
|
|
462
|
+
raise ValueError("The zero-attitude case must have a positive freestream speed")
|
|
463
|
+
|
|
464
|
+
final_loads = np.concatenate((load_history['forces'][-1], load_history['moments'][-1]))
|
|
465
|
+
dynamic_pressure = 0.5 * rho * speed**2
|
|
466
|
+
coefficients = final_loads.copy()
|
|
467
|
+
coefficients[:3] /= dynamic_pressure * reference_area
|
|
468
|
+
coefficients[3:] /= dynamic_pressure * reference_area * reference_length
|
|
469
|
+
|
|
470
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
471
|
+
coefficients_file = os.path.join(output_dir, metadata['result_name'] + '_coefficients.txt')
|
|
472
|
+
headers = [
|
|
473
|
+
'# Zero-attitude static load coefficients',
|
|
474
|
+
f"# Model: {metadata['model']}",
|
|
475
|
+
f"# V_inf vector: {velocity_vector.tolist()} m/s",
|
|
476
|
+
f"# V_inf magnitude: {speed} m/s",
|
|
477
|
+
f"# rho: {rho} kg/m^3",
|
|
478
|
+
f"# q_inf: {dynamic_pressure} Pa",
|
|
479
|
+
f"# S_ref: {reference_area} m^2",
|
|
480
|
+
f"# L_ref: {reference_length} m",
|
|
481
|
+
f"# Load component: {metadata['component']}; reference tag: {metadata['reference_tag']}",
|
|
482
|
+
f"# Result time: {load_history['time'][-1]} s",
|
|
483
|
+
'# Coefficients: CFx, CFy, CFz, CMx, CMy, CMz',
|
|
484
|
+
]
|
|
485
|
+
with open(coefficients_file, 'w') as output_file:
|
|
486
|
+
output_file.write('\n'.join(headers) + '\n')
|
|
487
|
+
output_file.write('\t'.join(f'{value:.10e}' for value in coefficients) + '\n')
|
|
488
|
+
|
|
489
|
+
return {
|
|
490
|
+
'force_coefficients': coefficients[:3],
|
|
491
|
+
'moment_coefficients': coefficients[3:],
|
|
492
|
+
'coefficients_file': coefficients_file,
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def run_SC_analysis(
|
|
497
|
+
loads_file,
|
|
498
|
+
analysis_type,
|
|
499
|
+
ampl,
|
|
500
|
+
omega,
|
|
501
|
+
u_inf,
|
|
502
|
+
rho,
|
|
503
|
+
reference_area,
|
|
504
|
+
reference_length,
|
|
505
|
+
alpha_0=0.0,
|
|
506
|
+
beta_0=0.0,
|
|
507
|
+
plot_file=None,
|
|
508
|
+
show=True,
|
|
509
|
+
output_dir=None,
|
|
510
|
+
metadata=None,
|
|
511
|
+
dt=None,
|
|
512
|
+
):
|
|
513
|
+
"""Analyze dynamic loads, calculate derivatives, and save plots and reports."""
|
|
514
|
+
history = read_integral_loads(loads_file)
|
|
515
|
+
if history['averaged']:
|
|
516
|
+
raise ValueError("Dynamic stability analysis requires time-resolved, non-averaged loads")
|
|
517
|
+
time = history['time']
|
|
518
|
+
forces = history['forces']
|
|
519
|
+
moments = history['moments']
|
|
520
|
+
angle, angle_label = compute_motion_angle(
|
|
521
|
+
time,
|
|
522
|
+
analysis_type,
|
|
523
|
+
ampl,
|
|
524
|
+
omega,
|
|
525
|
+
u_inf,
|
|
526
|
+
alpha_0,
|
|
527
|
+
beta_0,
|
|
528
|
+
)
|
|
529
|
+
|
|
530
|
+
if any(value <= 0 for value in (rho, u_inf, reference_area, reference_length)):
|
|
531
|
+
raise ValueError(
|
|
532
|
+
"rho, u_inf, reference_area and reference_length must be positive"
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
dynamic_pressure = 0.5 * rho * u_inf**2
|
|
536
|
+
force_coefficients = forces / (dynamic_pressure * reference_area)
|
|
537
|
+
moment_coefficients = moments / (dynamic_pressure * reference_area * reference_length)
|
|
538
|
+
derivative_data = calculate_stability_derivatives(
|
|
539
|
+
time,
|
|
540
|
+
force_coefficients,
|
|
541
|
+
moment_coefficients,
|
|
542
|
+
analysis_type,
|
|
543
|
+
ampl,
|
|
544
|
+
omega,
|
|
545
|
+
u_inf,
|
|
546
|
+
reference_length,
|
|
547
|
+
dt,
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
model_name = (
|
|
551
|
+
os.path.basename(os.path.normpath(metadata['model']))
|
|
552
|
+
if metadata and metadata.get('model')
|
|
553
|
+
else os.path.splitext(os.path.basename(loads_file))[0]
|
|
554
|
+
)
|
|
555
|
+
if output_dir is not None:
|
|
556
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
557
|
+
if plot_file is None:
|
|
558
|
+
plot_directory = output_dir or os.path.dirname(loads_file)
|
|
559
|
+
plot_file = os.path.join(plot_directory, model_name + '_loads_hysteresis.png')
|
|
560
|
+
derivatives_file = os.path.join(
|
|
561
|
+
output_dir or os.path.dirname(loads_file),
|
|
562
|
+
model_name + '_stability_derivatives.dat',
|
|
563
|
+
)
|
|
564
|
+
derivatives_hdf5_file = os.path.join(
|
|
565
|
+
output_dir or os.path.dirname(loads_file),
|
|
566
|
+
model_name + '_stability_derivatives.h5',
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
metadata = metadata or {
|
|
570
|
+
'model': 'unknown',
|
|
571
|
+
'analysis_type': analysis_type,
|
|
572
|
+
'amplitude': ampl,
|
|
573
|
+
'amplitude_units': 'unknown',
|
|
574
|
+
'omega': omega,
|
|
575
|
+
'u_inf': u_inf,
|
|
576
|
+
'rho': rho,
|
|
577
|
+
'dynamic_pressure': dynamic_pressure,
|
|
578
|
+
'reference_area': reference_area,
|
|
579
|
+
'reference_length': reference_length,
|
|
580
|
+
'alpha_0': alpha_0,
|
|
581
|
+
'beta_0': beta_0,
|
|
582
|
+
'dt': float(np.mean(np.diff(time))) if time.size > 1 else 0.0,
|
|
583
|
+
'tend': float(time[-1]) if time.size else 0.0,
|
|
584
|
+
'component': 'unknown',
|
|
585
|
+
'reference_tag': 'unknown',
|
|
586
|
+
}
|
|
587
|
+
history['angle'] = angle
|
|
588
|
+
history['angle_label'] = angle_label
|
|
589
|
+
history['force_coefficients'] = force_coefficients
|
|
590
|
+
history['moment_coefficients'] = moment_coefficients
|
|
591
|
+
history.update(derivative_data)
|
|
592
|
+
write_stability_derivatives(history, derivatives_file, metadata)
|
|
593
|
+
write_stability_derivatives_hdf5(history, derivatives_hdf5_file, metadata)
|
|
594
|
+
|
|
595
|
+
figure, axes = plt.subplots(2, 1, sharex=True, figsize=(10, 8))
|
|
596
|
+
force_colors = ('#0077B6', '#F77F00', '#2A9D8F')
|
|
597
|
+
moment_colors = ('#D1495B', '#6A4C93', '#8F5D28')
|
|
598
|
+
for index, label in enumerate(('CFx', 'CFy', 'CFz')):
|
|
599
|
+
axes[0].plot(angle, force_coefficients[:, index], label=label, color=force_colors[index], linewidth=1.8)
|
|
600
|
+
axes[0].set_ylabel('Force coefficient')
|
|
601
|
+
axes[0].legend()
|
|
602
|
+
axes[0].grid(True)
|
|
603
|
+
|
|
604
|
+
for index, label in enumerate(('CMx', 'CMy', 'CMz')):
|
|
605
|
+
axes[1].plot(angle, moment_coefficients[:, index], label=label, color=moment_colors[index], linewidth=1.8)
|
|
606
|
+
axes[1].set_xlabel(f'{angle_label} [deg]')
|
|
607
|
+
axes[1].set_ylabel('Moment coefficient')
|
|
608
|
+
axes[1].legend()
|
|
609
|
+
axes[1].grid(True)
|
|
610
|
+
|
|
611
|
+
figure.suptitle(
|
|
612
|
+
f"{metadata['model']} | {analysis_type} hysteresis\n"
|
|
613
|
+
f"V_inf={u_inf:g} m/s, rho={rho:g} kg/m^3, "
|
|
614
|
+
f"S_ref={reference_area:g} m^2, L_ref={reference_length:g} m, "
|
|
615
|
+
f"alpha_0={alpha_0:g} deg, beta_0={beta_0:g} deg",
|
|
616
|
+
fontsize=11,
|
|
617
|
+
)
|
|
618
|
+
figure.tight_layout()
|
|
619
|
+
figure.subplots_adjust(top=0.88)
|
|
620
|
+
figure.savefig(plot_file, dpi=150)
|
|
621
|
+
if show:
|
|
622
|
+
plt.show()
|
|
623
|
+
plt.close(figure)
|
|
624
|
+
|
|
625
|
+
history['plot_file'] = plot_file
|
|
626
|
+
history['derivatives_file'] = derivatives_file
|
|
627
|
+
history['derivatives_hdf5_file'] = derivatives_hdf5_file
|
|
628
|
+
return history
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def analyze_run(plan, loads_files):
|
|
632
|
+
"""Analyze the load files produced by a prepared run plan."""
|
|
633
|
+
analysis_type = plan['analysis_type']
|
|
634
|
+
if len(loads_files) != len(plan['cases']):
|
|
635
|
+
raise ValueError("The number of load files must match the planned cases")
|
|
636
|
+
|
|
637
|
+
if analysis_type == 'zero_attitude':
|
|
638
|
+
result_name = plan['cases'][0]['name']
|
|
639
|
+
analysis = run_zero_attitude_analysis(
|
|
640
|
+
loads_files[0],
|
|
641
|
+
plan['baseline_velocity'],
|
|
642
|
+
plan['rho'],
|
|
643
|
+
plan['reference_area'],
|
|
644
|
+
plan['reference_length'],
|
|
645
|
+
plan['output_directory'],
|
|
646
|
+
{
|
|
647
|
+
'model': plan['model_folder'],
|
|
648
|
+
'component': plan['load_component'],
|
|
649
|
+
'reference_tag': plan['load_reference'],
|
|
650
|
+
'result_name': result_name,
|
|
651
|
+
},
|
|
652
|
+
)
|
|
653
|
+
for coefficient, value in zip(
|
|
654
|
+
('CFx', 'CFy', 'CFz', 'CMx', 'CMy', 'CMz'),
|
|
655
|
+
np.concatenate((
|
|
656
|
+
analysis['force_coefficients'],
|
|
657
|
+
analysis['moment_coefficients'],
|
|
658
|
+
)),
|
|
659
|
+
):
|
|
660
|
+
print(f'{coefficient}_0 = {value:.10e}')
|
|
661
|
+
return
|
|
662
|
+
|
|
663
|
+
if analysis_type in {
|
|
664
|
+
'static_alpha', 'static_beta', 'static_v',
|
|
665
|
+
'control_blade_pitch', 'control_omega', 'control_surface',
|
|
666
|
+
}:
|
|
667
|
+
sweeps = plan.get('static_sweeps', [{
|
|
668
|
+
'parameter_name': plan['parameter_name'],
|
|
669
|
+
'parameter_values': plan['parameter_values'],
|
|
670
|
+
'velocity_cases': plan['velocity_cases'],
|
|
671
|
+
'output_directory': plan['output_directory'],
|
|
672
|
+
'analysis_metadata': plan['analysis_metadata'],
|
|
673
|
+
}])
|
|
674
|
+
for sweep_index, sweep in enumerate(sweeps):
|
|
675
|
+
if sweep_index:
|
|
676
|
+
print()
|
|
677
|
+
sweep_loads = loads_files[2 * sweep_index:2 * sweep_index + 2]
|
|
678
|
+
analysis = run_static_analysis(
|
|
679
|
+
sweep_loads,
|
|
680
|
+
sweep['parameter_name'],
|
|
681
|
+
sweep['parameter_values'],
|
|
682
|
+
sweep['velocity_cases'],
|
|
683
|
+
plan['rho'],
|
|
684
|
+
plan['reference_area'],
|
|
685
|
+
plan['reference_length'],
|
|
686
|
+
sweep['output_directory'],
|
|
687
|
+
sweep['analysis_metadata'],
|
|
688
|
+
)
|
|
689
|
+
for coefficient, value in zip(
|
|
690
|
+
('CFx', 'CFy', 'CFz', 'CMx', 'CMy', 'CMz'),
|
|
691
|
+
np.concatenate((
|
|
692
|
+
analysis['force_derivatives'],
|
|
693
|
+
analysis['moment_derivatives'],
|
|
694
|
+
)),
|
|
695
|
+
):
|
|
696
|
+
print(f"d{coefficient}/d{analysis['derivative_name']} = {value:.10e}")
|
|
697
|
+
return
|
|
698
|
+
|
|
699
|
+
for case_index, (case, loads_file) in enumerate(zip(plan['cases'], loads_files)):
|
|
700
|
+
if case_index:
|
|
701
|
+
print()
|
|
702
|
+
alpha_0 = case['alpha_0']
|
|
703
|
+
beta_0 = case['beta_0']
|
|
704
|
+
speed = case['speed']
|
|
705
|
+
ampl = case['ampl']
|
|
706
|
+
omega = case['omega']
|
|
707
|
+
metadata = {
|
|
708
|
+
'model': plan['model_folder'],
|
|
709
|
+
'analysis_type': analysis_type,
|
|
710
|
+
'amplitude': ampl,
|
|
711
|
+
'amplitude_units': (
|
|
712
|
+
'm' if analysis_type in (
|
|
713
|
+
'plunging', 'lateral', 'phugoid', 'lateral_phugoid'
|
|
714
|
+
) else 'rad'
|
|
715
|
+
),
|
|
716
|
+
'omega': omega,
|
|
717
|
+
'u_inf': speed,
|
|
718
|
+
'rho': plan['rho'],
|
|
719
|
+
'dynamic_pressure': 0.5 * plan['rho'] * speed ** 2,
|
|
720
|
+
'reference_area': plan['reference_area'],
|
|
721
|
+
'reference_length': plan['reference_length'],
|
|
722
|
+
'alpha_0': alpha_0,
|
|
723
|
+
'beta_0': beta_0,
|
|
724
|
+
'dt': plan['dt'],
|
|
725
|
+
't_start': plan['t_start'],
|
|
726
|
+
'tend': plan['tend'],
|
|
727
|
+
'component': plan['load_component'],
|
|
728
|
+
'reference_tag': plan['load_reference'],
|
|
729
|
+
}
|
|
730
|
+
analysis = run_SC_analysis(
|
|
731
|
+
loads_file,
|
|
732
|
+
analysis_type,
|
|
733
|
+
ampl,
|
|
734
|
+
omega,
|
|
735
|
+
speed,
|
|
736
|
+
plan['rho'],
|
|
737
|
+
plan['reference_area'],
|
|
738
|
+
plan['reference_length'],
|
|
739
|
+
alpha_0,
|
|
740
|
+
beta_0,
|
|
741
|
+
output_dir=case.get('output_directory', plan['output_directory']),
|
|
742
|
+
metadata=metadata,
|
|
743
|
+
dt=plan['dt'],
|
|
744
|
+
show=False,
|
|
745
|
+
)
|
|
746
|
+
for coefficient, value in zip(
|
|
747
|
+
('CFx', 'CFy', 'CFz', 'CMx', 'CMy', 'CMz'),
|
|
748
|
+
np.concatenate((
|
|
749
|
+
analysis['force_derivatives'],
|
|
750
|
+
analysis['moment_derivatives'],
|
|
751
|
+
)),
|
|
752
|
+
):
|
|
753
|
+
print(f"d{coefficient}/d{analysis['derivative_name']} = {value:.10e}")
|