fastoad.api module
This module gathers key FAST-OAD classes and functions for convenient import.
- fastoad.api.evaluate_problem(configuration_file_path: str | PathLike, overwrite: bool = False) FASTOADProblem [source]
Runs model according to provided problem file
- Parameters:
configuration_file_path – problem definition
overwrite – if True, output file will be overwritten
- Returns:
the OpenMDAO problem after run
- Raises:
FastPathExistsError – if overwrite==False and output data file of problem already exists
- fastoad.api.generate_configuration_file(configuration_file_path: str | PathLike, overwrite: bool = False, distribution_name=None, sample_file_name=None)[source]
Copies a sample configuration file from an available plugin.
- Parameters:
configuration_file_path – the path of file to be written
overwrite – if True, the file will be written, even if it already exists
distribution_name – the name of the installed package that provides the sample configuration file (can be omitted if only one plugin is available)
sample_file_name – the name of the sample configuration file (can be omitted if the plugin provides only one configuration file)
- Returns:
path of generated file
- Raises:
FastPathExistsError – if overwrite==False and configuration_file_path already exists
- fastoad.api.generate_inputs(configuration_file_path: str | PathLike, source_data_path: str | PathLike = None, source_data_path_schema='native', overwrite: bool = False) str [source]
Generates input file for the problem specified in configuration_file_path.
- Parameters:
configuration_file_path – where the path of input file to write is set
source_data_path – path of source data file data will be taken from
source_data_path_schema – set to ‘legacy’ if the source file come from legacy FAST
overwrite – if True, file will be written even if one already exists
- Returns:
path of generated file
- Raises:
FastPathExistsError – if overwrite==False and configuration_file_path already exists
- fastoad.api.generate_notebooks(destination_path: str | PathLike, overwrite: bool = False, distribution_name=None)[source]
Copies notebook folder(s) from available plugin(s).
- Parameters:
destination_path – the inner structure of the folders will depend on the number of installed package and the number of plugins they contain.
overwrite – if True and destination_path exists, it will be removed before writing.
distribution_name – the name of an installed package that provides notebooks
- fastoad.api.generate_source_data_file(source_data_file_path: str | PathLike, overwrite: bool = False, distribution_name=None, sample_file_name=None)[source]
Copies a sample source data file from an available plugin.
- Parameters:
source_data_file_path – the path of file to be written
overwrite – if True, the file will be written, even if it already exists
distribution_name – the name of the installed package that provides the sample source data file (can be omitted if only one plugin is available)
sample_file_name – the name of the sample source data file (can be omitted if the plugin provides only one source data file)
- Returns:
path of generated file
- Raises:
FastPathExistsError – if overwrite==False and source_file_path already exists
- fastoad.api.get_plugin_information(print_data=False) Dict[str, DistributionPluginDefinition] [source]
Provides information about available FAST-OAD plugins.
- Parameters:
print_data – if True, plugin data are displayed.
- Returns:
a dict with installed package names as keys and matching FAST-OAD plugin definitions as values.
- fastoad.api.list_modules(source_path: List[str | PathLike] | str | PathLike = None, out: str | PathLike | TextIO = None, overwrite: bool = False, verbose: bool = False, force_text_output: bool = False)[source]
Writes list of available systems. If source_path is given and if it defines paths where there are registered systems, they will be listed too.
- Parameters:
source_path – either a configuration file path, folder path, or list of folder path
out – the output stream or a path for the output file (None means sys.stdout)
overwrite – if True and out is a file path, the file will be written even if one already exists
verbose – if True, shows detailed information for each system if False, shows only identifier and path of each system
force_text_output – if True, list will be written as text, even if command is used in an interactive IPython shell (Jupyter notebook). Has no effect in other shells or if out parameter is not sys.stdout
- Returns:
path of generated file, or None if no file was generated.
- Raises:
FastPathExistsError – if overwrite==False and out is a file path and the file exists
- fastoad.api.list_variables(configuration_file_path: str | PathLike, out: str | PathLike | TextIO = None, overwrite: bool = False, force_text_output: bool = False, tablefmt: str = 'grid')[source]
Writes list of variables for the problem specified in configuration_file_path.
List is generally written as text. It can be displayed as a scrollable table view if: - function is used in an interactive IPython shell - out == sys.stdout - force_text_output == False
- Parameters:
configuration_file_path –
out – the output stream or a path for the output file (None means sys.stdout)
overwrite – if True and out parameter is a file path, the file will be written even if one already exists
force_text_output – if True, list will be written as text, even if command is used in an interactive IPython shell (Jupyter notebook). Has no effect in other shells or if out parameter is not sys.stdout
tablefmt – The formatting of the requested table. Options are the same as those available to the tabulate package. See tabulate.tabulate_formats for a complete list. If “var_desc” the file will use the variable_descriptions.txt format.
- Returns:
path of generated file, or None if no file was generated.
- Raises:
FastPathExistsError – if overwrite==False and out is a file path and the file exists
- fastoad.api.optimization_viewer(configuration_file_path: str | PathLike)[source]
Displays optimization information and enables its editing
- Parameters:
configuration_file_path – problem definition
- Returns:
display of the OptimizationViewer
- fastoad.api.optimize_problem(configuration_file_path: str | PathLike, overwrite: bool = False, auto_scaling: bool = False) FASTOADProblem [source]
Runs driver according to provided problem file
- Parameters:
configuration_file_path – problem definition
overwrite – if True, output file will be overwritten
auto_scaling – if True, automatic scaling is performed for design variables and constraints
- Returns:
the OpenMDAO problem after run
- Raises:
FastPathExistsError – if overwrite==False and output data file of problem already exists
- fastoad.api.variable_viewer(file_path: str | PathLike, file_formatter: IVariableIOFormatter = None, editable=True)[source]
Displays a widget that enables to visualize variables information and edit their values.
- Parameters:
file_path – the path of file to interact with
file_formatter – the formatter that defines file format. If not provided, default format will be assumed.
editable – if True, an editable table with variable filters will be displayed. If False, the table will not be editable nor searchable, but can be stored in an HTML file.
- Returns:
display handle of the VariableViewer
- fastoad.api.write_n2(configuration_file_path: str | PathLike, n2_file_path: str | PathLike = None, overwrite: bool = False)[source]
Write the N2 diagram of the problem in file n2.html
- Parameters:
configuration_file_path –
n2_file_path – if None, will default to n2.html
overwrite –
- Returns:
path of generated file.
- Raises:
FastPathExistsError – if overwrite==False and n2_file_path already exists
- fastoad.api.write_xdsm(configuration_file_path: str | PathLike, xdsm_file_path: str | PathLike = None, overwrite: bool = False, depth: int = 2, wop_server_url: str = None, dry_run: bool = False)[source]
- Parameters:
configuration_file_path –
xdsm_file_path – the path for HTML file to be written (will overwrite if needed)
overwrite – if False, will raise an error if file already exists.
depth – the depth analysis for WhatsOpt
wop_server_url – URL of WhatsOpt server (if None, ether.onera.fr/whatsopt will be used)
dry_run – if True, will run wop without sending any request to the server. Generated XDSM will be empty. (for test purpose only)
- Returns:
path of generated file.
- Raises:
FastPathExistsError – if overwrite==False and xdsm_file_path already exists
- class fastoad.api.CalcRunner(configuration_file_path: str | PathLike, input_file_path: str | PathLike | None = None, optimize: bool = False)[source]
Bases:
object
Class for running FAST-OAD computations for a specific configuration.
It is specifically designed to run several computations concurrently with
run_cases()
. For each computation, data can be isolated in a specific folder.- run(input_values: VariableList | None = None, calculation_folder: str | PathLike | None = None) DataFile [source]
Run the computation.
This method is useful to set input values on-the-fly, and/or isolate the computation data in a dedicated folder.
- Parameters:
input_values – if provided, these values will supersede the content of input file (specified in configuration file)
calculation_folder – if specified, all data, including configuration file, will be stored in that folder. The input file in this folder will contain data from input_values
- Returns:
the written output data
- run_cases(input_list: List[VariableList], destination_folder: str | PathLike, *, max_workers: int | None = None, use_MPI_if_available: bool = True, overwrite_subfolders: bool = False)[source]
Run computations concurrently.
The data of each computation will be isolated in a dedicated subfolder of destination folder.
- Parameters:
input_list – a computation will be run for each item of this list
destination_folder – The data of each computation will be isolated in a dedicated subfolder of this folder.
max_workers – if not specified, all available processors will be used. Set to -1 to use all available processors except 1 (useful when running locally while keeping some CPU for working meanwhile).
use_MPI_if_available – If False, or if no MPI implementation is available, computations will be run concurrently using the multiprocessing library.
overwrite_subfolders – if False, calculations that match existing subfolders won’t be run (allows batch continuation)
- fastoad.api.aircraft_geometry_plot(aircraft_file_path: str | PathLike, name=None, fig=None, *, file_formatter=None) FigureWidget [source]
Returns a figure plot of the top view of the wing. Different designs can be superposed by providing an existing fig. Each design can be provided a name.
- Parameters:
aircraft_file_path – path of data file
name – name to give to the trace added to the figure
fig – existing figure to which add the plot
file_formatter – the formatter that defines the format of data file. If not provided, default format will be assumed.
- Returns:
wing plot figure
- fastoad.api.drag_polar_plot(aircraft_file_path: str | PathLike, name=None, fig=None, *, file_formatter=None) FigureWidget [source]
Returns a figure plot of the aircraft drag polar. Different designs can be superposed by providing an existing fig. Each design can be provided a name.
- Parameters:
aircraft_file_path – path of data file
name – name to give to the trace added to the figure
fig – existing figure to which add the plot
file_formatter – the formatter that defines the format of data file. If not provided, default format will be assumed.
- Returns:
wing plot figure
- fastoad.api.mass_breakdown_bar_plot(aircraft_file_path: str | PathLike, name=None, fig=None, *, file_formatter=None, input_mass_name='data:weight:aircraft:MTOW') FigureWidget [source]
Returns a figure plot of the aircraft mass breakdown using bar plots. Different designs can be superposed by providing an existing fig. Each design can be provided a name.
- Parameters:
aircraft_file_path – path of data file
name – name to give to the trace added to the figure
fig – existing figure to which add the plot
file_formatter – the formatter that defines the format of data file. If not provided, default format will be assumed.
input_mass_name – the variable name for the mass input as defined in the mission definition file.
- Returns:
bar plot figure
- fastoad.api.mass_breakdown_sun_plot(aircraft_file_path: str | PathLike, *, file_formatter=None, input_mass_name='data:weight:aircraft:MTOW', mission_name=None)[source]
Returns a figure sunburst plot of the mass breakdown of the aircraft of the sizing mission. On the left a MTOW sunburst and on the right a OWE sunburst. Different designs can be superposed by providing an existing fig. Each design can be provided a name.
- Parameters:
aircraft_file_path – path of data file
file_formatter – the formatter that defines the format of data file. If not provided, default format will be assumed.
input_mass_name – the variable name for the mass input as defined in the mission definition file.
mission_name – the name of the specific mission for which the mass breakdown is plotted. If not provided, the sizing mission configuration is plotted.
- Returns:
sunburst plot figure
- fastoad.api.payload_range_plot(aircraft_file_path: str | PathLike, name='Payload-Range', mission_name='operational', variable_of_interest: str = None, variable_of_interest_legend: str = None)[source]
Returns a figure of the payload-range diagram. The diagram contains by default only the contour but can also provide a heatmap of the grid points, if variable_of_interest is not None. Please note that the data for the contour are expected in the variables data:payload_range:{mission_name}:range and data:payload_range:{mission_name}:payload. Similarly, the data for the heatmap are expected in the variables data:payload_range:{mission_name}:grid:range, data:payload_range:{mission_name}:grid:payload and data:payload_range:{mission_name}:grid:{variable_of_interest}.
- Parameters:
aircraft_file_path – path of data file
name – name to give to the trace added to the figure
mission_name – name of the mission present in the data file to be plotted.
variable_of_interest – variable of interest for the heatmap.
variable_of_interest_legend – name to give to variable of interest in plot legend.
- Returns:
payload-range plot figure
- fastoad.api.wing_geometry_plot(aircraft_file_path: str | PathLike, name=None, fig=None, *, file_formatter=None) FigureWidget [source]
Returns a figure plot of the top view of the wing. Different designs can be superposed by providing an existing fig. Each design can be provided a name.
- Parameters:
aircraft_file_path – path of data file
name – name to give to the trace added to the figure
fig – existing figure to which add the plot
file_formatter – the formatter that defines the format of data file. If not provided, default format will be assumed.
- Returns:
wing plot figure
- class fastoad.api.MissionViewer[source]
Bases:
object
A class for facilitating the post-processing of mission and trajectories
- add_mission(mission_data: str | PathLike | DataFrame, name=None)[source]
Adds the mission to the mission database (self.missions) :param mission_data: path of the mission file or Dataframe containing the mission data :param name: name to give to the mission
- display(layout_dict=None, layout_overwrite=False, **kwargs)[source]
Display the user interface
- Parameters:
layout_dict – Dictionary of properties to be updated
layout_overwrite – If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation.
kwargs – Keyword/value pair of properties to be updated
:return the display object
- class fastoad.api.OptimizationViewer[source]
Bases:
object
A class for interacting with FAST-OAD Problem optimization information.
- problem_configuration: FASTOADProblemConfigurator
Instance of the FAST-OAD problem configuration
- dataframe
The dataframe which is the mirror of self.file
- load(problem_configuration: FASTOADProblemConfigurator)[source]
Loads the FAST-OAD problem and stores its data.
- Parameters:
problem_configuration – the FASTOADProblem instance.
- save()[source]
Save the optimization to the files. Possible files modified are:
the .yml configuration file
the input file (initial values)
the output file (values)
- display()[source]
Displays the datasheet. load() must be ran before.
- Returns:
display of the user interface:
- load_variables(variables: VariableList, attribute_to_column: Dict[str, str] = None)[source]
Loads provided variable list and replace current data set.
- Parameters:
variables – the variables to load
attribute_to_column – dictionary keys tell what variable attributes are kept and the values tell what name will be displayed. If not provided, default translation will apply.
- get_variables(column_to_attribute: Dict[str, str] = None) VariableList [source]
- Parameters:
column_to_attribute – dictionary keys tell what columns are kept and the values tell whatvariable attribute it corresponds to. If not provided, default translation will apply.
- Returns:
a variable list from current data set
- class fastoad.api.VariableViewer[source]
Bases:
object
A class for interacting with FAST-OAD files. The file data is stored in a pandas DataFrame. The class built so that a modification of the DataFrame is instantly replicated on the file file. The interaction is achieved using a user interface built with widgets from ipywidgets and Sheets from ipysheet.
A classical usage of this class will be:
df = VariableViewer() # instantiation of dataframe file = AbstractOMFileIO('problem_outputs.file') # instantiation of file io df.load(file) # load the file df.display() # renders a ui for reading/modifying the file
- file
The path of the data file that will be viewed/edited
- dataframe
The dataframe which is the mirror of self.file
- load(file_path: str | PathLike, file_formatter: IVariableIOFormatter = None)[source]
Loads the file and stores its data.
- Parameters:
file_path – the path of file to interact with
file_formatter – the formatter that defines file format. If not provided, default format will be assumed.
- save(file_path: str | PathLike = None, file_formatter: IVariableIOFormatter = None)[source]
Save the dataframe to the file.
- Parameters:
file_path – the path of file to save. If not given, the initially read file will be overwritten.
file_formatter – the formatter that defines file format. If not provided, default format will be assumed.
- load_variables(variables: VariableList, attribute_to_column: Dict[str, str] = None)[source]
Loads provided variable list and replace current data set.
- Parameters:
variables – the variables to load
attribute_to_column – dictionary keys tell what variable attributes are kept and the values tell what name will be displayed. If not provided, default translation will apply.
- get_variables(column_to_attribute: Dict[str, str] = None) VariableList [source]
- Parameters:
column_to_attribute – dictionary keys tell what columns are kept and the values tell what variable attribute it corresponds to. If not provided, default translation will apply.
- Returns:
a variable list from current data set
- class fastoad.api.DataFile(data_source: str | PathLike | IO | list = None, formatter: IVariableIOFormatter = None, load_data: bool = True)[source]
Bases:
VariableList
Class for managing FAST-OAD data files.
Behaves like
VariableList
class but hasload()
andsave()
methods.If variable list is specified for data_source,
file_path
will have to be set before using :method:`save`.- Parameters:
data_source – Can be the file path where data will be loaded and saved, or a list of
Variable
instances that will be used for initialization (or aVariableList
instance).formatter – (ignored if data_source is not an I/O stream nor a file path) a class that determines the file format to be used. Defaults to FAST-OAD native format. See
VariableIO
for more information.load_data – (ignored if data_source is not an I/O stream nor a file path) if True, file is expected to exist and its content will be loaded at instantiation.
- property formatter: IVariableIOFormatter
Class that defines the file format.
- save_as(file_path: str | PathLike, overwrite=False, formatter: IVariableIOFormatter = None)[source]
Sets the associated file path as specified and saves current state of variables.
- Parameters:
file_path –
overwrite – if specified file already exists and overwrite is False, an error is triggered.
formatter – a class that determines the file format to be used. Defaults to FAST-OAD native format. See
VariableIO
for more information.
- class fastoad.api.FASTOADProblemConfigurator(conf_file_path: str | PathLike = None)[source]
Bases:
object
class for configuring an OpenMDAO problem from a configuration file
See description of configuration file.
- Parameters:
conf_file_path – if provided, configuration will be read directly from it
- get_problem(read_inputs: bool = False, auto_scaling: bool = False) FASTOADProblem [source]
Builds the OpenMDAO problem from current configuration.
- Parameters:
read_inputs – if True, the created problem will already be fed with variables from the input file
auto_scaling – if True, automatic scaling is performed for design variables and constraints
- Returns:
the problem instance
- load(conf_file: str | PathLike)[source]
Reads the problem definition
- Parameters:
conf_file – Path to the file to open
- save(filename: str | PathLike = None)[source]
Saves the current configuration If no filename is provided, the initially read file is used.
- Parameters:
filename – file where to save configuration
- write_needed_inputs(source_file_path: str | PathLike = None, source_formatter: IVariableIOFormatter = None)[source]
Writes the input file of the problem with unconnected inputs of the configured problem.
Written value of each variable will be taken:
from input_data if it contains the variable
from defined default values in component definitions
- Parameters:
source_file_path – if provided, variable values will be read from it
source_formatter – the class that defines format of input file. if not provided, expected format will be the default one.
- get_optimization_definition() Dict [source]
- Returns information related to the optimization problem:
Design Variables
Constraints
Objectives
- Returns:
dict containing optimization settings for current problem
- set_optimization_definition(optimization_definition: Dict)[source]
Updates configuration with the list of design variables, constraints, objectives contained in the optimization_definition dictionary.
Keys of the dictionary are: “design_var”, “constraint”, “objective”.
Configuration file will not be modified until
save()
is used.- Parameters:
optimization_definition – dict containing the optimization problem definition
- make_local(new_folder_path: str | PathLike, copy_models: bool = False)[source]
Modify the current configurator so that all input and output files will be in the indicated folder.
- Parameters:
new_folder_path – the folder path that will contain in/out files
copy_models – True if local models (declared in module_folders) should be copied in new_folder_path
- class fastoad.api.Atmosphere(*args, **kwargs)[source]
Bases:
object
Simple implementation of International Standard Atmosphere for troposphere and stratosphere.
Atmosphere properties are provided in the same “shape” as provided altitude:
if altitude is given as a float, returned values will be floats
if altitude is given as a sequence (list, 1D numpy array, …), returned values will be 1D numpy arrays
if altitude is given as nD numpy array, returned values will be nD numpy arrays
Usage:
>>> pressure = Atmosphere(30000).pressure # pressure at 30,000 feet, dISA = 0 K >>> density = Atmosphere(5000, 10).density # density at 5,000 feet, dISA = 10 K >>> atm = Atmosphere(np.arange(0,10001,1000, 15)) # init for alt. 0 to 10,000, dISA = 15K >>> temperatures = atm.pressure # pressures for all defined altitudes >>> viscosities = atm.kinematic_viscosity # viscosities for all defined altitudes
- Parameters:
altitude – altitude (units decided by altitude_in_feet)
delta_t – temperature increment (°C) applied to whole temperature profile
altitude_in_feet – if True, altitude should be provided in feet. Otherwise, it should be provided in meters.
- get_altitude(altitude_in_feet: bool = True) float | Sequence[float] [source]
- Parameters:
altitude_in_feet – if True, altitude is returned in feet. Otherwise, it is returned in meters
- Returns:
altitude provided at instantiation
- class fastoad.api.AtmosphereSI(*args, **kwargs)[source]
Bases:
Atmosphere
Same as
Atmosphere
except that altitudes are always in meters.- Parameters:
altitude – altitude in meters
delta_t – temperature increment (°C) applied to whole temperature profile
- property altitude
Altitude in meters.
- class fastoad.api.FlightPoint(time: float = 0.0, altitude: float = None, isa_offset: float = 0.0, ground_distance: float = 0.0, mass: float = None, consumed_fuel: float = 0.0, true_airspeed: float = None, equivalent_airspeed: float = None, mach: float = None, engine_setting: EngineSetting = None, CL: float = None, CD: float = None, lift: float = None, drag: float = None, thrust: float = None, thrust_rate: float = None, thrust_is_regulated: bool = None, sfc: float = None, slope_angle: float = None, acceleration: float = None, alpha: float = 0.0, slope_angle_derivative: float = None, name: str = None)[source]
Bases:
object
Dataclass for storing data for one flight point.
This class is meant for:
pandas friendliness: data exchange with pandas DataFrames is simple
extensibility: any user might add fields to the class using
add_field()
Exchanges with pandas DataFrame
A pandas DataFrame can be generated from a list of FlightPoint instances:
>>> import pandas as pd >>> from fastoad.model_base import FlightPoint >>> fp1 = FlightPoint(mass=70000., altitude=0.) >>> fp2 = FlightPoint(mass=60000., altitude=10000.) >>> df = pd.DataFrame([fp1, fp2])
And FlightPoint instances can be created from DataFrame rows:
# Get one FlightPoint instance from a DataFrame row >>> fp1bis = FlightPoint.create(df.iloc[0]) # Get a list of FlightPoint instances from the whole DataFrame >>> flight_points = FlightPoint.create_list(df)
Extensibility
FlightPoint class is bundled with several fields that are commonly used in trajectory assessment, but one might need additional fields.
Python allows to add attributes to any instance at runtime, but for FlightPoint to run smoothly, especially when exchanging data with pandas, you have to work at class level. This can be done using
add_field()
, preferably outside any class or function:# Adding a float field with None as default value >>> FlightPoint.add_field( ... "ion_drive_power", ... unit="W", ... is_cumulative=False, # Tells if quantity sums up during mission ... ) # Adding a field and defining its type and default value >>> FlightPoint.add_field("warp", annotation_type=int, default_value=9) # Now these fields can be used at instantiation >>> fp = FlightPoint(ion_drive_power=110.0, warp=12) # Removing a field, even an original one >>> FlightPoint.remove_field("sfc")
Note
All original parameters in FlightPoint instances are expected to be in SI units.
- engine_setting: EngineSetting = None
Engine setting.
- thrust_is_regulated: bool = None
If True, propulsion should match the thrust value. If False, propulsion should match thrust rate.
- set_as_relative(field_names: Sequence[str] | str)[source]
Makes that values for given field_names will be considered as relative when calling
make_absolute()
.- Parameters:
field_names –
- set_as_absolute(field_names: Sequence[str] | str)[source]
Makes that values for given field_names will be considered as absolute when calling
make_absolute()
.- Parameters:
field_names –
- is_relative(field_name) bool [source]
Tells if given field is considered as relative or absolut
- Parameters:
field_name –
- Returns:
True if it is relative
- make_absolute(reference_point: FlightPoint) FlightPoint [source]
Computes a copy flight point where no field is relative.
- Parameters:
reference_point – relative fields will be made absolute using this point.
- Returns:
the copied flight point with no relative field.
- scalarize()[source]
Convenience method for converting to scalars all fields that have a one-item array-like value.
- classmethod get_units() dict [source]
Returns (field name, unit) dict for any field that has a defined unit.
A dimensionless physical quantity will have “-” as unit.
- classmethod get_unit(field_name) str | None [source]
Returns unit for asked field.
A dimensionless physical quantity will have “-” as unit.
- classmethod is_cumulative(field_name) bool | None [source]
Tells if asked field is cumulative (sums up during mission).
Returns None if field not found.
- classmethod create(data: Mapping) FlightPoint [source]
Instantiate FlightPoint from provided data.
data can typically be a dict or a pandas DataFrame row.
- Parameters:
data – a dict-like instance where keys are FlightPoint attribute names
- Returns:
the created FlightPoint instance
- classmethod create_list(data: DataFrame) List[FlightPoint] [source]
Creates a list of FlightPoint instances from provided DataFrame.
- Parameters:
data – a dict-like instance where keys are FlightPoint attribute names
- Returns:
the created FlightPoint instance
- classmethod add_field(name: str, annotation_type=<class 'float'>, default_value: ~typing.Any = None, unit='-', is_cumulative=False)[source]
Adds the named field to FlightPoint class.
If the field name already exists, the field is redefined.
- Parameters:
name – field name
annotation_type – field type
default_value – field default value
unit – expected unit for the added field. “-” should be provided for a dimensionless physical quantity. Set to None, when unit concept does not apply.
is_cumulative – True if field value is summed up during mission
- class fastoad.api.BaseCycleGroup(**kwargs)[source]
Bases:
CycleGroup
Inherited from
CycleGroup
with no modification of default behavior.Set the solvers to nonlinear and linear block Gauss–Seidel by default.
- default_linear_solver = 'om.DirectSolver'
- default_nonlinear_solver = 'om.NonlinearBlockGS'
- default_solver_options = {'linear_solver_options': {}, 'nonlinear_solver_options': {}}
- use_solvers_by_default = True
- class fastoad.api.CycleGroup(**kwargs)[source]
Bases:
Group
,ABC
Use this class as a base class if your model should contain solvers.
This class defines standard options to control inner solvers.
Please be sure to call the super() method when using initialize() and setup() in the derived class.
By default, the inner solver is activated. If you want your subclass to deactivate the solver by default, you can define it when subclassing:
class MyGroup(CycleGroup, use_solver_by_default=False): ...
You may also specify default solver settings for your subclass. They will be used when adding the solver, unless overwritten through OpenMDAO options when instantiating:
class MyGroup( CycleGroup, default_linear_solver="om.ScipyKrylov", default_nonlinear_solver="om.NewtonSolver", default_nonlinear_options={"maxiter": 50, "iprint": 0}, default_linear_options={"maxiter": 100, "rtol": 1.e-6}, ): ...
Set the solvers to nonlinear and linear block Gauss–Seidel by default.
- setup()[source]
Build this group.
This method should be overidden by your Group’s method. The reason for using this method to add subsystem is to save memory and setup time when using your Group while running under MPI. This avoids the creation of systems that will not be used in the current process.
You may call ‘add_subsystem’ to add systems to this group. You may also issue connections, and set the linear and nonlinear solvers for this group level. You cannot safely change anything on children systems; use the ‘configure’ method instead.
- Available attributes:
name pathname comm options
- class fastoad.api.IOMPropulsionWrapper[source]
Bases:
object
Interface for wrapping a
IPropulsion
subclass in OpenMDAO.The implementation class defines the needed input variables for instantiating the
IPropulsion
subclass insetup()
and use them for instantiation inget_model()
See
OMRubberEngineWrapper
for an example of implementation.- abstract setup(component: Component)[source]
Defines the needed OpenMDAO inputs for propulsion instantiation as done in
get_model()
Use add_inputs and declare_partials methods of the provided component
- Parameters:
component –
- abstract static get_model(inputs) IPropulsion [source]
This method defines the used
IPropulsion
subclass instance.- Parameters:
inputs – OpenMDAO input vector where the parameters that define the propulsion model are
- Returns:
the propulsion model instance
- class fastoad.api.AbstractFlightSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0)[source]
Bases:
IFlightPart
,ABC
Base class for flight path segment.
As a dataclass, attributes can be set at instantiation.
Important
compute_from()
is the method to call to achieve the segment computation.However, when subclassing, the method to overload is
compute_from_start_to_target()
. Generic reprocessing of start and target flight points is done incompute_from()
before callingcompute_from_start_to_target()
- target: FlightPoint = <object object>
A FlightPoint instance that provides parameter values that should all be reached at the end of
compute_from()
. Possible parameters depend on the current segment. A parameter can also be set toCONSTANT_VALUE
to tell that initial value should be kept during all segment.
- CONSTANT_VALUE = 'constant'
Using this value will tell to keep the associated parameter constant.
- abstract compute_from_start_to_target(start, target) DataFrame [source]
Here should come the implementation for computing flight points between start and target flight points.
- Parameters:
start –
target – Definition of segment target
- Returns:
a pandas DataFrame where column names match fields of
FlightPoint
- compute_from(start: FlightPoint) DataFrame [source]
Computes the flight path segment from provided start point.
Computation ends when target is attained, or if the computation stops getting closer to target. For instance, a climb computation with too low thrust will only return one flight point, that is the provided start point.
Important
When subclasssing, if you need to overload
compute_from()
, you should consider overridingcompute_from_start_to_target()
instead. Therefore, you will take benefit of the preprocessing of start and target flight points that is done incompute_from()
.- Parameters:
start – the initial flight point, defined for altitude, mass and speed (true_airspeed, equivalent_airspeed or mach). Can also be defined for time and/or ground_distance.
- Returns:
a pandas DataFrame where column names match fields of
FlightPoint
- complete_flight_point(flight_point: FlightPoint)[source]
Computes data for provided flight point.
Assumes that it is already defined for time, altitude, mass, ground distance and speed (TAS, EAS, or Mach).
- Parameters:
flight_point – the flight point that will be completed in-place
- static complete_flight_point_from(flight_point: FlightPoint, source: FlightPoint)[source]
Sets undefined values in flight_point using the ones from source.
The particular case of speeds is taken into account: if at least one speed parameter is defined, all other speed parameters are considered defined, because they will be deduced when needed.
- Parameters:
flight_point –
source –
- static consume_fuel(flight_point: FlightPoint, previous: FlightPoint, fuel_consumption: float = None, mass_ratio: float = None)[source]
This method should be used whenever fuel consumption has to be stored.
It ensures that “mass” and “consumed_fuel” fields will be kept consistent.
Mass can be modified using the ‘fuel_consumption” argument, or the ‘mass_ratio’ argument. One of them should be provided.
- Parameters:
flight_point – the FlightPoint instance where “mass” and “consumed_fuel” fields will get new values
previous – FlightPoint instance that will be the base for the computation
fuel_consumption – consumed fuel, in kg, between ‘previous’ and ‘flight_point’. Positive when fuel is consumed.
mass_ratio – the ratio flight_point.mass/previous.mass
- class fastoad.api.IFlightPart(name: str = '')[source]
Bases:
ABC
,BaseDataClass
Base class for all flight parts.
- target: FlightPoint
- abstract compute_from(start: FlightPoint) DataFrame [source]
Computes a flight sequence from provided start point.
- Parameters:
start – the initial flight point, defined for altitude, mass and speed (true_airspeed, equivalent_airspeed or mach). Can also be defined for time and/or ground_distance.
- Returns:
a pandas DataFrame where column names match fields of
FlightPoint
- class fastoad.api.RegisterSegment(keyword='')[source]
Bases:
RegisterElement
Decorator for registering IFlightPart classes.
>>> @RegisterSegment("segment_foo") >>> class FooSegment(IFlightPart): >>> ...
Then the registered class can be obtained by:
>>> my_class = RegisterSegment.get_class("segment_foo")
- class fastoad.api.AbstractFixedDurationSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 60.0, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB)[source]
Bases:
AbstractTimeStepFlightSegment
,ABC
Base class for computing a fixed-duration segment.
- time_step: float = 60.0
Used time step for computation (actual time step can be lower at some particular times of the flight path).
- get_distance_to_target(flight_points: List[FlightPoint], target: FlightPoint) float [source]
Computes a “distance” from last flight point to target.
Computed does not need to have a real meaning. The important point is that it must be signed so that algorithm knows on which “side” of the target we are. And of course, it should be 0. if flight point is on target.
- Parameters:
flight_points – list of all currently computed flight_points
target – segment target (will not contain relative values)
- Returns:
if target is attained, a non-null value otherwise
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.AbstractGroundSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 0.1, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB, thrust_rate: float = 1.0, wheels_friction: float = 0.03)[source]
Bases:
AbstractTakeOffSegment
,ABC
Class for computing accelerated segments on the ground with wheel friction.
- get_gamma_and_acceleration(flight_point: FlightPoint)[source]
For ground segment, gamma is assumed always 0 and wheel friction (with or without brake) is added to drag
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.AbstractManualThrustSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 0.2, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB, thrust_rate: float = 1.0)[source]
Bases:
AbstractTimeStepFlightSegment
,ABC
Base class for computing flight segment where thrust rate is imposed.
- Variables:
thrust_rate – used thrust rate. Can be set at instantiation using a keyword argument.
- compute_propulsion(flight_point: FlightPoint)[source]
Computes propulsion data.
Provided flight point is modified in place.
Generally, this method should end with:
self.propulsion.compute_flight_points(flight_point)
- Parameters:
flight_point –
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.AbstractPolarModifier[source]
Bases:
ABC
Base class to implement a change to the polar during the mission computation
- abstract modify_polar(polar: Polar, flight_point: FlightPoint) Polar [source]
- Parameters:
polar – an instance of Polar
flight_point – an intance of FlightPoint containg only floats
- Returns:
the modified polar for the flight point
- class fastoad.api.AbstractRegulatedThrustSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 60.0, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB)[source]
Bases:
AbstractTimeStepFlightSegment
,ABC
Base class for computing flight segment where thrust rate is adjusted on drag.
- time_step: float = 60.0
Used time step for computation (actual time step can be lower at some particular times of the flight path).
- compute_propulsion(flight_point: FlightPoint)[source]
Computes propulsion data.
Provided flight point is modified in place.
Generally, this method should end with:
self.propulsion.compute_flight_points(flight_point)
- Parameters:
flight_point –
- get_gamma_and_acceleration(flight_point: FlightPoint) Tuple[float, float] [source]
Computes slope angle (gamma) and acceleration.
- Parameters:
flight_point – parameters after propulsion model has been called (i.e. mass, thrust and drag are available)
- Returns:
slope angle in radians and acceleration in m**2/s
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.AbstractTakeOffSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 0.1, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB, thrust_rate: float = 1.0)[source]
Bases:
AbstractManualThrustSegment
,AbstractLiftFromAoASegment
,ABC
Class for computing takeoff segment.
- time_step: float = 0.1
Used time step for computation (actual time step can be lower at some particular times of the flight path).
- compute_from_start_to_target(start: FlightPoint, target: FlightPoint) DataFrame [source]
Here should come the implementation for computing flight points between start and target flight points.
- Parameters:
start –
target – Definition of segment target
- Returns:
a pandas DataFrame where column names match fields of
FlightPoint
- get_gamma_and_acceleration(flight_point: FlightPoint)[source]
Redefinition : computes slope angle derivative (gamma_dot) and x-acceleration. Replaces CL, CD, lift dan drag values (for ground effect and accelerated flight)
- Parameters:
flight_point – parameters after propulsion model has been called (i.e. mass, thrust and drag are available)
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.AbstractTimeStepFlightSegment(name: str = '', target: ~fastoad.model_base.flight_point.FlightPoint = <object object>, isa_offset: float = 0.0, propulsion: ~fastoad.model_base.propulsion.IPropulsion = <object object>, polar: ~fastoad.models.performances.mission.polar.Polar = <object object>, polar_modifier: ~fastoad.models.performances.mission.polar_modifier.AbstractPolarModifier = <factory>, reference_area: float = <object object>, time_step: float = 0.2, maximum_CL: float = None, altitude_bounds: tuple = (-500.0, 40000.0), mach_bounds: tuple = (-1e-06, 5.0), interrupt_if_getting_further_from_target: bool = True, engine_setting: ~fastoad.constants.EngineSetting = EngineSetting.CLIMB)[source]
Bases:
AbstractFlightSegment
,ABC
Base class for time step computation flight segments.
This class implements the time computation. For this computation to work, subclasses must implement abstract methods
get_distance_to_target()
,get_gamma_and_acceleration()
andcompute_propulsion()
.compute_next_alpha()
also has to be overloaded if angle of attack should be different of 0.- propulsion: IPropulsion = <object object>
A IPropulsion instance that will be called at each time step.
- polar_modifier: AbstractPolarModifier
- time_step: float = 0.2
Used time step for computation (actual time step can be lower at some particular times of the flight path).
- altitude_bounds: tuple = (-500.0, 40000.0)
Minimum and maximum authorized altitude values. If computed altitude gets beyond these limits, computation will be interrupted and a warning message will be issued in logger.
- mach_bounds: tuple = (-1e-06, 5.0)
Minimum and maximum authorized mach values. If computed Mach gets beyond these limits, computation will be interrupted and a warning message will be issued in logger.
- interrupt_if_getting_further_from_target: bool = True
If True, computation will be interrupted if a parameter stops getting closer to target between two iterations (which can mean the provided thrust rate is not adapted).
- engine_setting: EngineSetting = 2
The EngineSetting value associated to the segment. Can be used in the propulsion model.
- abstract get_distance_to_target(flight_points: List[FlightPoint], target: FlightPoint) float [source]
Computes a “distance” from last flight point to target.
Computed does not need to have a real meaning. The important point is that it must be signed so that algorithm knows on which “side” of the target we are. And of course, it should be 0. if flight point is on target.
- Parameters:
flight_points – list of all currently computed flight_points
target – segment target (will not contain relative values)
- Returns:
if target is attained, a non-null value otherwise
- abstract compute_lift(flight_point: FlightPoint, reference_force: float, polar: Polar)[source]
Fills values for CL, and lift in provided flight_point.
- Parameters:
flight_point –
reference_force – CL = lift / reference_force
polar – unused here, but can be used when overloading this method
- abstract compute_propulsion(flight_point: FlightPoint)[source]
Computes propulsion data.
Provided flight point is modified in place.
Generally, this method should end with:
self.propulsion.compute_flight_points(flight_point)
- Parameters:
flight_point –
- abstract get_gamma_and_acceleration(flight_point: FlightPoint) Tuple[float, float] [source]
Computes slope angle (gamma) and acceleration.
- Parameters:
flight_point – parameters after propulsion model has been called (i.e. mass, thrust and drag are available)
- Returns:
slope angle in radians and acceleration in m**2/s
- get_next_alpha(previous_point: FlightPoint, time_step: float) float [source]
Determine the next angle of attack.
- Parameters:
previous_point – the flight point from which next alpha is computed
time_step – the duration between computed flight point and previous_point
- complete_flight_point(flight_point: FlightPoint)[source]
Computes data for provided flight point.
Assumes that it is already defined for time, altitude, mass, ground distance and speed (TAS, EAS, or Mach).
- Parameters:
flight_point – the flight point that will be completed in-place
- compute_from_start_to_target(start: FlightPoint, target: FlightPoint) DataFrame [source]
Here should come the implementation for computing flight points between start and target flight points.
- Parameters:
start –
target – Definition of segment target
- Returns:
a pandas DataFrame where column names match fields of
FlightPoint
- compute_next_flight_point(flight_points: List[FlightPoint], time_step: float) FlightPoint [source]
Computes time, altitude, speed, mass and ground distance of next flight point.
- Parameters:
flight_points – previous flight points
time_step – time step for computing next point
- Returns:
the computed next flight point
- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.FlightSegment(*args, **kwargs)[source]
Bases:
AbstractTimeStepFlightSegment
,ABC
Base class for time step computation flight segments.
This class implements the time computation. For this computation to work, subclasses must implement abstract methods
get_get_distance_to_target()
,get_gamma_and_acceleration()
andcompute_propulsion()
.- property target: FlightPoint
The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless instance that has no instance attributes and cannot be given any.
- class fastoad.api.RegisterOpenMDAOSystem(provider_id: str, desc=None, domain: ModelDomain = None, options: dict = None)[source]
Bases:
_RegisterSpecializedOpenMDAOService
Decorator class for registering an OpenMDAO system for use in FAST-OAD configuration.
If a variable_descriptions.txt file is in the same folder as the class module, its content is loaded (once, even if several classes are registered at the same level).
- Parameters:
provider_id – the identifier of the service provider to register
desc – description of the service. If not provided, the docstring will be used.
domain – a category for the registered service provider
options – a dictionary of options that can be associated to the service provider
- class fastoad.api.RegisterPropulsion(provider_id: str, desc=None, domain: ModelDomain = None, options: dict = None)[source]
Bases:
_RegisterSpecializedOpenMDAOService
Decorator class for registering an OpenMDAO wrapper of a propulsion-dedicated model.
- Parameters:
provider_id – the identifier of the service provider to register
desc – description of the service. If not provided, the docstring will be used.
domain – a category for the registered service provider
options – a dictionary of options that can be associated to the service provider
- class fastoad.api.RegisterSpecializedService(provider_id: str, desc=None, domain: ModelDomain = None, options: dict = None)[source]
Bases:
RegisterService
Base class for decorator classes that allow to register a particular service.
The service may be associated to a base class (or interface). The registered class must inherit from this base class.
Unlike
RegisterService
, this class has to be subclassed, because the service identifier is defined when subclassing.The definition of the base class is done by subclassing, e.g.:
class RegisterSomeService( RegisterSpecializedService, base_class=ISomeService, service_id="my.particularservice"): "Allows to register classes that implement interface ISomeService."
Then basic registering of a class is done with:
@RegisterSomeService("my.particularservice.provider") class ParticularService(ISomeService): ...
- Parameters:
provider_id – the identifier of the service provider to register
desc – description of the service. If not provided, the docstring will be used.
domain – a category for the registered service provider
options – a dictionary of options that can be associated to the service provider
- get_properties(service_class: Type[T]) dict [source]
Override this method to modify the properties that will be associated to the registered service provider.
This basic version ensures the associated description property is the one provided when instantiating this decorator class, if it is provided. Otherwise, it will be the docstring of the decorated class.
- Parameters:
service_class – the class that will be registered as service provider
- Returns:
the dictionary of properties that will be associated to the registered service provider
- class fastoad.api.RegisterSubmodel(service_id: str, provider_id: str, desc=None, options: dict = None)[source]
Bases:
_RegisterOpenMDAOService
Decorator class that allows to submodels.
Submodels are OpenMDAO systems that fulfill a requirement (service id) in a FAST-OAD module.
active_models
defines the submodel to be used for any service identifier it has as key. Seeget_submodel()
for more details.The registering of a class is done with:
@RegisterSubmodel("my.service", "id.of.the.provider") class MyService: ...
Then the submodel can be instantiated and used with:
submodel_instance = RegisterSubmodel.get_submodel("my.service") some_model.add_subsystem("my_submodel", submodel_instance, promotes=["*"]) ...
- Parameters:
service_id – the identifier of the provided service
provider_id – the identifier of the service provider to register
desc – description of the service. If not provided, the docstring will be used.
options – a dictionary of options that will be defaults when instantiating the system
- active_models: Dict[str, str | None] = {}
Dictionary (key = service id, value=provider id) that defines submodels to be used for associated services.
- classmethod get_submodel(service_id: str, options: dict = None)[source]
Provides a submodel for the given service identifier.
- If
active_models
has service_id as key: if the associated value is a non-empty string, a submodel will be instantiated with this string as submodel identifier. If the submodel identifier matches nothing, an error will be raised.
if the associated value is None, an empty submodel (om.Group()) will be instantiated. You may see it as a way to deactivate a particular submodel.
- If
active_models
has service_id has NOT as key: if no submodel is declared for this service_id, an error will be raised.
if one and only one submodel is declared for this service_id, it will be instantiated.
if several submodels are declared for this service_id, an error will be raised.
If an actual (not empty) submodel is defined, provided options will be used.
- Parameters:
service_id –
options –
- Returns:
the instantiated submodel
- If
- class fastoad.api.FASTOADProblem(*args, **kwargs)[source]
Bases:
Problem
Vanilla OpenMDAO Problem except that it can write its outputs to a file.
It also runs
ValidityDomainChecker
after eachrun_model()
orrun_driver()
(but it does nothing if no check has been registered).Initialize attributes.
- input_file_path
File path where
read_inputs()
will read inputs
- output_file_path
File path where
write_outputs()
will write outputs
- additional_variables
Variables that are not part of the problem but that should be written in output file.
- run_model(case_prefix=None, reset_iter_counts=True)[source]
Run the model by calling the root system’s solve_nonlinear.
- run_driver(case_prefix=None, reset_iter_counts=True)[source]
Run the driver on the model.
- Parameters:
- Returns:
Failure flag; True if failed to converge, False is successful.
- Return type:
- write_needed_inputs(source_file_path: str | PathLike = None, source_formatter: IVariableIOFormatter = None)[source]
Writes the input file of the problem using its unconnected inputs.
Written value of each variable will be taken:
from input_data if it contains the variable
from defined default values in component definitions
- Parameters:
source_file_path – if provided, variable values will be read from it
source_formatter – the class that defines format of input file. if not provided, expected format will be the default one.
- property analysis: ProblemAnalysis
Information about inner structure of this problem.
The collected data (internally stored) are used in several steps of the computation.
This analysis is performed once. Each subsequent usage reuses the obtained data.
To ensure the analysis is run again, use
reset_analysis()
.
- class fastoad.api.ValidityDomainChecker(limits: Dict[str, tuple] = None, logger_name: str = None)[source]
Bases:
object
Decorator class that checks variable values against limit bounds
This class aims at producing a status of out of limits variables at the end of an OpenMDAO computation.
The point is to allow to define limit bounds when defining an OpenMDAO system, but to make the check on the OpenMDAO problem after the run.
When defining an OpenMDAO system, use this class as Python decorator to define validity domains:
@ValidityDomainChecker class MyComponent(om.ExplicitComponent): ...
The above code will check values against lower and upper bounds that have been defined when adding OpenMDAO outputs.
Next code shows how to define lower and upper bounds, for inputs and/or outputs.
@ValidityDomainChecker( { "a:variable:with:two:bounds": (-10.0, 1.0), "a:variable:with:lower:bound:only": (0.0, None), "a:variable:with:upper:bound:only": (None, 4.2), }, ) class MyComponent(om.ExplicitComponent): ...
The defined domain limits supersedes lower and upper bounds from OpenMDAO output definitions, but only in the frame of ValidityDomainChecker. In any case, OpenMDAO process is not affected by usage of ValidityDomainChecker.
Validity status can be obtained through log messages from Python logging module after problem has been run with:
... problem.run_model() ValidityDomainChecker.check_problem_variables(problem)
Warnings: - Units of limit values defined in ValidityDomainChecker are assumed to be the
same as in add_input() and add_output() statements of decorated class
Validity check currently only applies to scalar values
- Parameters:
limits – a dictionary where keys are variable names and values are two-values tuples that give lower and upper bound. One bound can be set to None.
logger_name – The named of the logger that will be used. If not provided, name of current module (i.e. “__name__””) will be used.
- classmethod check_problem_variables(problem: Problem) List[CheckRecord] [source]
Checks variable values in provided problem.
Logs warnings for each variable that is out of registered limits.
problem.setup() must have been run.
- Parameters:
problem –
- Returns:
the list of checks
- classmethod check_variables(variables: VariableList, activated_only: bool = True) List[CheckRecord] [source]
Check values of provided variables against registered limits.
- Parameters:
variables –
activated_only – if True, only activated checkers are considered.
- Returns:
the list of checks
- static log_records(records: List[CheckRecord])[source]
Logs warnings through Python logging module for each CheckRecord in provided list if it is not OK.
- Parameters:
records –
- Returns:
- class fastoad.api.Variable(name, **kwargs)[source]
Bases:
Hashable
A class for storing data of OpenMDAO variables.
Instantiation is expected to be done through keyword arguments only.
Beside the mandatory parameter ‘name, kwargs is expected to have keys ‘value’, ‘units’ and ‘desc’, that are accessible respectively through properties
name()
,value()
,units()
anddescription()
.Other keys are possible. They match the definition of OpenMDAO’s method
Component.add_output()
described here.These keys can be listed with class method
get_openmdao_keys()
. Any other key in kwargs will be silently ignored.Special behaviour:
description()
will return the content of kwargs[‘desc’] unless these 2 conditions are met:kwargs[‘desc’] is None or ‘desc’ key is missing
a description exists in FAST-OAD internal data for the variable name
Then, the internal description will be returned by
description()
- Parameters:
kwargs – the attributes of the variable, as keyword arguments
- name
Name of the variable
- get_val(new_units: str | None = None) float | ndarray [source]
Returns the variable value converted in the new_units
- classmethod read_variable_descriptions(file_parent: str | PathLike, update_existing: bool = True)[source]
Reads variable descriptions in indicated folder or package, if it contains some.
The file variable_descriptions.txt is looked for. Nothing is done if it is not found (no error raised also).
Each line of the file should be formatted like:
my:variable||The description of my:variable, as long as needed, but on one line.
- Parameters:
file_parent – the folder path or the package name that should contain the file
update_existing – if True, previous descriptions will be updated. if False, previous descriptions will be erased.
- classmethod update_variable_descriptions(variable_descriptions: Mapping[str, str] | Iterable[Tuple[str, str]])[source]
Updates description of variables.
- Parameters:
variable_descriptions – dict-like object with variable names as keys and descriptions as values
- property value
value of the variable
- property val
value of the variable (alias of property “value”)
- property units
units associated to value (or None if not found)
- property description
description of the variable (or None if not found)
- property desc
description of the variable (or None if not found) (alias of property “description”)
- property is_input
I/O status of the variable.
True if variable is a problem input
False if it is an output
None if information not found
- class fastoad.api.VariableList(iterable=(), /)[source]
Bases:
list
Class for storing OpenMDAO variables.
A list of
Variable
instances, but items can also be accessed through variable names. It also has utilities to be converted from/to some other data structures (python dict, OpenMDAO IndepVarComp, pandas DataFrame)See documentation of
Variable
to see how to manipulate each element.There are several ways for adding variables:
# Assuming these Python variables are ready... var_1 = Variable('var/1', value=0.) metadata_2 = {'value': 1., 'units': 'm'} # ... a VariableList instance can be populated like this: vars_A = VariableList() vars_A.append(var_1) # Adds directly a Variable instance vars_A['var/2'] = metadata_2 # Adds the variable with given name and given metadata
Note
Adding a Variable instance with a name that is already in the VariableList instance will replace the previous Variable instance instead of adding a new one.
# It is also possible to instantiate a VariableList instance from another VariableList # instance or a simple list of Variable instances vars_B = VariableList(vars_A) vars_C = VariableList([var_1]) # An existing VariableList instance can also receive the content of another VariableList # instance. vars_C.update(vars_A) # variables in vars_A will overwrite variables with same # name in vars_C
After that, following equalities are True:
print( var_1 in vars_A ) print( 'var/1' in vars_A.names() ) print( 'var/2' in vars_A.names() )
- metadata_keys() List[str] [source]
- Returns:
the metadata keys that are common to all variables in the list
- append(var: Variable) None [source]
Appends var to the end of the list, unless its name is already used. In that case, var will replace the previous Variable instance with the same name.
- add_var(name, **kwargs)[source]
Adds, or replace, the named variable with given attributes
- Parameters:
name –
kwargs –
- update(other_var_list: list, add_variables: bool = True)[source]
Uses variables in other_var_list to update the current VariableList instance.
- For each Variable instance in other_var_list:
if a Variable instance with same name exists, it is replaced by the one in other_var_list (special case: if one in other_var_list has an empty description, the original description is kept)
if not, Variable instance from other_var_list will be added only if add_variables==True
- Parameters:
other_var_list – source for new Variable data
add_variables – if True, unknown variables are also added
- to_ivc() IndepVarComp [source]
- Returns:
an OpenMDAO IndepVarComp instance with all variables from current list
- to_dataframe() DataFrame [source]
Creates a DataFrame instance from a VariableList instance.
Column names are “name” + the keys returned by
Variable.get_openmdao_keys()
. Values in Series “value” are floats or lists (numpy arrays are converted).- Returns:
a pandas DataFrame instance with all variables from current list
- classmethod from_dict(var_dict: Mapping[str, dict] | Iterable[Tuple[str, dict]]) VariableList [source]
Creates a VariableList instance from a dict-like object.
- Parameters:
var_dict –
- Returns:
a VariableList instance
- classmethod from_ivc(ivc: IndepVarComp) VariableList [source]
Creates a VariableList instance from an OpenMDAO IndepVarComp instance
- Parameters:
ivc – an IndepVarComp instance
- Returns:
a VariableList instance
- classmethod from_dataframe(df: DataFrame) VariableList [source]
Creates a VariableList instance from a pandas DataFrame instance.
The DataFrame instance is expected to have column names “name” + some keys among the ones given by
Variable.get_openmdao_keys()
.- Parameters:
df – a DataFrame instance
- Returns:
a VariableList instance
- classmethod from_problem(problem: Problem, use_initial_values: bool = False, get_promoted_names: bool = True, promoted_only: bool = True, io_status: str = 'all') VariableList [source]
Creates a VariableList instance containing inputs and outputs of an OpenMDAO Problem.
The inputs (is_input=True) correspond to the variables of IndepVarComp components and all the unconnected input variables.
Note
Variables from _auto_ivc are ignored.
- Parameters:
problem – OpenMDAO Problem instance to inspect
use_initial_values – if True, or if problem has not been run, returned instance will contain values before computation
get_promoted_names – if True, promoted names will be returned instead of absolute ones (if no promotion, absolute name will be returned)
promoted_only – if True, only promoted variable names will be returned
io_status – to choose with type of variable we return (“all”, “inputs, “outputs”)
- Returns:
VariableList instance
- classmethod from_unconnected_inputs(problem: Problem, with_optional_inputs: bool = False) VariableList [source]
Creates a VariableList instance containing unconnected inputs of an OpenMDAO Problem.
Warning
problem.setup() must have been run.
If optional_inputs is False, only inputs that have numpy.nan as default value (hence considered as mandatory) will be in returned instance. Otherwise, all unconnected inputs will be in returned instance.
- Parameters:
problem – OpenMDAO Problem instance to inspect
with_optional_inputs – If True, returned instance will contain all unconnected inputs. Otherwise, it will contain only mandatory ones.
- Returns:
VariableList instance