Ground-Wing / scripts /samples /sample_generation.py
andreacenzato's picture
Added description and analysis files
f355580 verified
Raw History Blame Contribute Delete
20.6 kB
import numpy as np
import pandas as pd
import warnings
import os
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder,KBinsDiscretizer
from skmultilearn.model_selection import iterative_train_test_split
from scipy import interpolate
from scipy.stats import qmc
def check_bounds(sample,bounds):
sample_ok = True
for i in range(len(sample)):
if not bounds[i][0] <= sample[i] <= bounds[i][1]:
sample_ok = False
return sample_ok
def check_feasibility(p_set:list,bounds:list)->bool:
"""
Checks if a set of parameters is suitable for geometry generation
"""
# Calculate forward displacement of wingtip
forward_disp = -np.tan(np.deg2rad(p_set[4]))*1000
# Check that angle of attack and twist angle sum does not exceed limits
if not bounds[0][0] < p_set[0] + p_set[1] < bounds[0][1]:
return False
# Check forward displacement
if forward_disp + p_set[2] > bounds[2][1]:
return False
# Check backwards displacement
if forward_disp + p_set[2] < bounds[3][0]:
return False
# Check if outboard chord is too large
if p_set[3] - p_set[2] - forward_disp > bounds[3][1]:
return False
return True
def check_feasibility_batch(points,bounds):
"""
Checks if each set of parameters is suitable for geometry generation
"""
feas_bounds = np.array([check_bounds(point,bounds) for point in points])
feas_constrains = np.array([check_feasibility(point,bounds) for point in points])
return np.logical_and(feas_bounds,feas_constrains)
def build_F_inv(p_index, p_bounds, sens_funcs, num_points=200):
a, b = p_bounds[p_index]
# grid on axis i
xs = np.linspace(a, b, num_points)
ds = sens_funcs[p_index](xs) # sensitivities at grid points
ds = np.maximum(ds, 1e-12) # Ensure no zeros are present, to avoid duplicates in cdf
if np.all(ds == ds[0]):
ds = np.ones_like(ds)
pdf = ds
cdf_vals = np.cumsum(pdf)
cdf_vals = cdf_vals / cdf_vals[-1] # normalize to [0,1]
inv_cdf = interpolate.make_interp_spline(cdf_vals,xs,k=1)
def F_inv(u):
u = np.clip(u, 0.0, 1.0)
return inv_cdf(u)
return F_inv
# -----------------------------
# Warp using empirical per-axis CDF inverse
# -----------------------------
def warp_samples(X, F_inv_funcs):
M = X.shape[0]
X_warped = np.empty_like(X)
for i in range(len(F_inv_funcs)):
X_warped[:, i] = F_inv_funcs[i](X[:, i])
return X_warped
def clip_samples(X,bounds):
for i in range(len(bounds)):
X[:,i] = np.interp(X[:,i],(X[:,i].min(),X[:,i].max()),(bounds[i][0],bounds[i][1]))
return X
def compute_sample_weights(samples, sens_funcs, bounds):
"""
Compute importance weights based on sensitivity functions.
Samples with higher sensitivity values get higher weights.
Args:
samples: Array of shape (n_samples, n_dims)
sens_funcs: List of sensitivity functions, one per dimension
bounds: Parameter bounds
Returns:
weights: Array of shape (n_samples,) with normalized weights
"""
n_samples = samples.shape[0]
weights = np.ones(n_samples)
# Multiply sensitivity values across all dimensions
for i in range(samples.shape[1]):
sens_values = sens_funcs[i](samples[:, i])
# Ensure positive values
sens_values = np.maximum(sens_values, 1e-12)
weights *= sens_values
# Normalize weights to sum to 1
weights = weights / weights.sum()
return weights
# -----------------------------
# Maximin subset selection in warped space
# -----------------------------
def maximin_subset(points, k):
n = points.shape[0]
selected = []
available = np.ones(n,dtype=bool)
# 1) Start with the point farthest from the centroid
mean_pt = np.mean(points, axis=0)
dists_to_mean = np.linalg.norm(points - mean_pt, axis=1)
first = int(np.argmax(dists_to_mean))
selected.append(first)
available[first] = False
# 2) Iteratively add points maximizing distance to the current set
for _ in range(1, k):
# Compute, for each candidate in 'remaining', the distance to its nearest
# point in 'selected'
cand_indices = np.nonzero(available)[0]
cand_points = points[cand_indices] # shape (m, d)
selected_points = points[np.array(selected)] # shape (s, d)
# Compute pairwise distances: (m, s)
dist_matrix = np.linalg.norm(
cand_points[:, None, :] - selected_points[None, :, :], axis=2
)
# For each candidate, distance to the nearest selected point
min_dist_to_selected = dist_matrix.min(axis=1)
# Pick the candidate with the maximum of these minima
pos = int(np.argmax(min_dist_to_selected))
chosen = int(cand_indices[pos])
selected.append(chosen)
available[chosen] = False
return np.array(selected, dtype=int)
def weighted_maximin_selection(points, weights, k):
"""
Select k points using weighted maximin strategy.
Combines space coverage (maximin) with importance sampling (weights).
Args:
points: Array of shape (n_samples, n_dims)
weights: Array of shape (n_samples,) with sample importance weights
k: Number of points to select
Returns:
selected_indices: Array of selected point indices
"""
n = points.shape[0]
selected = []
available = np.ones(n, dtype=bool)
# 1) Start with weighted probability selection for the first point
# This ensures we start in a high-sensitivity region
probs = weights / weights.sum()
first = np.random.choice(n, p=probs)
selected.append(first)
available[first] = False
# 2) Iteratively add points balancing distance and weight
for _ in range(1, k):
cand_indices = np.nonzero(available)[0]
if len(cand_indices) == 0:
break
cand_points = points[cand_indices]
cand_weights = weights[cand_indices]
selected_points = points[np.array(selected)]
# Compute pairwise distances to selected points
dist_matrix = np.linalg.norm(
cand_points[:, None, :] - selected_points[None, :, :], axis=2
)
# For each candidate, distance to the nearest selected point
min_dist_to_selected = dist_matrix.min(axis=1)
# Normalize distances to [0, 1]
if min_dist_to_selected.max() > 0:
norm_dists = min_dist_to_selected / min_dist_to_selected.max()
else:
norm_dists = np.ones_like(min_dist_to_selected)
# Normalize weights to [0, 1]
if cand_weights.max() > 0:
norm_weights = cand_weights / cand_weights.max()
else:
norm_weights = np.ones_like(cand_weights)
# Combined score: balance distance (70%) and weight (30%)
# Adjust these ratios to prioritize coverage vs sensitivity
scores = 0.7 * norm_dists + 0.3 * norm_weights
# Pick the candidate with the highest combined score
pos = int(np.argmax(scores))
chosen = int(cand_indices[pos])
selected.append(chosen)
available[chosen] = False
return np.array(selected, dtype=int)
def weighted_maximin_selection_with_weight(points, weights, k, coverage_weight=0.5):
"""
Select k points using weighted maximin strategy with adjustable balance.
Combines space coverage (maximin) with importance sampling (weights).
Args:
points: Array of shape (n_samples, n_dims)
weights: Array of shape (n_samples,) with sample importance weights
k: Number of points to select
coverage_weight: Weight for coverage (0-1). Higher = more coverage, less sensitivity bias
Returns:
selected_indices: Array of selected point indices
"""
n = points.shape[0]
selected = []
available = np.ones(n, dtype=bool)
# 1) Start with weighted probability selection for the first point
probs = weights / weights.sum()
first = np.random.choice(n, p=probs)
selected.append(first)
available[first] = False
# 2) Iteratively add points balancing distance and weight
sensitivity_weight = 1.0 - coverage_weight
for i in range(1, k):
if i % 10 == 0:
print(f"Selected {i} of {k} samples...")
cand_indices = np.nonzero(available)[0]
if len(cand_indices) == 0:
break
cand_points = points[cand_indices]
cand_weights = weights[cand_indices]
selected_points = points[np.array(selected)]
# Compute pairwise distances to selected points
dist_matrix = np.linalg.norm(
cand_points[:, None, :] - selected_points[None, :, :], axis=2
)
min_dist_to_selected = dist_matrix.min(axis=1)
# Normalize distances to [0, 1]
if min_dist_to_selected.max() > 0:
norm_dists = min_dist_to_selected / min_dist_to_selected.max()
else:
norm_dists = np.ones_like(min_dist_to_selected)
# Normalize weights to [0, 1]
if cand_weights.max() > 0:
norm_weights = cand_weights / cand_weights.max()
else:
norm_weights = np.ones_like(cand_weights)
# Combined score with adjustable balance
scores = coverage_weight * norm_dists + sensitivity_weight * norm_weights
# Pick the candidate with the highest combined score
pos = int(np.argmax(scores))
chosen = int(cand_indices[pos])
selected.append(chosen)
available[chosen] = False
return np.array(selected, dtype=int)
def iterative_split(samples, N, M, bound_names, max_attempts = 12):
df = pd.DataFrame(data=samples, columns=bound_names)
continuos_cols = [c for c in bound_names if c in ["CS","OS"]]
with warnings.catch_warnings(record=True) as rw:
bin_numeric = KBinsDiscretizer(n_bins=20,encode="ordinal",strategy='uniform')
one_hot_encode = OneHotEncoder(handle_unknown="error",sparse_output=False,)
col_trans1 = ColumnTransformer(transformers=[("bin_numeric",bin_numeric,continuos_cols)],remainder="passthrough",verbose_feature_names_out=False)
col_trans2 = ColumnTransformer(transformers=[("one_hot_encode",one_hot_encode,df.columns)],remainder="drop",verbose_feature_names_out=False)
pp = Pipeline([("col_trans1",col_trans1),("col_trans2",col_trans2)])
pp.set_output(transform="pandas")
one_hot_labels : pd.DataFrame = pp.fit_transform(df) # type: ignore
# Converting to numpy
df = df.to_numpy()
one_hot_labels = one_hot_labels.to_numpy() # type: ignore
# Setup split parameters
subset_size = N/len(samples)
subset = []
attempt = 1
# Loop to ensure that the extracted subset lenght is correct
while attempt < max_attempts:
# Split data
_,_,subset,_ = iterative_train_test_split(df,one_hot_labels,subset_size)
if len(subset) < N:
if attempt == max_attempts:
print(f"Failed to obtain desired number of samples!")
subset_size += 0.025
attempt += 1
else:
break
print(f"Obtained a subset with {len(subset)} samples in {attempt} attempts!")
return subset
def generate_feasible_samples(bounds, sens_funcs, N=128, M=512, max_attempts=12, p_bases=np.array([0.5,0.5,5,5,1]), coverage_weight=0.5):
"""
Two-stage sampling approach:
1. Generate feasible samples with uniform space coverage
2. Select N samples using weighted maximin (balancing coverage and sensitivity)
Args:
bounds: Parameter bounds array
sens_funcs: List of sensitivity functions
N: Target number of samples to select
M: Initial candidate pool size
max_attempts: Maximum attempts to generate enough feasible samples
p_bases: Rounding bases for each parameter
coverage_weight: Weight for space coverage vs sensitivity (0.5 = equal importance)
Returns:
X_selected: Selected samples
M: Final candidate pool size used
"""
if len(bounds) != len(sens_funcs):
raise ValueError(f"Expected bounds and sens_funcs to have the same length. Got {bounds.shape} and {sens_funcs.shape}")
# Filtering input
bounds = np.asarray(bounds,dtype=float)
d = len(bounds)
# Setup sampling loop - generate enough feasible samples for selection
X_feasible = []
target_feasible = N * 3 # Generate 3x more samples than needed for good selection pool
for attempt in range(1, max_attempts+1):
# STAGE 1: Generate uniform Sobol samples for space coverage
sampler = qmc.Sobol(d, scramble=True)
X = sampler.random(n=M)
# Scale to parameter bounds
X_scaled = qmc.scale(X, bounds[:, 0]-p_bases/2, bounds[:, 1]+p_bases/2)
# Round to closest acceptable value
X_rounded = round_samples(X_scaled, p_bases)
# Remove duplicates
X_unique = np.unique(X_rounded, axis=0)
# Applying feasibility filter
feas_mask = check_feasibility_batch(X_unique, bounds)
X_feasible = X_unique[feas_mask]
# Check if we have enough feasible samples
if len(X_feasible) >= target_feasible:
print(f"Generated {len(X_feasible)} feasible samples in {attempt} attempts")
break
else:
# Increase M if not enough points are feasible
M = int(M * 2)
if attempt == max_attempts:
print(f"Warning: Only generated {len(X_feasible)} feasible samples (target was {target_feasible})")
if len(X_feasible) == 0:
raise ValueError("Could not generate any feasible samples with the given settings")
elif len(X_feasible) < N:
raise ValueError(f"Only {len(X_feasible)} feasible samples could be generated, but N={N} required. Increase M or max_attempts.")
# STAGE 2: Select N samples using weighted maximin selection
print(f"Selecting {N} samples from {len(X_feasible)} feasible candidates...")
weights = compute_sample_weights(X_feasible, sens_funcs, bounds)
# Adjust the weighted_maximin_selection to use the coverage_weight parameter
# (We'll pass it directly in the call)
selected_indices = weighted_maximin_selection_with_weight(X_feasible, weights, N, coverage_weight)
X_selected = X_feasible[selected_indices]
print(f"Selected {len(X_selected)} samples balancing space coverage and sensitivity")
return X_selected, M
def validate_samples(samples,bounds,sens_funcs):
print("Checking if constraints were respected")
valid = check_feasibility_batch(samples,bounds)
if any(valid == False):
raise ValueError("At least one samples does not respect the provided constraints")
print("Checking if any samples are identical")
if len(np.unique(samples, axis=0)) != len(samples):
raise ValueError("At least one identical pair of parameters found")
print("Validation complete")
def round_samples(samples,p_bases):
for i in range(len(p_bases)):
samples[:,i] = round_to_base(samples[:,i],p_bases[i])
return samples
def round_to_base(x,base=1):
return base*np.rint(x/base)
def main():
bound_names = ["CA","OA","CS","OS","AF"]
N = 50 # target samples
M = 2048 # candidate pool size
csv_name = "samples_filling.csv"
csv_path = "."
csv_path = os.path.join(csv_path,csv_name)
# Define parameter bounds
bounds = np.array([
[-10.0, 5.0], # CA
[-10.0, 10.0], # OA
[550.0, 700.0], # CS
[350.0, 700.0], # OS
[-8.5, 20.0] # AF
], dtype=float)
d = bounds.shape[0]
# ========== SENSITIVITY FUNCTION DATA ==========
# Define your parameter values, lift coefficients (CL), and drag coefficients (CD)
# Aerodynamic efficiency will be calculated as CL/CD
# s1: CA parameter
s1_param_values = np.array([-10,-8,-6,-4,-2,0,2,4,5])
s1_lift = np.array([2.71597,2.59168,2.38756,2.11036,1.79931,1.46873,1.13276,0.79852,0.63399]) # Replace with CL values
s1_drag = np.array([0.19559,0.16673,0.13793,0.11181,0.08745,0.06607,0.04852,0.03574,0.03121]) # Replace with CD values
# s2: OA parameter
s2_param_values = np.array([-10,-8,-6,-4,-2,0,2,4,6,8,10])
s2_lift = np.array([2.11753,2.00106,1.87441,1.74326,1.60771,1.46873,1.32822,1.18505,1.03937,0.88601,0.72393]) # Replace with CL values
s2_drag = np.array([0.12137,0.10840,0.09681,0.08580,0.07550,0.06607,0.05760,0.05028,0.04426,0.04071,0.04110]) # Replace with CD values
# s3: CS parameter
s3_param_values = np.array([700,675,650,625,600,575,550])
s3_lift = np.array([1.59557,1.56641,1.53579,1.50281,1.46873,1.43109,1.39120]) # Replace with CL values
s3_drag = np.array([0.07392,0.07200,0.07008,0.06806,0.06607,0.06395,0.06179]) # Replace with CD values
# s4: OS parameter
s4_param_values = np.array([700,650,600,550,500,455,400,350])
s4_lift = np.array([1.76696,1.72398,1.67319,1.60908,1.53883,1.46873,1.37725,1.29316]) # Replace with CL values
s4_drag = np.array([0.08746,0.08379,0.07981,0.07517,0.07047,0.06607,0.06063,0.05588]) # Replace with CD values
# s5: AF parameter
s5_param_values = np.array([-8.5,-4,0,4,8,12,16,20])
s5_lift = np.array([1.31019,1.35985,1.39354,1.42229,1.45279,1.48344,1.50923,1.53197]) # Replace with CL values
s5_drag = np.array([0.05940,0.06138,0.06270,0.06387,0.06528,0.06673,0.06792,0.06904]) # Replace with CD values
# ========== CREATE INTERPOLATORS FOR LIFT AND DRAG (built once for efficiency) ==========
_s1_lift_interp = interpolate.make_interp_spline(s1_param_values, s1_lift, k=3)
_s1_drag_interp = interpolate.make_interp_spline(s1_param_values, s1_drag, k=3)
_s1_lift_deriv = _s1_lift_interp.derivative()
_s1_drag_deriv = _s1_drag_interp.derivative()
_s2_lift_interp = interpolate.make_interp_spline(s2_param_values, s2_lift, k=3)
_s2_drag_interp = interpolate.make_interp_spline(s2_param_values, s2_drag, k=3)
_s2_lift_deriv = _s2_lift_interp.derivative()
_s2_drag_deriv = _s2_drag_interp.derivative()
_s3_lift_interp = interpolate.make_interp_spline(np.flip(s3_param_values), np.flip(s3_lift), k=3)
_s3_drag_interp = interpolate.make_interp_spline(np.flip(s3_param_values), np.flip(s3_drag), k=3)
_s3_lift_deriv = _s3_lift_interp.derivative()
_s3_drag_deriv = _s3_drag_interp.derivative()
_s4_lift_interp = interpolate.make_interp_spline(np.flip(s4_param_values), np.flip(s4_lift), k=3)
_s4_drag_interp = interpolate.make_interp_spline(np.flip(s4_param_values), np.flip(s4_drag), k=3)
_s4_lift_deriv = _s4_lift_interp.derivative()
_s4_drag_deriv = _s4_drag_interp.derivative()
_s5_lift_interp = interpolate.make_interp_spline(s5_param_values, s5_lift, k=3)
_s5_drag_interp = interpolate.make_interp_spline(s5_param_values, s5_drag, k=3)
_s5_lift_deriv = _s5_lift_interp.derivative()
_s5_drag_deriv = _s5_drag_interp.derivative()
# ========== SENSITIVITY FUNCTIONS ==========
def s1(p):
return np.abs(_s1_lift_deriv(p)) + np.abs(_s1_drag_deriv(p))
def s2(p):
return np.abs(_s2_lift_deriv(p)) + np.abs(_s2_drag_deriv(p))
def s3(p):
return np.abs(_s3_lift_deriv(p)) + np.abs(_s3_drag_deriv(p))
def s4(p):
return np.abs(_s4_lift_deriv(p)) + np.abs(_s4_drag_deriv(p))
def s5(p):
return np.abs(_s5_lift_deriv(p)) + np.abs(_s5_drag_deriv(p))
sens_funcs = [s1, s2, s3, s4, s5]
# Generate the samples using two-stage approach
# This now returns exactly N samples that balance space coverage and sensitivity
samples,M = generate_feasible_samples(bounds=bounds,sens_funcs=sens_funcs,N=N,M=M,coverage_weight=0.5)
# Validate the samples
validate_samples(samples,bounds,sens_funcs)
# Add column for profile
profile_sampler = qmc.Sobol(1,scramble=True)
profile_samples = profile_sampler.random(n=len(samples))
profile_samples = qmc.scale(profile_samples,0.5,12.5)
profile_samples = round_to_base(profile_samples,base=1)
samples = np.c_[profile_samples,samples]
print("Saving to file...")
try:
np.savetxt(csv_name,samples,delimiter=",",header="P,"+",".join(bound_names),fmt='%f')
print(f"Saved {csv_name}!")
except:
raise RuntimeError("Could not save .csv file")
if __name__ == "__main__":
main()