Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
aqitya committed Aug 1, 2023
1 parent 89af074 commit 4a0af20
Show file tree
Hide file tree
Showing 11 changed files with 202 additions and 109 deletions.
109 changes: 96 additions & 13 deletions examples/horizon.ipynb

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions examples/horizon.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def future_loading(t, x = None):
# THIS IS WHERE WE DIVERGE FROM THE THROWN_OBJECT_EXAMPLE
# Here we set a prediction horizon
# We're saying we are not interested in any events that occur after this time
PREDICTION_HORIZON = 7.75
PREDICTION_HORIZON = 5
samples = filt.x # Since we're using a particle filter, which is also sample-based, we can directly use the samples, without changes
STEP_SIZE = 0.01
mc_results = mc.predict(samples, future_loading, dt=STEP_SIZE, horizon = PREDICTION_HORIZON)
Expand All @@ -60,7 +60,7 @@ def future_loading(t, x = None):
mc_results.time_of_event.plot_hist(keys = 'impact')
mc_results.time_of_event.plot_hist(keys = 'falling')

print("\nSamples where impact occurs before horizon: {:.2f}%".format(metrics['impact']['number of samples']/NUM_SAMPLES*100))
print("\nSamples where impact occurs before horizon: {:.2f}%".format(metrics['impact']['number of samples']/100 * 100))

# Step 4: Show all plots
import matplotlib.pyplot as plt # For plotting
Expand Down
2 changes: 1 addition & 1 deletion examples/kalman_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# Linear Model for an object thrown into the air
class ThrownObject(LinearModel):
"""
Model that similates an object thrown into the air without air resistance
Model that simulates an object thrown into the air without air resistance
Events (2)
| falling: The object is falling
Expand Down
2 changes: 1 addition & 1 deletion examples/new_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def future_load(t, x=None):
print('The object hit the ground in {} seconds'.format(round(simulated_results.times[-1],2)))

# OK, now lets compare performance on different heavenly bodies.
# This requires that we update the cofiguration
# This requires that we update the configuration
grav_moon = -1.62

# The first way to change the configuration is to pass in your desired config into construction of the model
Expand Down
39 changes: 15 additions & 24 deletions examples/pce.ipynb

Large diffs are not rendered by default.

19 changes: 13 additions & 6 deletions examples/sensitivity.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
"eods = np.empty(len(thrower_height_range))\n",
"for (i, thrower_height) in zip(range(len(thrower_height_range)), thrower_height_range):\n",
" m.parameters['thrower_height'] = thrower_height\n",
" simulated_results = m.simulate_to_threshold(future_load, threshold_keys=[event], dt =1e-3, save_freq =10)\n",
" simulated_results = m.simulate_to_threshold(threshold_keys=[event], dt =1e-3, save_freq =10)\n",
" eods[i] = simulated_results.times[-1]"
]
},
Expand All @@ -117,7 +117,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"What we are doing here is very simple. We are looping through each of the results of our simulations, and calculating the difference between the time of impact of the thrown object and the time of impact of the thrown object when the thrower_height is 1.5 meters. This is the sensitivity of the model's predictions to changes in the thrower_height parameter.\n",
"What we are doing here is very simple. We are looping through each of the results of our simulations, and calculating the difference between the time of impact of the thrown object and the time of impact of the thrown object when the thrower_height is 1.83 meters. This is the sensitivity of the model's predictions to changes in the thrower_height parameter.\n",
"\n",
"We do this by taking the difference in impact times between the maximum and minimum thrower heights `(eods[-1]-eods[0])`, and dividing this by the difference in thrower heights `(thrower_height_range[-1] - thrower_height_range[0])`. The result is a measure of how much the impact time changes, on average, for a unit change in thrower height."
]
Expand All @@ -140,7 +140,7 @@
"eods = np.empty(len(throw_speed_range))\n",
"for (i, throw_speed) in zip(range(len(throw_speed_range)), throw_speed_range):\n",
" m.parameters['throwing_speed'] = throw_speed\n",
" simulated_results = m.simulate_to_threshold(future_load, threshold_keys=[event], options={'dt':1e-3, 'save_freq':10})\n",
" simulated_results = m.simulate_to_threshold(threshold_keys=[event], options={'dt':1e-3, 'save_freq':10})\n",
" eods[i] = simulated_results.times[-1]\n",
"\n",
"\n",
Expand All @@ -162,9 +162,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"To conclude, the sensitivity analysis was performed by systematically varying the `thrower_height` and `throwing_speed` parameters of the `ThrownObject` model. The model's predictions (e.g., the time of impact of the thrown object) were then recorded for each set of parameters, and the sensitivity of the model's predictions to changes in these parameters was assessed.\n",
"### Conclusion"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The sensitivity analysis was performed by systematically varying the `thrower_height` and `throwing_speed` parameters of the `ThrownObject` model. The model's predictions (e.g., the time of impact of the thrown object) were then recorded for each set of parameters, and the sensitivity of the model's predictions to changes in these parameters was assessed.\n",
"\n",
"For more information on ProgPy and its capabilities, please visit the [ProgPy documentation](https://nasa.github.io/progpy/)!"
"For more information on ProgPy and its capabilities, please visit the [ProgPy documentation](https://nasa.github.io/progpy/)."
]
}
],
Expand All @@ -184,7 +191,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
"version": "3.11.4"
},
"orig_nbformat": 4
},
Expand Down
69 changes: 47 additions & 22 deletions examples/serialization.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,38 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"##### __METHOD 1: Serialize with JSON__"
"##### __METHOD 1: Serialize with Pickle__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, let's demonstrate how to serialize a model using the `to_json` method."
"First, let's demonstrate how to serialize a model using the `pickle` package."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pickle.dump(batt, open('model_save_pkl.pkl','wb'))\n",
"load_pkl = pickle.load(open('model_save_pkl.pkl','rb'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### __METHOD 2: Serialize with JSON__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, let's demonstrate how to serialize a model using the `to_json` method."
]
},
{
Expand Down Expand Up @@ -119,31 +143,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"##### __METHOD 2: Serialize with Pickle__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, let's demonstrate how to serialize a model using the `pickle` package."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pickle.dump(batt, open('model_save_pkl.pkl','wb'))\n",
"load_pkl = pickle.load(open('model_save_pkl.pkl','rb'))"
"### Comparing the simulations of the serialized models"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use ProgPy's [Simulation](https://nasa.github.io/progpy/prog_models_guide.html#simulation) methods to simulate the model to threshold and compare the results of the serialization methods.\n",
"We can use ProgPy's [Simulation](https://nasa.github.io/progpy/prog_models_guide.html#simulation) methods to simulate the model to threshold and compare the results of the serializations.\n",
"\n",
"First, we'll need to define our [Future Loading Profile](https://nasa.github.io/progpy/prog_models_guide.html#future-loading)."
]
Expand Down Expand Up @@ -234,6 +241,24 @@
"\n",
"print(f\"The simulated results from the original and serialized models are {'identical. This means that our serialization works!' if are_arrays_same else 'not identical. This means that our serialization does not work.'}!\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conclusion\n",
"\n",
"In this notebook, we explored how serialization can be used in ProgPy. We learned how to utilize the `pickle` module to serialize and deserialize ProgPy models. We also explored alternative serialization formats like JSON.\n",
"\n",
"Overall, understanding how to serialize and deserialize models can be a powerful tool for Prognostics developers. It allows you to save your models to disk and load them back into memory at a later time. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For more information on ProgPy, please refer to the ProgPy [Documentation](https://nasa.github.io/progpy/)."
]
}
],
"metadata": {
Expand All @@ -252,7 +277,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
"version": "3.11.4"
},
"orig_nbformat": 4
},
Expand Down
4 changes: 2 additions & 2 deletions examples/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def run_example():
## Step 1: Create a model object
batt = Battery()

# Set process nosie to 0 to illustrate match between original and serialized versions
# Set process noise to 0 to illustrate match between original and serialized versions
batt.parameters['process_noise'] = 0

### Step 2: serialize model for future use
Expand All @@ -27,7 +27,7 @@ def run_example():
# Serialized result can also be saved to a text file and uploaded later using the following code:
txtFile = open("model_save_json.txt", "w")
txtFile.write(save_json)
txtFile.close()
txtFile.close()

with open('model_save_json.txt') as infile:
load_json = infile.read()
Expand Down
9 changes: 1 addition & 8 deletions examples/sim_pump.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -208,13 +208,6 @@
"thresholds_met = SimResult(simulated_results.times, thresholds_met)\n",
"thresholds_met.plot(compact = False, title = 'Threshold Met', xlabel = 'time', ylabel = '', tight_layout=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand All @@ -233,7 +226,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
"version": "3.11.4"
},
"orig_nbformat": 4
},
Expand Down
37 changes: 12 additions & 25 deletions examples/sim_value.ipynb → examples/sim_valve.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"### Importing Modules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll be using ProgPy's [PneumaticValue](https://nasa.github.io/progpy/api_ref/prog_models/IncludedModels.html#pneumatic-valve) Model for this example!"
"We'll be using ProgPy's [PneumaticValve](https://nasa.github.io/progpy/api_ref/prog_models/IncludedModels.html#pneumatic-valve) Model for this example!"
]
},
{
Expand All @@ -45,6 +38,13 @@
"- `pDiff`: This is the difference in pressure between the left and right sides of the valve.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Importing Modules"
]
},
{
"cell_type": "code",
"execution_count": null,
Expand Down Expand Up @@ -160,20 +160,15 @@
"metadata": {},
"outputs": [],
"source": [
"# Simulate to threshold\n",
"print('\\n\\n------------------------------------------------')\n",
"print('Simulating to threshold\\n\\n')\n",
"# Configure options\n",
"config = {\n",
" 'dt': 0.1,\n",
" 'horizon': 800,\n",
" 'save_freq': 60,\n",
" # 'print': True,\n",
" # 'progress': True,\n",
"}\n",
"# Simulate\n",
"# Simulate to Threshold\n",
"simulated_results = valv.simulate_to_threshold(future_loading, first_output, **config)\n",
"simulated_results.outputs.plot(compact = False, title = 'Outputs', xlabel = 'time', ylabel = '') # Plots may show up twice. Product of Jupyter Notebook."
"simulated_results.outputs.plot(compact = False, title = 'Outputs', xlabel = 'time', ylabel = '', tight_layout=True) # Plots may show up twice. Product of Jupyter Notebook."
]
},
{
Expand Down Expand Up @@ -237,9 +232,6 @@
"metadata": {},
"outputs": [],
"source": [
"print('\\n\\n------------------------------------------------')\n",
"print('Simulating to threshold\\n\\n')\n",
"\n",
"simulated_results = valv.simulate_to_threshold(future_loading, first_output, **config)\n",
"simulated_results.outputs.plot(compact = False, title = 'Outputs', xlabel = 'time', ylabel = '', tight_layout=True) # Plots may show up twice. Product of Jupyter Notebook."
]
Expand All @@ -250,13 +242,8 @@
"source": [
"To conclude, the `PneumaticValue` model in ProgPy is a great tool for simulating the behavior of a pneumatic valve as it degrades over time. It can be used to gain insights into the performance of the valve and predict when it will fail.\n",
"\n",
"For more information, please refer to our [Pneumatic Value](https://nasa.github.io/progpy/api_ref/prog_models/IncludedModels.html#pneumatic-valve) documentation. For more information on ProgPy, please refer to the [ProgPy Documentation](https://nasa.github.io/progpy/index.html)!"
"For more information, please refer to our [Pneumatic Value Documentation](https://nasa.github.io/progpy/api_ref/prog_models/IncludedModels.html#pneumatic-valve). For more information on ProgPy, please refer to the [ProgPy Documentation](https://nasa.github.io/progpy/index.html)!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"metadata": {
Expand All @@ -275,7 +262,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
"version": "3.11.4"
},
"orig_nbformat": 4
},
Expand Down
17 changes: 12 additions & 5 deletions examples/state_limits.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that our `x` position never reaches a negative value! This is because we have defined a state limit for the `x` state that prevents it from going below __0__. This makes our simulation more realistic!"
"Notice that our `x` position never reaches a negative value! This is because we have defined a state limit for the `x` state that prevents it from going below __0__ (see _Warning_ above). This makes our simulation more realistic!"
]
},
{
Expand All @@ -161,7 +161,7 @@
"x0 = m.initialize(u = {}, z = {})\n",
"x0['x'] = -1\n",
"\n",
"simulated_results = m.simulate_to_threshold(future_load, threshold_keys=[event], dt=0.005, save_freq=1, x = x0)\n",
"simulated_results = m.simulate_to_threshold(threshold_keys=[event], dt=0.005, save_freq=1, x = x0)\n",
"\n",
"# Print states\n",
"print('Example 2: With -1 as initial x value')\n",
Expand Down Expand Up @@ -196,7 +196,7 @@
"m.parameters['g'] = -50000000\n",
"\n",
"print('Example 3')\n",
"simulated_results = m.simulate_to_threshold(future_load, threshold_keys=[event], dt=0.005, save_freq=0.3, x = x0, print = True, progress = False)\n",
"simulated_results = m.simulate_to_threshold(threshold_keys=[event], dt=0.005, save_freq=0.3, x = x0, print = True, progress = False)\n",
"\n",
"# Note that the limits can also be applied manually using the apply_limits function\n",
"print('limiting states')\n",
Expand All @@ -210,7 +210,14 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"In conclusion, setting appropriate state limits is crucial in creating realistic and accurate state-transition models. It ensures that the model's behavior stays within realistic bounds, regardless of the conditions or variables applied. Keep in mind that the limits should be set based on the physical or practical constraints of the system being modeled.\n",
"### Conclusion"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Setting appropriate state limits is crucial in creating realistic and accurate state-transition models. It ensures that the model's behavior stays within realistic bounds, regardless of the conditions or variables applied. Keep in mind that the limits should be set based on the physical or practical constraints of the system being modeled.\n",
"\n",
"For more information, please refer to our [State Limits](https://nasa.github.io/progpy/prog_models_guide.html#state-limits) documentation. For more information on ProgPy, please refer to our [ProgPy](https://nasa.github.io/progpy/) documentation."
]
Expand All @@ -232,7 +239,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
"version": "3.11.4"
},
"orig_nbformat": 4
},
Expand Down

0 comments on commit 4a0af20

Please sign in to comment.