### Install mdoLab baseClasses from source Source: https://github.com/mdolab/baseclasses/blob/main/doc/index.md Installs the mdoLab baseClasses package from its source code. This involves cloning the repository and running the pip install command from the root directory. ```bash pip install . ``` -------------------------------- ### Install mdoLab baseClasses with pip Source: https://github.com/mdolab/baseclasses/blob/main/doc/index.md Installs the mdoLab baseClasses package using pip. This is a standard method for Python package installation. ```bash pip install mdolab-baseclassees ``` -------------------------------- ### Initialize AeroProblem for Onera M6 Tunnel Test (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Illustrates initializing an AeroProblem for the Onera M6 tunnel test case. This example shows configurations for both Euler and RANS solvers, including Mach, area, chord, reference coordinates, and Reynolds number for RANS. ```Python >>> # Onera M6 Test condition (Euler) >>> ap = AeroProblem('m6_tunnel', mach=0.8395, areaRef=0.772893541, chordRef=0.64607, xRef=0.0, zRef=0.0, alpha=3.06) >>> # Onera M6 Test condition (RANS) >>> ap = AeroProblem('m6_tunnel', mach=0.8395, reynolds=11.72e6, reynoldsLength=0.64607, areaRef=0.772893541, chordRef=0.64607, xRef=0.0, zRef=0.0, alpha=3.06, T=255.56) ``` -------------------------------- ### Configure Weight Problem and Fuel Cases in Python Source: https://context7.com/mdolab/baseclasses/llms.txt Sets up a `WeightProblem` for aircraft weight configurations and defines specific loading scenarios using `FuelCase`. This includes specifying unit systems, evaluation functions, fuel fractions, and reserve fuel. Design variables can be added to fuel cases, and surface data or DVGeometry can be set for analysis. The example also shows how to set and retrieve design variables. ```python from baseclasses.problems import WeightProblem, FuelCase # Create weight problem with unit system wp = WeightProblem( name="aircraft_config", units="imperial", # or "metric" evalFuncs=["totalWeight", "cg"] # Functions to evaluate ) # Create fuel cases for different loading scenarios max_fuel = FuelCase( name="max_fuel", fuelFraction=0.95, # 95% of tank volume filled reserveFraction=0.05 # 5% reserve fuel ) min_fuel = FuelCase( name="min_fuel", fuelFraction=0.15, reserveFraction=0.05 ) # Add fuel cases to the weight problem wp.addFuelCases([max_fuel, min_fuel]) # Add design variables to fuel case max_fuel.addDV( "fuelFraction", value=0.95, lower=0.1, upper=1.0, scale=1.0 ) # Set a surface for coordinate-based components (from CFD solver) # surf = cfdSolver.getTriangulatedMeshSurface() # wp.setSurface(surf) # Set DVGeometry for shape optimization # wp.setDVGeo(DVGeo) # Set/get design variables wp.setDesignVars({'aircraft_config_max_fuel_fuelFraction': 0.85}) var_names = wp.getVarNames() ``` -------------------------------- ### Install mdoLab baseClasses with Conda Source: https://github.com/mdolab/baseclasses/blob/main/doc/index.md Installs the mdoLab baseClasses package using Conda from the conda-forge channel. This is useful for managing complex dependencies in scientific computing environments. ```bash conda install -c conda-forge mdolab-baseclasses ``` -------------------------------- ### Implement Custom Solver with BaseSolver in Python Source: https://context7.com/mdolab/baseclasses/llms.txt Extends the `BaseSolver` class to create a custom solver (`MySolver`) that manages solver options with type checking, default values, immutable options, and deprecated options. It includes an example of accessing and using these options within a `solve` method, along with MPI-aware printing. ```python from baseclasses import BaseSolver class MySolver(BaseSolver): def __init__(self, comm=None, options={}): # Define default options with types and values defaultOptions = { "maxIterations": (int, 1000), "tolerance": (float, 1e-8), "outputLevel": (int, [0, 1, 2]), # List = allowed values "preconditioner": (str, ["ilu", "jacobi", "none"]), } # Define immutable options (can't change after creation) immutableOptions = {"meshFile"} # Define deprecated options with messages deprecatedOptions = { "oldOption": "Use 'newOption' instead" } super().__init__( name="MySolver", category="CFD", defaultOptions=defaultOptions, options=options, immutableOptions=immutableOptions, deprecatedOptions=deprecatedOptions, comm=comm ) def solve(self): # Access options max_iter = self.getOption("maxIterations") tol = self.getOption("tolerance") self.pp(f"Solving with maxIter={max_iter}, tol={tol}") ``` -------------------------------- ### MissionProfile Initialization Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Initializes a MissionProfile object, representing a subsection of a mission composed of an ordered set of segments. Start and end points of segments must be continuous. ```python baseclasses.MissionProfile(name, englishUnits=False) ``` -------------------------------- ### MissionSegment addDV Method Example Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Adds a class attribute as a mission design variable (DV), such as Mach or altitude. It allows specifying bounds, scale, and a custom name for the variable used by the optimizer. ```python seg.addDV("initMach", value=0.75, lower=0.0, upper=1.0, scale=1.0) ``` -------------------------------- ### Set Solver Options for ADflow (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Demonstrates how to set solver-specific options that temporarily override the solver's internal settings for a particular aerodynamic problem. This example shows setting `vis4` for the `adflow` solver. ```Python solverOptions={'adflow':{'vis4':0.018}} ``` -------------------------------- ### getResNorms Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Returns the initial, starting, and final residual norms for the solver. ```APIDOC ## GET /getResNorms ### Description Returns the initial, starting, and final residual norms for the solver. ### Method GET ### Endpoint `/getResNorms` ### Parameters #### Path Parameters None #### Query Parameters None ``` -------------------------------- ### printOptions Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Prints a formatted dictionary of all current solver options to standard output on the root processor. ```APIDOC ## printOptions ### Description Prints a nicely formatted dictionary of all the current solver options to the stdout on the root processor. ### Method printOptions ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Prints to stdout. #### Response Example ``` { 'option1': 'value1', 'option2': 'value2' } ``` ``` -------------------------------- ### Solver Options Management Source: https://context7.com/mdolab/baseclasses/llms.txt Demonstrates how to initialize a solver with options, set individual options, and retrieve all or modified options. This is a fundamental aspect of configuring solvers. ```python solver = MySolver(options={"maxIterations": 500, "tolerance": 1e-10}) solver.setOption("outputLevel", 2) # Print all options (MPI-safe, only on root) solver.printOptions() # Print only modified options solver.printModifiedOptions() # Get options dictionary opts = solver.getOptions() modified = solver.getModifiedOptions() ``` -------------------------------- ### BaseSolver Initialization Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Initializes a BaseSolver object with various configuration options. ```APIDOC ## BaseSolver Initialization ### Description Initializes a BaseSolver object with a name, category, and configurable options. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **name** (string) - Required - The name of the solver * **category** (string) - Required - The category of the solver * **defaultOptions** (dict) - Optional - The default options dictionary * **options** (dict) - Optional - The user-supplied options dictionary * **immutableOptions** (set) - Optional - A set of immutable option names * **deprecatedOptions** (dict) - Optional - A dictionary of deprecated option names and messages * **comm** (object) - Optional - The communication object for parallel execution * **informs** (dict) - Optional - A dictionary of exit code: exit message mappings * **checkDefaultOptions** (boolean) - Optional - Flag to check default options for error checking * **caseSensitiveOptions** (boolean) - Optional - Flag for case sensitivity of option names ### Request Example ```json { "name": "MySolver", "category": "MyCategory", "defaultOptions": {"opt1": "val1"}, "options": {"opt2": "val2"}, "immutableOptions": ["opt1"], "deprecatedOptions": {"oldOpt": "Use newOpt instead"}, "comm": null, "informs": {"0": "Success"}, "checkDefaultOptions": true, "caseSensitiveOptions": false } ``` ### Response #### Success Response (200) None (Initialization does not return a value) #### Response Example None ``` -------------------------------- ### getSolution Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Retrieves the solution dictionary from the solver. ```APIDOC ## GET /getSolution ### Description Retrieves the solution dictionary from the solver. ### Method GET ### Endpoint `/getSolution` ### Parameters #### Path Parameters None #### Query Parameters None ``` -------------------------------- ### getDesignVars - Get Current Design Variable Values Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Retrieves the current values of all design variables associated with the object. ```APIDOC ## GET /getDesignVars ### Description Get the current DV values. ### Method GET ### Endpoint /getDesignVars ### Response #### Success Response (200) - **dvs** (object) - A dictionary containing the current design variable values. #### Response Example ```json { "dvs": { "alpha": 2.5, "mach": 0.85 } } ``` ``` -------------------------------- ### Initialize StructProblem Object Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyStruct_problem.md Demonstrates the instantiation of a StructProblem object with a name and an optional load file. This is the first step in setting up a structural analysis problem. ```python sp = StructProblem("lc0", loadFile="loads.txt") ``` -------------------------------- ### MissionProfile Class Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Represents a mission profile, containing an ordered set of segments that make up a single subsection of a mission. Start and end points of each segment in the profile are required to be continuous. ```APIDOC ## class baseclasses.MissionProfile(name, englishUnits=False) ### Description Mission Profile Object: This Mission Profile Object contain an ordered set of segments that make up a single subsection of a mission. Start and end points of each segment in the profile are required to be continuous. ### Methods #### addSegments(segments) Take in a list of segments and append it to the the current list. Check for consistency while we are at it. #### getSegmentParameters() Get the 4 segment parameters from each of the segment it owns. Order is [M1, h1, M2, h2]. #### setDesignVars(missionDVs) Set the variables for this mission profile. * **Parameters**: * **missionDVs** (dict) - Dictionary of variables which may or may not contain the design variable names this object needs ``` -------------------------------- ### Get Current Design Variable Values (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Retrieves the current values of all design variables associated with the object. This function is useful for inspecting the state of the design variables during an optimization process. ```python def getDesignVars(): """ Get the current DV values. * **Returns:** **dvs** : Current design variable values """ pass ``` -------------------------------- ### Evaluate Function Sensitivities for StructProblem Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyStruct_problem.md Demonstrates how to evaluate the sensitivities (gradients) of specified functions with respect to design variables. The sensitivities are saved into a provided dictionary, essential for gradient-based optimization. ```python sp.evalFunctionsSens(funcsSens, evalFuncs) ``` -------------------------------- ### Get Tolerance Values (Python) Source: https://context7.com/mdolab/baseclasses/llms.txt The `getTol` function from `baseclasses.testing` is used to retrieve relative and absolute tolerance values. It can accept a single tolerance value to set both `rtol` and `atol`, or individual values for `rtol` and `atol`. ```python from baseclasses.testing import getTol rtol, atol = getTol(tol=1e-8) # Both set to 1e-8 tol, atol = getTol(rtol=1e-6, atol=1e-12) # Individual values ``` -------------------------------- ### MissionProblem Initialization Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Initializes a MissionProblem object, which contains all information for analyzing a single mission. It aggregates multiple profiles and requires consistent units across all profiles. ```python baseclasses.MissionProblem(name, **kwargs) ``` -------------------------------- ### Initialize AeroProblem for Hydrofoil Simulation (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Demonstrates setting up an AeroProblem for a hydrofoil simulation, including parameters for incompressible flow, viscosity, and cavitation. It highlights custom settings like `muSuthDim` and `TSuthDim`. ```Python >>> # NACA0009 hydrofoil (0.9m semi-span) sailing condition (hacked for incompressible flow and viscosity) >>> # R=461.9 for water vapor, but we can lower it to get a higher Mach number >>> # Hack to get the dynamic viscosity of water, TSuthDim must equal T for this to work! >>> ap = AeroProblem("hydrofoil", areaRef=0.243, alpha=6, chordRef=0.27, T=288.15, V=17, rho=1025, xRef=0.18, yRef=0.0, zRef=0.0, evalFuncs=["cl","cd","lift","drag","cavitation","target_cavitation"], R=100, muSuthDim=1.22e-3, TSuthDim=288.15) ``` -------------------------------- ### Run Training Functions with testflo Source: https://github.com/mdolab/baseclasses/blob/main/doc/regression_example.md This bash command demonstrates how to use `testflo` to run specific training functions. By prefixing training functions with `train_*`, you can execute them all at once using the `-m` flag, which specifies a module-wide matching pattern. ```bash testflo -m train_* ``` -------------------------------- ### getModifiedOptions Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Prints a formatted dictionary of all modified solver options to standard output on the root processor. ```APIDOC ## getModifiedOptions ### Description Prints a nicely formatted dictionary of all the modified solver options to the stdout on the root processor. ### Method getModifiedOptions ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Prints to stdout. #### Response Example ``` { 'option1': 'value1', 'option2': 'value2' } ``` ``` -------------------------------- ### getOption Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Retrieves the current value of a specified solver option. ```APIDOC ## getOption ### Description Retrieves the current value of a specified solver option. The name lookup is not case sensitive. ### Method getOption ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **name** (string) - Required - The name of the option to retrieve. ### Request Example ```json { "name": "optionName" } ``` ### Response #### Success Response (200) * **value** (any) - The current value of the specified option. #### Response Example ```json { "value": "optionValue" } ``` ``` -------------------------------- ### Initialize AeroProblem with Flight Conditions (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Shows how to initialize an AeroProblem object for flight conditions, specifying Mach number, altitude, reference area, chord, and reference coordinates. Units are in meters. ```Python >>> # DPW4 Flight condition (metric) >>> ap = AeroProblem('flight_condition', mach=0.85, altitude=37000*.3048, areaRef=594720*.0254**2, chordRef=275.8*.0254, xRef=1325.9*0.0254, zRef=177.95*.0254) ``` -------------------------------- ### printModifiedOptions Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Prints a formatted dictionary of all solver options modified from their defaults to standard output on the root processor. ```APIDOC ## printModifiedOptions ### Description Prints a nicely formatted dictionary of all the current solver options that have been modified from the defaults to the root processor. ### Method printModifiedOptions ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Prints to stdout. #### Response Example ``` { 'modified_option': 'new_value' } ``` ``` -------------------------------- ### BaseRegTest - Regression Testing Framework Source: https://context7.com/mdolab/baseclasses/llms.txt Shows how to use the BaseRegTest class for creating and validating regression tests. It covers training mode for generating reference files and testing mode for comparison, including parallel testing with MPI. ```python from baseclasses import BaseRegTest import numpy as np # Training mode - creates reference file with BaseRegTest("test_reference.json", train=True) as handler: # Add scalar values handler.root_add_val("lift_coefficient", 0.4523, rtol=1e-6, atol=1e-12) handler.root_add_val("drag_coefficient", 0.0234, rtol=1e-6, atol=1e-12) # Add dictionary of values handler.root_add_dict("forces", { "fx": 1234.5, "fy": 0.123, "fz": 5678.9 }, rtol=1e-6) # Add numpy arrays coords = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) handler.root_add_val("coordinates", coords, rtol=1e-10) # Add metadata (not used for comparison) handler.add_metadata({ "solver_version": "2.0", "test_date": "2024-01-15" }) # Testing mode - compares against reference with BaseRegTest("test_reference.json", train=False) as handler: # Values are automatically compared against reference handler.root_add_val("lift_coefficient", 0.4523) # Passes handler.root_add_val("drag_coefficient", 0.0234) # Passes # Fails with clear error message if values don't match # handler.root_add_val("lift_coefficient", 0.5000) # AssertionError! # Parallel testing with MPI from mpi4py import MPI comm = MPI.COMM_WORLD with BaseRegTest("parallel_test.json", train=False, comm=comm) as handler: # Gather values from all processors local_values = np.array([1.0, 2.0, 3.0]) * comm.rank handler.par_add_val("distributed_array", local_values) # Add sum across all processors handler.par_add_sum("total_sum", local_values) # Add norm across all processors handler.par_add_norm("global_norm", local_values) ``` -------------------------------- ### Initialize WeightProblem and Set DVGeometry Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyWeight_problem.md Initializes a WeightProblem object and associates it with a DVGeometry object. The DVGeometry object is crucial for optimization tasks as it manipulates the constraints managed by the WeightProblem. ```python wp = WeightProblem(name="my_weight_problem", units="kg", evalFuncs=["mass"]) DVGeo = ... # Assume DVGeo object is defined elsewhere wp.setDVGeo(DVGeo) ``` -------------------------------- ### Initialize AeroProblem with Metric Units (Python) Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Demonstrates initializing an AeroProblem object with metric units for a DPW4 test condition. It sets parameters like Mach number, Reynolds number, temperature, area, chord, and reference coordinates. ```Python >>> # DPW4 Test condition (metric) >>> ap = AeroProblem('tunnel_condition', mach=0.85, reynolds=5e6, reynoldsLength=275.8*.0254, T=310.93, areaRef=594720*.0254**2, chordRef=275.8*.0254, xRef=1325.9*0.0254, zRef=177.95*.0254) ``` -------------------------------- ### AeroSolver Initialization Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Initializes the AeroSolver abstract class. It accepts various parameters for configuration, including solver options and communication settings. ```APIDOC ## AeroSolver Initialization ### Description Initializes the AeroSolver abstract class. It accepts various parameters for configuration, including solver options and communication settings. ### Method Constructor ### Endpoint N/A (Class Initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example instantiation (specific parameters depend on derived classes) aero_solver = AeroSolver(name='my_solver', category='flow', comm=None) ``` ### Response #### Success Response (200) N/A (Initialization does not return a response in the typical API sense.) #### Response Example None ``` -------------------------------- ### SolverHistory Source: https://github.com/mdolab/baseclasses/blob/main/doc/utils.md A class to store and print useful values during the execution of a solver. ```APIDOC ## Class: SolverHistory ### Description Stores and prints various useful values during a solver's execution. Note: This class is not designed for parallel execution. ### Parameters - **includeIter** (bool): Whether to include the iteration variable (default: True). - **includeTime** (bool): Whether to include the timing variable (default: True). ### Methods #### addMetadata(name, data) Add a piece of metadata to the history. - **Parameters**: - **name** (str): The name/key for the metadata. - **data**: The data to store. #### addVariable(name, varType, printVar=False, valueFormat=None, overwrite=False) Define a new field to be stored in the history. - **Parameters**: - **name** (str): The variable name. - **varType** (type): The variable type (e.g., int, float, str). - **printVar** (bool): Whether to include the variable in iteration printouts (default: False). - **valueFormat** (str): Format string for printing variables (e.g., `'{:17.11e}'`). - **overwrite** (bool): Whether to overwrite existing variables with the same name (default: False). #### getData() Get the recorded data. - **Returns**: dict: A dictionary containing the recorded data. ``` -------------------------------- ### pp Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Prints a given Python object to standard output, potentially flushing the stream. ```APIDOC ## pp ### Description This method prints `obj` (via `pprint`) on the root proc of `self.comm` if it exists. Otherwise, it will just print `obj`. ### Method pp ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **obj** (any) - Required - Any Python object to be printed. * **flush** (boolean) - Optional - If True, the stream will be flushed. Defaults to True. ### Request Example ```json { "obj": {"key": "value"}, "flush": true } ``` ### Response #### Success Response (200) Prints the object to stdout. #### Response Example ``` {'key': 'value'} ``` ``` -------------------------------- ### getStates Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Returns the states calculated on the current processor. ```APIDOC ## GET /getStates ### Description Returns the states calculated on the current processor. ### Method GET ### Endpoint `/getStates` ### Parameters #### Path Parameters None #### Query Parameters None ``` -------------------------------- ### MissionSegment Initialization Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Initializes a MissionSegment object, the fundamental building block for the mission solver. Requires a 'phase' parameter to define the segment type. ```python baseclasses.MissionSegment(phase, **kwargs) ``` -------------------------------- ### globalNKPreCon Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Applies preconditioning to the residual vector for a coupled Newton-Krylov method. ```APIDOC ## POST /globalNKPreCon ### Description Applies preconditioning to the residual vector for a coupled Newton-Krylov method. ### Method POST ### Endpoint `/globalNKPreCon` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **in_vec** (array) - Required - The residual vector to be preconditioned. ``` -------------------------------- ### Set Design Variables and Evaluate Functions Source: https://context7.com/mdolab/baseclasses/llms.txt Demonstrates setting design variables for aerodynamic and structural components and evaluating specified functions. This snippet is for a general Python environment. ```python asp.setDesignVars({'alpha_wing_analysis': 2.5}) # Add variables to pyOptSparse optimization problem # asp.addVariablesPyOpt(optProb) # Evaluate functions from both problems funcs = {} evalFuncs = ["cl", "cd", "mass", "failure"] asp.evalFunctions(funcs, evalFuncs) ``` -------------------------------- ### baseclasses.AeroProblem Constructor Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Initializes an AeroProblem object to represent a single aerodynamic analysis. It takes a name and various optional parameters to define thermodynamic and flight conditions. ```APIDOC ## POST /baseclasses.AeroProblem ### Description Initializes an AeroProblem object to represent a single aerodynamic analysis. It takes a name and various optional parameters to define thermodynamic and flight conditions. ### Method POST ### Endpoint /baseclasses.AeroProblem ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - Name of this aerodynamic problem. - **evalFuncs** (list) - Optional - The names of the functions the user wants evaluated with this aeroProblem. - **mach** (float) - Optional - Set the Mach number for the simulation. - **machRef** (float) - Optional - Sets the reference Mach number for the simulation. - **machGrid** (float) - Optional - Set the Mach number for the grid. - **alpha** (float) - Optional - Set the angle of attack in degrees. - **beta** (float) - Optional - Set the side-slip angle in degrees. - **altitude** (float) - Optional - Set all thermodynamic parameters from the 1976 standard atmosphere. The altitude must be given in meters. - **phat** (float) - Optional - Set the rolling rate coefficient. - **qhat** (float) - Optional - Set the pitch rate coefficient. - **rhat** (float) - Optional - Set the yawing rate coefficient. - **degPol** (int) - Optional - Degree of polynomial for prescribed motion. ADflow only. - **coefPol** (list) - Optional - Coefficients of polynomial motion. ADflow only. - **degFourier** (int) - Optional - Degree of Fourier series for prescribed motion. ADflow only. ### Request Example ```json { "name": "MyAeroProblem", "mach": 0.5, "altitude": 10000, "alpha": 5.0 } ``` ### Response #### Success Response (200) - **AeroProblem object** - An instance of the AeroProblem class initialized with the provided parameters. #### Response Example ```json { "message": "AeroProblem created successfully" } ``` ``` -------------------------------- ### Initialize AeroStructProblem Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAeroStruct_problem.md Initializes the AeroStructProblem class, which represents a coupled aero-structural analysis. It requires instances of AeroProblem and StructProblem as input. ```python class AeroStructProblem(ap, sp, **kwargs): """ The main purpose of this class is to represent all relevant information for a coupled aero-structural analysis. To this end, it maintains a reference to an AaeroProblem and a StructProblem. * **Parameters:** **ap** : An instance of the AeroProblem class defining the aerodynamic part of the problem. **sp** : An instance of the StructProblem class defining the structural part of the problem """ pass ``` -------------------------------- ### MissionProblem setUnits Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Sets the units and gravitational constant for the mission problem. This ensures consistency across all analyses. ```python setUnits(module) ``` -------------------------------- ### Write Triangulated Surface Mesh to Tecplot Format Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Exports the solver's triangulated surface mesh data into a Tecplot (.dat) file. This allows for visualization and analysis of the surface mesh in external tools. Optionally, a specific group of boundaries can be included. ```python solver.writeTriangulatedSurfaceTecplot(fileName='surface_mesh.dat', groupName='fuselage') ``` -------------------------------- ### FluidProperties - Thermodynamic Calculations Source: https://context7.com/mdolab/baseclasses/llms.txt Demonstrates the usage of the FluidProperties class to define and manipulate thermodynamic properties of fluids. It covers default air properties, custom fluid definitions, and calculations using English units. ```python from baseclasses.problems import FluidProperties # Default air properties air = FluidProperties() print(f"Gas constant R: {air.R:.3f} J/(kg·K)") # 287.055 print(f"Specific heat ratio γ: {air.gamma}") # 1.4 print(f"Prandtl number Pr: {air.Pr}") # 0.72 # Custom fluid (e.g., water vapor with hacked properties) custom_fluid = FluidProperties( R=461.9, # Specific gas constant gamma=1.33, # Specific heat ratio Pr=1.0, # Prandtl number muSuthDim=1.0e-5, # Reference viscosity TSuthDim=300.0, # Reference temperature SSuthDim=120.0 # Sutherland temperature ) # English units (ft-lbf/slug/R) air_english = FluidProperties(englishUnits=True) print(f"R (English): {air_english.R:.3f}") # ~1716.574 # Compute viscosity at a temperature air.updateViscosity(T=288.15) # Standard sea level print(f"Dynamic viscosity μ: {air.mu:.6e} Pa·s") ``` -------------------------------- ### redirectingIO Source: https://github.com/mdolab/baseclasses/blob/main/doc/utils.md Redirects stdout and optionally stderr within a 'with' block, restoring them upon exit. The provided file streams are closed after the block. ```APIDOC ## redirectingIO ### Description A function that redirects stdout in a with block and returns to the stdout after the with block completes. The filestream passed to this function will be closed after exiting the with block. ### Method N/A (This is a Python function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from baseclasses.utils import redirectingIO with redirectingIO(open("adflow_out.txt", "w")): # Code that writes to stdout or stderr pass ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters * **f_out** (file stream) - Required - A file stream that stdout should be redirected to. * **f_err** (file stream) - Optional - A file stream to redirect stderr to. If none is specified it is set to f_out. ``` -------------------------------- ### AeroSolver - CFD Solver Base Class Source: https://context7.com/mdolab/baseclasses/llms.txt Illustrates the creation of a custom CFD solver by inheriting from AeroSolver. It shows initialization with default options, setting aerodynamic problems, and managing surface geometry and groupings. ```python from baseclasses.solvers import AeroSolver import numpy as np class MyCFDSolver(AeroSolver): def __init__(self, comm=None, options={}): defaultOptions = { "gridFile": (str, ""), "L2Convergence": (float, 1e-8), } super().__init__( name="MyCFDSolver", category="CFD", defaultOptions=defaultOptions, options=options, comm=comm ) # Initialize families dict for boundary grouping self.families = {} def setAeroProblem(self, aeroProblem): """Set the current aero problem""" self.curAP = aeroProblem def getSurfaceCoordinates(self, groupName): """Return surface coordinates for a group""" # Implementation specific to solver pass # Usage with mesh and geometry solver = MyCFDSolver(comm=comm, options={"gridFile": "wing.cgns"}) # Set mesh warping object # solver.setMesh(mesh) # Set DVGeometry for shape optimization # solver.setDVGeo(DVGeo) # Add custom family groupings solver.addFamilyGroup("wing_surface", ["wing_upper", "wing_lower"]) # Get triangulated surface for constraints # surf = solver.getTriangulatedMeshSurface(groupName="wing_surface") # Check solution/adjoint failure for optimization # solver.checkSolutionFailure(aeroProblem, funcs) # solver.checkAdjointFailure(aeroProblem, funcsSens) ``` -------------------------------- ### Setting AeroProblem Variables Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_problem.md Demonstrates how to access and set variables within an AeroProblem object after its creation. This allows for dynamic modification of simulation parameters. ```python aeroProblem.mach = 0.5 aeroProblem.altitude = 10000.0 ``` -------------------------------- ### MissionProblem getSegments Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Returns an ordered list of all segments constituting the mission. ```python getSegments() ``` -------------------------------- ### MissionSegment propagateParameters Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Calculates and sets the final velocity, Mach number, and altitude based on initial values and the segment type. ```python propagateParameters() ``` -------------------------------- ### MissionProfile getSegmentParameters Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Retrieves the four key parameters (Mach 1, Altitude 1, Mach 2, Altitude 2) for each segment within the MissionProfile. ```python getSegmentParameters() ``` -------------------------------- ### Define Mission Segments, Profile, and Problem in Python Source: https://context7.com/mdolab/baseclasses/llms.txt Defines individual flight phases (`MissionSegment`), combines them into a flight mission profile (`MissionProfile`), and sets up a complete mission analysis (`MissionProblem`). This involves specifying parameters like fuel fraction, speed, altitude, and Mach number for each phase. Design variables can also be added to segments for optimization. ```python from baseclasses import MissionProblem, MissionProfile, MissionSegment # Define individual mission segments takeoff = MissionSegment( phase="fuelFraction", fuelFraction=0.970 # Fuel burned as fraction of starting weight ) climb_cvel = MissionSegment( phase="cvelClimb", # Constant velocity climb initCAS=250.0, # Calibrated airspeed (knots or m/s) initAlt=0.0, # Starting altitude finalMach=0.78, # Target Mach at end of climb nIntervals=4 # Number of analysis intervals ) climb_cmach = MissionSegment( phase="cmachClimb", # Constant Mach climb initMach=0.78, initAlt=10000, finalAlt=35000, nIntervals=6 ) cruise = MissionSegment( phase="cruise", initMach=0.85, initAlt=35000, nIntervals=8 ) descent = MissionSegment( phase="cmachDescent", initMach=0.85, initAlt=35000, finalAlt=10000, nIntervals=4 ) landing = MissionSegment( phase="fuelFraction", fuelFraction=0.990 ) # Create mission profile (segments must be continuous) profile = MissionProfile(name="trans_atlantic", englishUnits=True) profile.addSegments([takeoff, climb_cvel, climb_cmach, cruise, descent, landing]) # Create mission problem mission = MissionProblem(name="design_mission", evalFuncs=["fuel"]) mission.addProfile(profile) # Add design variables to segments for optimization cruise.addDV("initMach", lower=0.7, upper=0.9, scale=1.0) cruise.addDV("initAlt", lower=30000, upper=45000, scale=1e-4) # Print mission summary print(mission) # Output shows all segments with Alt, Mach, CAS, TAS values ``` -------------------------------- ### setOption Source: https://github.com/mdolab/baseclasses/blob/main/doc/BaseSolver.md Sets the value of a specified solver option. ```APIDOC ## setOption ### Description Sets the value of a specified solver option. The name lookup is not case sensitive, and the type of the value is checked for consistency. ### Method setOption ### Endpoint None (This is a method of the BaseSolver class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **name** (string) - Required - The name of the option to set. * **value** (any) - Required - The value to set for the option. ### Request Example ```json { "name": "optionName", "value": "newValue" } ``` ### Response #### Success Response (200) None (This method modifies the solver state and does not return a value). #### Response Example None ``` -------------------------------- ### Set Processor States Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyAero_solver.md Sets the state information on the current processor. This method is used to update or initialize the state variables relevant to the solver's operation. ```python solver.setStates(states) ``` -------------------------------- ### MissionSegment Class Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md The basic building block of the mission solver. ```APIDOC ## class baseclasses.MissionSegment(phase, **kwargs) ### Description Mission Segment Object: This is the basic building block of the mission solver. ### Parameters * **phase** (string) - Segment type selector valid options include ### Methods #### addDV(paramKey, lower=-1e+20, upper=1e+20, scale=1.0, name=None) Add one of the class attributes as a mission design variable. Typical variables are mach or velocity and altitude. An error will be given if the requested DV is not allowed to be added. * **Parameters**: * **dvName** (string) - Name used by the optimizer for this variables. * **paramKey** (string) - Name of variable to add. See above for possible ones. * **value** (float) - Initial value for variable. If not given, current value of the attribute will be used. * **lower** (float) - Optimization lower bound. Default is unbonded. * **upper** (float) - Optimization upper bound. Default is unbounded. * **scale** (float) - Set scaling parameter for the optimization to use. * **name** (string) - Overwrite the name of this variable. This is typically only used when the user wishes to have multiple aeroProblems to explictly use the same design variable. ### Examples ```pycon >>> # Add initMach variable with typical bounds >>> seg.addDV("initMach", value=0.75, lower=0.0, upper=1.0, scale=1.0) ``` #### determineInputs() Determine which of the four parameters (h, M, CAS, TAS) are inputs, which can be updated directly by the DV. For each end, there should be two inputs. At this point, the two beginning inputs should already be determined during initalization or by the MissionProfile. #### propagateParameters() Set the final V,M,h base on initial values and segType. ``` -------------------------------- ### MissionProfile addSegments Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Appends a list of segments to the current MissionProfile, while also checking for consistency among the segments. ```python addSegments(segments) ``` -------------------------------- ### Evaluate Functions for StructProblem Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyStruct_problem.md Illustrates the process of evaluating specified functions for the structural problem. The results are stored in a provided dictionary. This method is used to compute performance metrics or other desired outputs. ```python sp.evalFunctions(funcs, evalFuncs) ``` -------------------------------- ### WeightProblem Class Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyWeight_problem.md The WeightProblem class handles the estimation of component weights. It allows for the addition of components, fuel cases, and constraints, and provides methods to set design variables and output data. ```APIDOC ## Class: WeightProblem ### Description Manages the estimation of component weights within a configuration. It stores all information required to estimate the weight of a particular component configuration. ### Parameters * **name** (str): A name for the configuration. * **units** (str): Defines the units used for the weight problem. This unit system is transferred to all components. * **kwargs**: Additional keyword arguments. ### Methods #### addComponents(components) * **Description**: Appends a list of components to the internal component list. * **Parameters**: * **components** (list): A list of component objects to add. #### addConstraintsPyOpt(optProb=None) * **Description**: Adds linear constraints for each fuel case and non-linear constraints for total TOW less than MTOW. * **Parameters**: * **optProb** (object, optional): Optimization problem definition to which variables are added. Defaults to None. #### addFuelCases(cases) * **Description**: Appends a list of fuel cases to the weight problem. * **Parameters**: * **cases** (list): A list of fuel case objects to add. #### addVariablesPyOpt(optProb) * **Description**: Adds the current set of variables to the optProb object. * **Parameters**: * **optProb** (object): Optimization problem definition to which variables are added. #### getFuelCase(caseName) * **Description**: Retrieves the fuel case object associated with a given case name. * **Parameters**: * **caseName** (str): The name of the fuel case to retrieve. * **Returns**: The fuel case object. #### getVarNames() * **Description**: Gets the variable names associated with this weight problem. * **Returns**: list: A list of variable names. #### resetFuelCase() * **Description**: Resets the fuel weight for the current case. #### setDVGeo(DVGeo) * **Description**: Sets the DVGeometry object responsible for manipulating this object. Required for optimization. * **Parameters**: * **dvGeo** (object): The DVGeometry object. * **Example**: ```pycon >>> wp.setDVGeo(DVGeo) ``` #### setDesignVars(x) * **Description**: Sets the variables in the x-dict for this object. * **Parameters**: * **x** (dict): Dictionary of variables which may or may not contain the design variable names this object needs. #### setFuelCase(case) * **Description**: Loops over the components and sets the specified fuel case. * **Parameters**: * **case** (str): The name of the fuel case to set. #### setSurface(surf) * **Description**: Sets the surface this configuration will use for projections. * **Parameters**: * **surf** (object): The surface representation to use for projections. Can be a pyGeo surface object or a triangulated surface. * **Example**: ```pycon >>> # Using a triangulated mesh from ADFLOW: >>> CFDsolver = ADFLOW(comm=comm, options=aeroOptions) >>> surf = CFDsolver.getTriangulatedMeshSurface() >>> wp.setSurface(surf) >>> # Or using a pyGeo surface object: >>> surf = pyGeo("iges", fileName="wing.igs") >>> wp.setSurface(surf) ``` #### writeMassesTecplot(filename) * **Description**: Writes mass data to a Tecplot file. A `.dat` suffix is appended to the filename. * **Parameters**: * **filename** (str): The base filename for writing the masses. #### writeProblemData(fileName) * **Description**: Writes the problem data to a file. * **Parameters**: * **fileName** (str): The name of the file to write. #### writeSurfaceTecplot(fileName) * **Description**: Writes the triangulated surface mesh used in the weight_problem object to a Tecplot file for visualization. * **Parameters**: * **fileName** (str): The file name for the Tecplot file. Should have a `.dat` extension. #### writeTecplot(fileName) * **Description**: Writes a visualization file for components that have coordinates. Useful for publication and constraint verification. * **Parameters**: * **fileName** (str): The file name for the Tecplot file. Should have a `.dat` extension. ``` -------------------------------- ### Define Structural Analysis Conditions with StructProblem Source: https://context7.com/mdolab/baseclasses/llms.txt The StructProblem class defines conditions for structural analysis, including external loads and load factors, interfacing with structural solvers. It supports evaluation of functions like mass, stress, and displacement. It requires the 'baseclasses' library. ```python from baseclasses import StructProblem # Define a structural load case with external loads from CFD sp = StructProblem( name="cruise_loads", loadFile="aero_loads.txt", # External load file from ADflow/Tripan loadFactor=2.5, # Load factor (e.g., for limit load) evalFuncs=["mass", "stress", "displacement"] ) # Access the load case properties print(f"Load case: {sp.name}") print(f"Load factor: {sp.loadFactor}") # The structural solver evaluates functions funcs = {} sp.evalFuncs = ["mass", "ks_failure"] # Solver populates funcs dict with results ``` -------------------------------- ### MissionProblem getAltitudeConsSens Method Source: https://github.com/mdolab/baseclasses/blob/main/doc/pyMission_problem.md Solves for the sensitivity of altitude with respect to CAS and Mach, at which CAS equals Mach. ```python getAltitudeConsSens(CAS, mach, alt, stepSize=1e-20) ```