Skip to content

Commit

Permalink
DOC: Update examples documentation (#78)
Browse files Browse the repository at this point in the history
Co-authored-by: Lucas Boucinha <[email protected]>
Co-authored-by: Kathy Pippert <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored Feb 17, 2023
1 parent 7d46ed1 commit ae2bac2
Show file tree
Hide file tree
Showing 8 changed files with 270 additions and 232 deletions.
2 changes: 1 addition & 1 deletion examples/README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
=========
Examples
=========
End-to-end examples show how you can use PyTwin. If the PyTwin ``pytwin`` package is installed on your machine,
End-to-end examples show how you can use PyTwin. If the ``pytwin`` package is installed on your machine,
you can download these examples as Python files or Jupyter notebooks and run them locally.

.. toctree::
Expand Down
74 changes: 35 additions & 39 deletions examples/evaluate/00-coupledClutches.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
""".. _ref_example_coupledClutches:
Twin evaluation example
---------------------------------------
This example shows how you can use PyTwin to load and evaluate a Twin model.
The model consists in a coupled clutches with 4 inputs (applied torque,
3 clutches opening) and 3 outputs (computed torque on each of the clutches)
Twin evaluation
---------------
This example shows how you can use PyTwin to load and evaluate a twin model.
The model consists of three coupled clutches. It has four inputs (applied torque
and the three clutch openings) and three outputs (the computed torque on each clutch).
"""

###############################################################################
Expand All @@ -17,8 +17,8 @@
###############################################################################
# Perform required imports
# ~~~~~~~~~~~~~~~~~~~~~~~~
# Perform required imports, which includes downloading and importing the
# input files
# Perform required imports, which include downloading and importing the
# input files.

import matplotlib.pyplot as plt
import pandas as pd
Expand All @@ -30,21 +30,21 @@


###############################################################################
# Auxiliary functions definition
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Post processing for results comparison.
# Define auxiliary functions
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define auxiliary functions for comparing and plotting the results from
# different simulations executed on the same twin model.


def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd.DataFrame):
"""Compare the results obtained from 2 different simulations executed
on the same TwinModel. The 2 results dataset are provided as Pandas
Dataframe. The function will plot the different results for all the
outputs"""
"""Compare the results obtained from two different simulations executed
on the same twin model. The two results datasets are provided as Pandas
dataframes. The function plots the results for all the outputs."""
pd.set_option("display.precision", 12)
pd.set_option("display.max_columns", 20)
pd.set_option("display.expand_frame_repr", False)

# Plotting the runtime outputs
# Plot the runtime outputs
columns = step_by_step_results.columns[1::]
result_sets = 2 # Results from only step-by-step, batch_mode
fig, ax = plt.subplots(ncols=result_sets, nrows=len(columns), figsize=(18, 7))
Expand All @@ -70,7 +70,7 @@ def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd
axes0.legend(loc=2)
axes0.set_xlabel("Time [s]")

# Plot Twin batch mode csv results
# Plot twin results in CSV file in batch mode
batch_results.plot(x=0, y=col_name, ax=axes1, ls="-.", color="g", title="Twin Runtime - Batch Mode")
axes1.legend(loc=2)
axes1.set_xlabel("Time [s]")
Expand All @@ -84,10 +84,9 @@ def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd


###############################################################################
# Loading the Twin Runtime and external CSV file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Loading the Twin Runtime and instantiating it.

# Load the twin runtime and external CSV file
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Load the twin runtime and instantiate it.

print("Loading model: {}".format(twin_file))
twin_model = TwinModel(twin_file)
Expand All @@ -96,23 +95,21 @@ def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd
number_of_datapoints = data_dimensions[0] - 1

###############################################################################
# Setting up the initial settings of the Twin and initializing it
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Defining the initial inputs of the Twin, initializing it and collecting
# the initial outputs values

# Define the initial inputs of the twin model and initialize it
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define the inputs of the twin model, initialize it, and collect
# the output values.

twin_model.initialize_evaluation(json_config_filepath=twin_config)
outputs = [twin_model.evaluation_time]
for item in twin_model.outputs:
outputs.append(twin_model.outputs[item])

###############################################################################
# Step by step simulation mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Looping over all the input data, simulating the Twin one time step at a
# time and collecting corresponding outputs

# Simulate the twin in step by step mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Loop over all inputs, simulating the twin at each time step
# and collecting the corresponding output values.

sim_output_list_step = [outputs]
data_index = 0
Expand All @@ -132,12 +129,11 @@ def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd
results_step_pd = pd.DataFrame(sim_output_list_step, columns=["Time"] + list(twin_model.outputs), dtype=float)

###############################################################################
# Batch simulation mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Resetting/re-initializing the Twin and running it in batch mode (i.e. passing
# all the input data, simulating all the data points, and collecting all
# the outputs at once)

# Simulate the twin in batch mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Reset/re-initialize the twin and run the simulation in batch mode, which
# passes all the input data, simulates all the data points, and collects all
# the outputs at once.

data_index = 0
inputs = dict()
Expand All @@ -150,8 +146,8 @@ def plot_result_comparison(step_by_step_results: pd.DataFrame, batch_results: pd
results_batch_pd = twin_model.evaluate_batch(twin_model_input_df)

###############################################################################
# Post processing
# ~~~~~~~~~~~~~~~~~~~
# Plotting the different results and saving the image on disk
# Plot results
# ~~~~~~~~~~~~
# Plot the results and save the images on disk.

plot_result_comparison(results_step_pd, results_batch_pd)
79 changes: 41 additions & 38 deletions examples/evaluate/01-electricRange.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
""".. _ref_example_electricRange:
Parametric dynamic Twin evaluation example
------------------------------------------
This example shows how you can
use PyTwin to load and evaluate a Twin model and simulate multiple
parametric variations. The model is used for determining the range of an
electric vehicle. The vehicle is represented by a battery, the electric
loads of the vehicle, and an electric machine connected to a simple 1D
chassis. The driver controls the vehicle speed to follow a repeated
sequence of the WLTP cycle (class 3). The mass of the vehicle as well
as the electric power loads are parameterized so that we can see their
effects on the overall electric range
Parametric dynamic twin evaluation
----------------------------------
This example shows how you can use PyTwin to load and evaluate a twin model
and simulate multiple parametric variations. The model is used for
determining the range of an electric vehicle. The vehicle is represented
by a battery, the electric loads of the vehicle, and an electric machine
connected to a simple 1D chassis. The driver controls the vehicle speed
to follow a repeated sequence of the WLTP cycle (class 3). The mass of the
vehicle and the electric power loads are parameterized so that their
effects on the overall electric range can be seen.
"""

###############################################################################
Expand All @@ -23,7 +22,8 @@
###############################################################################
# Perform required imports
# ~~~~~~~~~~~~~~~~~~~~~~~~
# Perform required imports, which includes downloading and importing the input files
# Perform required imports, which include downloading and importing the input
# files.

import matplotlib.pyplot as plt
import pandas as pd
Expand All @@ -32,31 +32,32 @@
twin_file = download_file("ElectricRange_23R1_other.twin", "twin_files")

###############################################################################
# Auxiliary functions definition
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Definition of plot_result_comparison for post-processing the results
# Define auxiliary functions
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define auxiliary functions for comparing and plotting the results from
# different parametric simulations executed on the same twin model.


def plot_result_comparison(results: list[pd.DataFrame], sweep: list[dict]):
"""Compare the results obtained from the different parametric simulations executed on the same TwinModel. The
results dataset are provided as Pandas Dataframe. The function will plot the different results for few particular
variables of interest"""
"""Compare the results obtained from the different parametric simulations executed
on the same TwinModel. The results datasets are provided as Pandas dataframes. The
function plots the results for a few variables of particular interest."""

pd.set_option("display.precision", 12)
pd.set_option("display.max_columns", 20)
pd.set_option("display.expand_frame_repr", False)

color = ["g", "b", "r"]
# output ordering : time, battery_loss, loads_loss, machine_loss, pack_SoC, position, speed_m, speed_ref,
# tau_ref, tau_sns
# Output ordering: time, battery_loss, loads_loss, machine_loss, pack_SoC, position,
# speed_m, speed_ref, tau_ref, tau_sns
x0_ind = 0
y0_ind = 6
z0_ind = 7
x1_ind = 4
y1_ind = 5

# Plotting the runtime outputs
# We will plot 2 different results : the drive cycle results as well as the distance
# achieved vs battery state of charge for all the parametric variations
# Plot the runtime outputs for two results: the drive cycle and the distance
# achieved versus the battery state of the charge for all parametric variations
fig, ax = plt.subplots(ncols=1, nrows=2, figsize=(18, 7))

fig.subplots_adjust(hspace=0.5)
Expand Down Expand Up @@ -88,35 +89,37 @@ def plot_result_comparison(results: list[pd.DataFrame], sweep: list[dict]):


###############################################################################
# Loading the Twin Runtime and instantiating it
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Loading the Twin Runtime and instantiating it.

# Load the twin runtime and instantiate it
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Load the twin runtime and instantiate it.

print("Loading model: {}".format(twin_file))
twin_model = TwinModel(twin_file)

###############################################################################
# User inputs
# ~~~~~~~~~~~~~~~~~~~~~~~~
# Defining user inputs and simulation settings
# Define inputs and simulation settings
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define the inputs and simulation settings.

time_step = 1.0
time_end = 24000.0 # simulating the model for 400 minutes
time_end = 24000.0 # Simulate the model for 400 minutes
print("Twin parameters : {}".format(twin_model.parameters))
dp1 = {"ElectricRange_powerLoad": 2000.0, "ElectricRange_vehicleMass": 2000.0}
dp2 = {"ElectricRange_powerLoad": 3000.0, "ElectricRange_vehicleMass": 2000.0}
dp3 = {"ElectricRange_powerLoad": 2000.0, "ElectricRange_vehicleMass": 1500.0}
sweep = [dp1, dp2, dp3]

###############################################################################
# Parametric sweep over the different design points
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Simulating the Twin for each set of parameters values, one time step at a time and collecting corresponding outputs
# Simulate the twin for each set of parameter values
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Simulate the twin for each set of parameters values for each time step
# and collect corresponding output values.

results = []
for dp in sweep:
# Twin initialization with the right parameters values and collection of initial outputs values
# Initialize twin model with the correct parameters values and collect
# initial output values

twin_model.initialize_evaluation(parameters=dp)
outputs = [twin_model.evaluation_time]
for item in twin_model.outputs:
Expand All @@ -137,8 +140,8 @@ def plot_result_comparison(results: list[pd.DataFrame], sweep: list[dict]):
results.append(sim_results)

###############################################################################
# Post processing
# ~~~~~~~~~~~~~~~~~~~
# Plotting the different results and saving the image on disk
# Plot results
# ~~~~~~~~~~~~
# Plot the results and save the images on disk.

plot_result_comparison(results, sweep)
Loading

0 comments on commit ae2bac2

Please sign in to comment.