|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import numpy as np |
| 5 | +from matplotlib.patches import Ellipse |
| 6 | + |
| 7 | +from rocketpy.stochastic.post_processing.stochastic_cache import \ |
| 8 | + SimulationCache |
| 9 | + |
| 10 | +# 1-3 sigma |
| 11 | +lower_percentiles = [0.16, 0.03, 0.003] |
| 12 | +upper_percentiles = [0.84, 0.97, 0.997] |
| 13 | + |
| 14 | + |
| 15 | +# Define function to calculate eigen values |
| 16 | +def eigsorted(cov): |
| 17 | + vals, vecs = np.linalg.eigh(cov) |
| 18 | + order = vals.argsort()[::-1] |
| 19 | + return vals[order], vecs[:, order] |
| 20 | + |
| 21 | + |
| 22 | +def compute_impact(file_name, batch_path, save, show): |
| 23 | + cache = SimulationCache( |
| 24 | + file_name, |
| 25 | + batch_path, |
| 26 | + ) |
| 27 | + x_impact = cache.read_outputs('x_impact') |
| 28 | + y_impact = cache.read_outputs('y_impact') |
| 29 | + |
| 30 | + x_mean_impact = np.nanmean(x_impact, axis=0) |
| 31 | + y_mean_impact = np.nanmean(y_impact, axis=0) |
| 32 | + |
| 33 | + # Calculate error ellipses for impact |
| 34 | + impact_cov = np.cov(x_impact.flatten(), y_impact.flatten()) |
| 35 | + impact_vals, impactVecs = eigsorted(impact_cov) |
| 36 | + impact_theta = np.degrees(np.arctan2(*impactVecs[:, 0][::-1])) |
| 37 | + impact_w, impactH = 2 * np.sqrt(impact_vals) |
| 38 | + |
| 39 | + fig, ax = plt.subplots() |
| 40 | + ax.scatter(x_impact, y_impact, c='blue') |
| 41 | + ax.scatter( |
| 42 | + x_mean_impact, |
| 43 | + y_mean_impact, |
| 44 | + marker='x', |
| 45 | + c='red', |
| 46 | + label='Mean Impact Point', |
| 47 | + ) |
| 48 | + |
| 49 | + # Draw error ellipses for impact |
| 50 | + impact_ellipses = [] |
| 51 | + for j in [1, 2, 3]: |
| 52 | + impactEll = Ellipse( |
| 53 | + xy=(np.mean(x_impact), np.mean(y_impact)), |
| 54 | + width=impact_w * j, |
| 55 | + height=impactH * j, |
| 56 | + angle=impact_theta, |
| 57 | + color="black", |
| 58 | + ) |
| 59 | + impactEll.set_facecolor((0, 0, 1, 0.2)) |
| 60 | + impact_ellipses.append(impactEll) |
| 61 | + ax.add_artist(impactEll) |
| 62 | + |
| 63 | + ax.set_xlabel('X Impact Point [m]') |
| 64 | + ax.set_ylabel('Y Impact Point [m]') |
| 65 | + ax.set_title('Impact Point Distribution') |
| 66 | + ax.set_aspect('equal') |
| 67 | + ax.legend() |
| 68 | + ax.grid() |
| 69 | + |
| 70 | + if save: |
| 71 | + plt.savefig(batch_path / 'mean_impact_distribution.png') |
| 72 | + |
| 73 | + if show: |
| 74 | + plt.show() |
| 75 | + plt.show() |
| 76 | + |
| 77 | + |
| 78 | +def run(file_name, batch_path, save, show): |
| 79 | + compute_impact(file_name, batch_path, save, show) |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == '__main__': |
| 83 | + # import easygui |
| 84 | + |
| 85 | + batch_path = Path("mc_simulations/") |
| 86 | + file_name = 'monte_carlo_class_example' |
| 87 | + run(file_name, batch_path, save=True, show=True) |
0 commit comments