### Example: TubeBeam1 Initialization and Setup Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/structures/legacy/beams.html Demonstrates the initialization of a TubeBeam1 object and the setup of structural analysis with specific loads and constraints. ```python opti = cas.Opti() beam = TubeBeam1( opti=opti, length=60 / 2, points_per_point_load=50, diameter_guess=100, bending=True, torsion=False, ) lift_force = 9.81 * 103.873 load_location = opti.variable() opti.set_initial(load_location, 15) opti.subject_to( [ load_location > 2, load_location < 60 / 2 - 2, load_location == 18, ] ) beam.add_point_load(load_location, -lift_force / 3) beam.add_uniform_load(force=lift_force / 2) beam.setup() # Tip deflection constraint opti.subject_to( [ # beam.u[-1] < 2, # Source: http://web.mit.edu/drela/Public/web/hpa/hpa_structure.pdf # beam.u[-1] > -2 # Source: http://web.mit.edu/drela/Public/web/hpa/hpa_structure.pdf beam.du * 180 / cas.pi < 10, beam.du * 180 / cas.pi > -10, ] ) opti.subject_to( [ ``` -------------------------------- ### CasADi Integrator Setup Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/numpy/integrate.html Sets up and uses a CasADi integrator for solving ordinary differential equations (ODEs). This is useful when a custom ODE solver is needed or when integrating with CasADi's optimization capabilities. Requires CasADi to be installed. ```python if backend == "casadi_func": t_variable = _cas.MX.sym("t") y_variables = _cas.MX.sym("y", y0.shape[0], y0.shape[1]) fun = np.array(fun(t_variable, y_variables)) """ At this point: * `fun` is a CasADi expression (cas.MX) * `t_variable` is a CasADi variable (cas.MX) * `y_variables` is a CasADi variable (cas.MX), possibly a vector of variables """ t0 = t_span[0] tf = t_span[1] # sim_time = t0 + (tf - t0) * t_variable ode = _cas.substitute( fun, t_variable, # from normalized time # (t_variable - t0) / (tf - t0), # to real time t0 + (tf - t0) * t_variable, # to real time ) * (tf - t0) # Find parameters by finding all variables in the expression graph that are not t_variable or y_variables all_vars = _cas.symvar(ode) # All variables found in the expression graph def variable_is_t_or_y(var): return ( _cas.is_equal(var, t_variable) or _cas.is_equal(var, y_variables) or any( [ _cas.is_equal(var, y_variables[i]) for i in range(np.prod(y_variables.shape)) ] ) ) parameters = _cas.vertcat( *[var for var in all_vars if not variable_is_t_or_y(var)] ) simtime_eval = np.linspace(0, 1, 100) # Define the integrator integrator = _cas.integrator( "integrator", "cvodes", # 'idas', { "x": y_variables, "p": parameters, "t": t_variable, "ode": ode, "quad": 1, }, 0, simtime_eval, { # Options "abstol": 1e-8, "reltol": 1e-6, }, ) res = integrator( x0=y0, p=parameters, ) return integrate._ivp.ivp.OdeResult( t=t0 + (tf - t0) * res["qf"], y=res["xf"], t_events=None, y_events=None, nfev=0, njev=0, nlu=0, status=0, message="", success=True, sol=None, ) else: raise ValueError(f"Invalid backend: {backend}") ``` -------------------------------- ### Control Variable Initialization Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Illustrates the default initialization of control variables to zero within a dynamics instance. This is a conceptual example. ```python For each control variable, self.control_var = 0 ``` -------------------------------- ### Example Usage and Verification Source: https://aerosandbox.readthedocs.io/en/master/_modules/discrete_squared_curvature_derivation_simpson_bernstein.html Provides a concrete example by defining a sample function, calculating necessary symbolic values, substituting them into the derived curvature formula, and comparing the result with an exact integration of the second derivative squared. ```python if __name__ == "__main__": x = s.symbols("x", real=True) a = 0 b = 4 def example_f(x): return x**2 + 2 * x + 3 h_val = b - a hm_val = 1 hp_val = 3 df_val = example_f(b) - example_f(a) dfm_val = example_f(a) - example_f(a - hm_val) dfp_val = example_f(b + hp_val) - example_f(b) subs = { h: h_val, hm: hm_val, hp: hp_val, df: df_val, dfm: dfm_val, dfp: dfp_val, } exact = s.N(s.integrate(example_f(x).diff(x, 2) ** 2, (x, a, b))) eqn = s.N(res.subs(subs)) print(f"exact: {exact}") print(f"eqn: {eqn}") print(f"ratio: {exact/eqn}") ``` -------------------------------- ### Example Usage and Verification Source: https://aerosandbox.readthedocs.io/en/master/_modules/discrete_squared_curvature_derivation_bernstein.html Provides an example of how to use the derived formula. It defines a sample function, calculates the necessary symbolic values, substitutes them into the derived result, and compares it with the exact integration of the second derivative squared. ```python if __name__ == "__main__": x = s.symbols("x", real=True) a = 0 b = 4 def example_f(x): return x**3 + 1 h_val = b - a hm_val = 1 hp_val = 1 df_val = example_f(b) - example_f(a) dfm_val = example_f(a) - example_f(a - hm_val) dfp_val = example_f(b + hp_val) - example_f(b) ddfm_val = df_val - dfm_val ddfp_val = dfp_val - df_val subs = { h: h_val, hm: hm_val, hp: hp_val, df: df_val, dfm: dfm_val, dfp: dfp_val, # ddfm: ddfm_val, # ddfp: ddfp_val, } exact = s.N(s.integrate(example_f(x).diff(x, 2) ** 2, (x, a, b))) eqn = s.N(res.subs(subs)) print(f"exact: {exact}") print(f"eqn: {eqn}") print(f"ratio: {exact / eqn}") ``` -------------------------------- ### Example Usage Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/dynamics/point_mass/point_2D/cartesian.html Demonstrates the instantiation of the DynamicsPointMass2DCartesian class with default parameters. ```python if __name__ == "__main__": dyn = DynamicsPointMass2DCartesian() ``` -------------------------------- ### Initialize and Solve Optimization Problem Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/optimization/opti/index.html Demonstrates the basic workflow of setting up an optimization problem: initializing Opti, defining variables, adding constraints, setting the objective, and solving. ```python >>> opti = asb.Opti() # Initializes an optimization environment >>> x = opti.variable(init_guess=5) # Initializes a new variable in that environment >>> f = x ** 2 # Evaluates a (in this case, nonlinear) function based on a variable >>> opti.subject_to(x > 3) # Adds a constraint to be enforced >>> opti.minimize(f) # Sets the objective function as f >>> sol = opti.solve() # Solves the problem using CasADi and IPOPT backend >>> print(sol(x)) # Prints the value of x at the optimum. ``` -------------------------------- ### Get Source Code From Location Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/tools/inspect_tools/index.html Retrieves the source code of a statement starting at a specified file location. ```APIDOC ## GET /aerosandbox/tools/inspect_tools/get_source_code_from_location ### Description Gets the source code of the single statement that begins at the file location specified. File location must, at a minimum, contain the filename and the line number. Optionally, you can also provide code_context. ### Method GET ### Endpoint /aerosandbox/tools/inspect_tools/get_source_code_from_location ### Parameters #### Query Parameters - **filename** (Union[pathlib.Path, str]) - Required - A Path object or string containing a filename. - **lineno** (int) - Required - The line number in the file where this function was called. Should refer to the first line of a string in question. - **code_context** (str) - Optional - The immediate line of code at this location. If provided, allows short-circuiting (bypassing file I/O) if the line is a complete expression. - **strip_lines** (bool) - Optional - A boolean flag about whether or not to strip leading and trailing whitespace off each line of a multi-line function call. ### Returns The source code of the call, as a string. Might be a multi-line string (i.e., contains '\n' characters) if the call is multi-line. Almost certainly (but not guaranteed due to edge cases) to be a complete Python expression. ### Example ```python # Assuming get_source_code_from_location is imported filename = "my_file.py" lineno = 5 code_context = "print(get_caller_source_location(stacklevel=2))" source_code = get_source_code_from_location(filename=filename, lineno=lineno, code_context=code_context, strip_lines=True) print(source_code) ``` ``` -------------------------------- ### Dynamics Initialization Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/point_mass/index.rst.txt Demonstrates how to initialize a Dynamics instance, setting mass properties and initial state/control variables. ```python For each state variable, self.state_var = state_var For each indirect control variable, self.indirect_control_var = indirect_control_var For each control variable, self.control_var = 0 ``` -------------------------------- ### Initialize DynamicsRigidBody3DBodyEuler Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/dynamics/rigid_body/rigid_3D/body_euler.html Example of initializing the DynamicsRigidBody3DBodyEuler class with basic mass properties. This is a starting point for simulating rigid body dynamics. ```python if __name__ == "__main__": import aerosandbox as asb dyn = DynamicsRigidBody3DBodyEuler(mass_props=asb.MassProperties(mass=1)) ``` -------------------------------- ### Initialize and Solve Optimization Problem Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/optimization/index.rst.txt Demonstrates the basic workflow of setting up an optimization problem: initializing Opti, defining variables, adding constraints, setting the objective, and solving. Requires importing aerosandbox as asb. ```python opti = asb.Opti() # Initializes an optimization environment x = opti.variable(init_guess=5) # Initializes a new variable in that environment f = x ** 2 # Evaluates a (in this case, nonlinear) function based on a variable opti.subject_to(x > 3) # Adds a constraint to be enforced opti.minimize(f) # Sets the objective function as f sol = opti.solve() # Solves the problem using CasADi and IPOPT backend print(sol(x)) # Prints the value of x at the optimum. ``` -------------------------------- ### Installed Engines Mass Calculation Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/library/weights/raymer_general_aviation_weights/index.rst.txt Computes the mass of the engines installed on a general aviation aircraft. ```APIDOC ## POST /api/mass/engines ### Description Computes the mass of the engines installed on a general aviation aircraft, according to Raymer's Aircraft Design. Includes propellers and engine mounts. ### Method POST ### Endpoint /api/mass/engines ### Parameters #### Request Body - **n_engines** (integer) - Required - The number of engines installed on the aircraft. - **mass_per_engine** (number) - Required - The mass of a single engine [kg]. ### Response #### Success Response (200) - **mass** (number) - The mass of the engines installed on the aircraft [kg]. #### Response Example ```json { "mass": 400.0 } ``` ``` -------------------------------- ### Setup Beam Analysis Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/structures/legacy/beams.html Sets up the beam analysis problem, including discretization and load application. This should be run last. ```APIDOC ## POST /setup ### Description Sets up the problem. Run this last. ### Method POST ### Endpoint `/setup` ### Parameters #### Request Body - **bending_BC_type** (string) - Optional - Type of bending boundary condition. Defaults to "cantilevered". ### Response #### Success Response (200) - **None** (None) - The operation is performed in-place. #### Response Example ```json null ``` ``` -------------------------------- ### State Variable Assignment Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Demonstrates how state variables are assigned within a dynamics instance. This is a conceptual example. ```python For each state variable, self.state_var = state_var ``` -------------------------------- ### Initialize LinearPotentialFlow and Run Simulation Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/aerodynamics/aero_3D/linear_potential_flow.html Demonstrates how to initialize the LinearPotentialFlow with an airplane and operating point, then run the simulation to obtain aerodynamic results. The results are printed to the console. ```python import aerosandbox as asb from pathlib import Path geometry_folder = Path(__file__).parent / "test_aero_3D" / "geometries" import sys sys.path.insert(0, str(geometry_folder)) from vanilla import airplane as vanilla ### Do the AVL run lpf = LinearPotentialFlow( airplane=vanilla, op_point=asb.OperatingPoint( atmosphere=asb.Atmosphere(altitude=0), velocity=10, alpha=0, beta=0, p=0, q=0, r=0, ), ) dis = lpf.discretization res = lpf.run() for k, v in res.items(): print(f"{str(k).rjust(10)} : {v}") ``` -------------------------------- ### Estimate Installed Avionics Mass Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/library/weights/raymer_cargo_transport_weights.html Computes the installed mass of avionics for a cargo/transport aircraft. The input is the uninstalled mass of the avionics. ```python def mass_avionics( mass_uninstalled_avionics: float, ): """ Computes the mass of the avionics for a cargo/transport aircraft, according to Raymer's Aircraft Design: A Conceptual Approach. Args: mass_uninstalled_avionics: The mass of the avionics, before installation [kg]. Returns: The mass of the avionics, as installed [kg]. """ return (1.73 * (mass_uninstalled_avionics / u.lbm) ** 0.983) * u.lbm ``` -------------------------------- ### Instantiate and Evaluate FittedModel Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/index.rst.txt Demonstrates how to instantiate a FittedModel with data and parameters, and then evaluate it at a given point. ```python my_fitted_model = FittedModel(...) >>> y = my_fitted_model(x) ``` -------------------------------- ### Parameter Initialization Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/optimization/opti/index.rst.txt Demonstrates how to initialize scalar and vector parameters using the `opti.parameter()` method. ```APIDOC ## Parameter Initialization ### Description Initializes a parameter, which can be either scalar or a vector. ### Method `opti.parameter(value, n_params=None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **value** (float or ndarray) - The initial value for the parameter. For vectors, this can be a float (if `n_params` is provided) or a NumPy ndarray. - **n_params** (int) - Optional. Used to manually override the dimensionality of the parameter. If not provided, the dimensionality is inferred from `value`. ### Request Example ```python import aerosandbox as asb import numpy as np opti = asb.Opti() # Scalar parameter scalar_param = opti.parameter(value=5) # Vector parameter initialized with a scalar value vector_param_scalar = opti.parameter(value=5, n_params=10) # Vector parameter initialized with a NumPy array vector_param_array = opti.parameter(value=np.linspace(0, 5, 10)) ``` ### Response #### Success Response (200) Returns the parameter itself as a symbolic CasADi variable (MX type). #### Response Example ``` # Symbolic CasADi variable (MX type) ``` ``` -------------------------------- ### Vector Transformation Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/numpy/index.rst.txt Example demonstrating how to transform a vector from body axes to earth axes using a pre-multiplied rotation matrix. ```python vector_earth = rotation_matrix_from_euler_angles(np.pi / 4, np.pi / 4, np.pi / 4) @ vector_body ``` -------------------------------- ### State Variable Initialization Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/point_mass/index.rst.txt Shows the default initialization values for various state variables. ```python x_e :value: 0 y_e :value: 0 z_e :value: 0 u_e :value: 0 v_e :value: 0 w_e :value: 0 ``` -------------------------------- ### Nelder-Mead Optimization Setup Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/aerodynamics/aero_2D/airfoil_optimizer/airfoil_optimizer.html Initializes and runs the Nelder-Mead optimization algorithm. It sets up the initial simplex, defines optimization options such as maximum iterations and tolerances, and calls the minimize function with the augmented objective and callback. ```python draw(initial_airfoil) initial_simplex = (0.5 + 1 * np.random.random((len(x0) + 1, len(x0)))) * x0 initial_simplex[0, :] = x0 # Include x0 in the simplex print("Initializing simplex (give this a few minutes)...") res = optimize.minimize( fun=augmented_objective, x0=pack(lower_guess, upper_guess), method="Nelder-Mead", callback=callback, options={ "maxiter": 10**6, "initial_simplex": initial_simplex, "xatol": 1e-8, "fatol": 1e-6, "adaptive": False, }, ) final_airfoil = make_airfoil(res.x) ``` -------------------------------- ### Indirect Control Variable Assignment Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Shows the assignment of indirect control variables within a dynamics instance. This is a conceptual example. ```python For each indirect control variable, self.indirect_control_var = indirect_control_var ``` -------------------------------- ### XFoil Analysis Setup Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/index.html Initializes an explicit analysis using XFoil for airfoil performance. Configurable with Reynolds number, Mach number, transition points, and XFoil command. ```python _class _aerosandbox.XFoil(_airfoil_ , _Re =0.0_, _mach =0.0_, _n_crit =9.0_, _xtr_upper =1.0_, _xtr_lower =1.0_, _hinge_point_x =0.75_, _full_potential =False_, _max_iter =100_, _xfoil_command ='xfoil'_, _xfoil_repanel =True_, _xfoil_repanel_n_points =279_, _include_bl_data =False_, _verbose =False_, _timeout =30_, _working_directory =None_) ``` -------------------------------- ### Airfoil Normalization and Drawing Example Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/geometry/airfoil/airfoil_families.html Demonstrates normalizing an airfoil and drawing it using the Plotly backend. This is a basic usage example for the Airfoil class. ```python import aerosandbox as asb import aerosandbox.numpy as np af = asb.Airfoil("e377").normalize() af.draw(backend="plotly") ``` -------------------------------- ### Example Function for Timing Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/tools/code_benchmarking/index.html A simple placeholder function 'f' used in examples to demonstrate timing mechanisms. It takes no arguments and its execution time can be measured. ```python aerosandbox.tools.code_benchmarking.f() ``` -------------------------------- ### Basic Optimization Setup and Solve in AeroSandbox Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/optimization/opti.html Sets up a simple optimization problem with parameters, variables, an objective function, and a constraint, then solves it. Asserts the solution against expected values. ```python import pytest # pytest.main() opti = Opti() # set up an optimization environment a = opti.parameter(1) b = opti.parameter(100) # Define optimization variables x = opti.variable(init_guess=0) y = opti.variable(init_guess=0) # Define objective f = (a - x) ** 2 + b * (y - x**2) ** 2 opti.minimize(f) opti.subject_to([x**2 + y**2 <= 1]) # Optimize sol = opti.solve() assert sol([x, y]) == pytest.approx([0.7864, 0.6177], abs=1e-3) ``` -------------------------------- ### Example Usage: Propeller and Gearbox Mass Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/library/propulsion_propeller.html Demonstrates the usage of the `mass_hpa_propeller` and `mass_gearbox` functions with example parameters. Includes setting up a matplotlib style for plotting. ```python if __name__ == "__main__": import matplotlib.style as style style.use("seaborn") # Daedalus propeller print( mass_hpa_propeller( diameter=3.4442, max_power=177.93 * 8.2, # max thrust at cruise speed include_variable_pitch_mechanism=False, ) ) # Should weight ca. 800 grams print(mass_gearbox(power=3000, rpm_in=6000, rpm_out=600)) ``` -------------------------------- ### Opti Parameter Initialization Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/optimization/index.rst.txt Demonstrates how to initialize scalar and vector parameters using the `opti.parameter()` method. ```APIDOC ## Opti Parameter Initialization ### Description Initializes a parameter, which can be either scalar or a vector. ### Method `opti.parameter(value, n_params=None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **value** (float or np.ndarray) - The initial value for the parameter. If a float, it's used for scalar parameters or repeated for all elements of a vector parameter. If a NumPy array, each element is used for the corresponding parameter element. - **n_params** (int, Optional) - Manually overrides the dimensionality of the parameter. Useful for creating vector parameters initialized to a scalar value. ### Request Example ```python import aerosandbox as asb import numpy as np opti = asb.Opti() # Scalar parameter scalar_param = opti.parameter(value=5) # Vector parameter initialized to a scalar value vector_param_scalar = opti.parameter(value=5, n_params=10) # Vector parameter initialized from a NumPy array vector_param_array = opti.parameter(value=np.linspace(0, 5, 10)) ``` ### Response #### Success Response (200) - **parameter** (CasADi MX type) - The created symbolic parameter. #### Response Example None (This is a method call, not an API endpoint returning JSON) ``` -------------------------------- ### Example Propulsor Instantiation Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/geometry/propulsor.html Demonstrates creating instances of the Propulsor class for a disk-shaped propulsor and a cylinder-shaped propulsor. ```python if __name__ == "__main__": p_disk = Propulsor(radius=3) p_can = Propulsor(length=1) ``` -------------------------------- ### Example Usage of Normal Shock Relations Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/library/aerodynamics/normal_shock_relations.html Demonstrates the usage of normal shock relations by calculating a 'q_ratio' for a given Mach number. This is an example of how the functions can be combined. ```python if __name__ == "__main__": def q_ratio(mach): return ( density_ratio_across_normal_shock(mach) * ( mach_number_after_normal_shock(mach) * temperature_ratio_across_normal_shock(mach) ** 0.5 ) ** 2 ) q_ratio(2) ``` -------------------------------- ### VortexLatticeMethod Usage Example Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/aerodynamics/aero_3D/vortex_lattice_method.html Example of how to instantiate and run the VortexLatticeMethod analysis. This involves creating an airplane object, defining an operating point, and then calling the run and draw methods. ```python analysis = asb.VortexLatticeMethod( airplane=my_airplane, op_point=asb.OperatingPoint( velocity=100, # m/s alpha=5, # deg beta=4, # deg p=0.01, # rad/sec q=0.02, # rad/sec r=0.03, # rad/sec ) ) aero_data = analysis.run() analysis.draw() ``` -------------------------------- ### Initialize Optimization Environment Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/optimization/opti.html Initializes an optimization environment. This is the first step in setting up any optimization problem. ```python opti = asb.Opti() # Initializes an optimization environment ``` -------------------------------- ### Example Usage: Transverse Gust Pitch Control Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/library/gust_pitch_control.html Sets the number of discrete spatial points for an example simulation. This is typically used to define the resolution for time-stepping in gust analysis. ```python if __name__ == "__main__": [docs] N = 100 # Number of discrete spatial points ``` -------------------------------- ### Set up Atmospheric Conditions and Operating Point Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/library/propulsion_turbofan.html Initializes an Atmosphere object for a specific altitude and creates an OperatingPoint with a given velocity relative to the speed of sound. ```python import aerosandbox as asb atmo = asb.Atmosphere(altitude=10668) op_point = asb.OperatingPoint(atmo, velocity=0.80 * atmo.speed_of_sound()) ``` -------------------------------- ### Initialize Optimization Environment Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/index.rst.txt Initializes an optimization environment using the Opti class. This is the starting point for defining optimization problems. ```python opti = asb.Opti() ``` -------------------------------- ### Check XFoil Installation and PATH Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/aerodynamics/aero_2D/mses.html This section explains how to verify if XFoil is installed and accessible via the system's PATH. If not found, the user is instructed to specify the executable's location. ```bash xfoil ``` -------------------------------- ### Initialize and Run XFoil Analysis Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/index.html Instantiate the XFoil class with an airfoil and Reynolds number, then perform analyses at specific angles of attack or lift coefficients. Ensure XFoil is installed and accessible via the system PATH or by specifying the xfoil_command. ```python >>> xf = XFoil( >>> airfoil=Airfoil("naca2412").repanel(n_points_per_side=100), >>> Re=1e6, >>> ) >>> >>> result_at_single_alpha = xf.alpha(5) >>> result_at_several_CLs = xf.cl([0.5, 0.7, 0.8, 0.9]) >>> result_at_multiple_alphas = xf.alpha([3, 5, 60]) ``` -------------------------------- ### Install XVFB on Linux Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/aerodynamics/aero_2D/mses.html Command to install the XVFB (X virtual framebuffer) package on a Debian-based Linux system. XVFB is used to run MSES without opening X11 windows. ```bash sudo apt-get install xvfb ``` -------------------------------- ### Example Usage of plot_color_by_value Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/tools/pretty_plots/plots/plot_color_by_value.html Demonstrates how to use the `plot_color_by_value` function with sample data, including setting a color limit and adding a colorbar with a label. This example requires `matplotlib.pyplot` and `aerosandbox.tools.pretty_plots` to be imported. ```python if __name__ == "__main__": import matplotlib.pyplot as plt import aerosandbox.tools.pretty_plots as p fig, ax = plt.subplots() [docs] x = np.linspace(-1, 1, 500) y = np.sin(10 * x) c = np.sin((10 * x) ** 2) plot_color_by_value( x, y, c=c, clim=(-1, 1), colorbar=True, colorbar_label="Colorbar Label" ) p.show_plot( "Title", "X Axis", "Y Axis", ) ``` -------------------------------- ### Set Initial Values from Solution Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/optimization/opti.html Initializes primals and/or duals of an Opti instance using values from another Opti solution. Assumes both Opti instances represent the same problem. ```python def set_initial_from_sol( self, sol: cas.OptiSol, initialize_primals=True, initialize_duals=True, ) -> None: """ Sets the initial value of all variables in the Opti object to the solution of another Opti instance. Useful for warm-starting an Opti instance based on the result of another instance. Args: sol: Takes in the solution object. Assumes that sol corresponds to exactly the same optimization problem as this Opti instance, perhaps with different parameter values. Returns: None (in-place) """ if initialize_primals: self.set_initial(self.x, sol.value(self.x)) if initialize_duals: self.set_initial(self.lam_g, sol.value(self.lam_g)) ``` -------------------------------- ### Initialize and Solve Optimization Problem Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/optimization/opti.html Demonstrates the basic workflow of initializing an Opti object, defining a variable and objective, and solving the problem. The solution object `sol` is then used to retrieve variable values. ```python >>> # Initialize an Opti object. >>> opti = asb.Opti() >>> >>> # Define a scalar variable. >>> x = opti.variable(init_guess=2.0) >>> >>> # Define an objective function. >>> opti.minimize(x ** 2) >>> >>> # Solve the optimization problem. `sol` is now a >>> sol = opti.solve() >>> >>> # Retrieve the value of the variable x in the solution: >>> x_value = sol(x) >>> >>> # Or, to be more concise: >>> x_value = sol(x) ``` -------------------------------- ### _DynamicsRigidBodyBaseClass.beta Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/dynamics/rigid_body/common_rigid_body/index.html Gets the sideslip angle. ```APIDOC ## _DynamicsRigidBodyBaseClass.beta ### Description The sideslip angle, in degrees. ### Method GET ### Endpoint N/A (Property of a class) ### Parameters None ### Response #### Success Response (200) - **beta** (float) - The sideslip angle in degrees. ``` -------------------------------- ### _DynamicsRigidBodyBaseClass.alpha Source: https://aerosandbox.readthedocs.io/en/master/autoapi/aerosandbox/dynamics/rigid_body/common_rigid_body/index.html Gets the angle of attack. ```APIDOC ## _DynamicsRigidBodyBaseClass.alpha ### Description The angle of attack, in degrees. ### Method GET ### Endpoint N/A (Property of a class) ### Parameters None ### Response #### Success Response (200) - **alpha** (float) - The angle of attack in degrees. ``` -------------------------------- ### Setting Initial Values from a Solution Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/index.rst.txt Initializes all variables in the current Opti instance using the solution from another Opti instance. This is useful for warm-starting optimization problems. ```python >>> sol = opti.solve() >>> opti.set_initial_from_sol(sol) ``` -------------------------------- ### Instantiate and Evaluate FittedModel Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/modeling/index.rst.txt Demonstrates how to instantiate a FittedModel with data and parameters, and then evaluate it like a function. The input type for evaluation can be determined by printing the model. ```python >>> my_fitted_model = FittedModel(...) >>> y = my_fitted_model(x) ``` ```python >>> print(my_fitted_model) ``` -------------------------------- ### beta Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Gets the sideslip angle. ```APIDOC ## GET /dynamics/beta ### Description Gets the sideslip angle, in degrees. ### Method GET ### Endpoint /dynamics/beta ### Parameters None ### Request Example None ### Response #### Success Response (200) - **beta** (float) - The sideslip angle in degrees. #### Response Example { "beta": 0.0 } ``` -------------------------------- ### alpha Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Gets the angle of attack. ```APIDOC ## GET /dynamics/alpha ### Description Gets the angle of attack, in degrees. ### Method GET ### Endpoint /dynamics/alpha ### Parameters None ### Request Example None ### Response #### Success Response (200) - **alpha** (float) - The angle of attack in degrees. #### Response Example { "alpha": 5.0 } ``` -------------------------------- ### speed Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/index.rst.txt Gets the speed of the object. ```APIDOC ## GET /dynamics/speed ### Description Gets the speed of the object, expressed as a scalar. ### Method GET ### Endpoint /dynamics/speed ### Parameters None ### Request Example None ### Response #### Success Response (200) - **speed** (float) - The speed of the object. #### Response Example { "speed": 100.0 } ``` -------------------------------- ### Control Variable Initialization Example Source: https://aerosandbox.readthedocs.io/en/master/_sources/autoapi/aerosandbox/dynamics/point_mass/index.rst.txt Shows the default initialization values for control variables (forces). ```python Fx_e :value: 0 Fy_e :value: 0 Fz_e :value: 0 ``` -------------------------------- ### Initialize Optimization Environment Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/modeling/fitting.html Initializes an optimization environment using the Opti class. This is a prerequisite for setting up and solving optimization problems. ```python opti = Opti() ``` -------------------------------- ### Setup Beam Problem and Discretization Source: https://aerosandbox.readthedocs.io/en/master/_modules/aerosandbox/structures/legacy/beams.html Initializes the beam problem by discretizing the geometry and assigning loads. This function must be run last before optimization. ```python def setup(self, bending_BC_type="cantilevered"): """ Sets up the problem. Run this last. :return: None (in-place) """ ### Discretize and assign loads # Discretize point_load_locations = [load["location"] for load in self.point_loads] point_load_locations.insert(0, 0) point_load_locations.append(self.length) self.x = cas.vertcat( *[ cas.linspace( point_load_locations[i], point_load_locations[i + 1], self.points_per_point_load, ) for i in range(len(point_load_locations) - 1) ] ) # Post-process the discretization self.n = self.x.shape[0] dx = cas.diff(self.x) # Add point forces self.point_forces = cas.GenMX_zeros(self.n - 1) for i in range(len(self.point_loads)): load = self.point_loads[i] self.point_forces[self.points_per_point_load * (i + 1) - 1] = load["force"] # Add distributed loads self.force_per_unit_length = cas.GenMX_zeros(self.n) self.moment_per_unit_length = cas.GenMX_zeros(self.n) for load in self.distributed_loads: if load["type"] == "uniform": self.force_per_unit_length += load["force"] / self.length elif load["type"] == "elliptical": load_to_add = ( load["force"] / self.length * (4 / cas.pi * cas.sqrt(1 - (self.x / self.length) ** 2)) ) self.force_per_unit_length += load_to_add else: raise ValueError( 'Bad value of "type" for a load within beam.distributed_loads!' ) # Initialize optimization variables log_nominal_diameter = self.opti.variable(self.n) self.opti.set_initial(log_nominal_diameter, cas.log(self.diameter_guess)) self.nominal_diameter = cas.exp(log_nominal_diameter) self.opti.subject_to([log_nominal_diameter > cas.log(self.thickness)]) def trapz(x): out = (x[:-1] + x[1:]) / 2 # out[0] += x[0] / 2 # out[-1] += x[-1] / 2 return out # Mass self.volume = cas.sum1( cas.pi / 4 * trapz( (self.nominal_diameter + self.thickness) ** 2 - (self.nominal_diameter - self.thickness) ** 2 ) * dx ) self.mass = self.volume * self.density # Mass proxy self.volume_proxy = cas.sum1( cas.pi * trapz(self.nominal_diameter) * dx * self.thickness ) self.mass_proxy = self.volume_proxy * self.density # Find moments of inertia self.I = ( cas.pi / 64 * ( # bending (self.nominal_diameter + self.thickness) ** 4 - (self.nominal_diameter - self.thickness) ** 4 ) ) self.J = ( cas.pi / 32 * ( # torsion (self.nominal_diameter + self.thickness) ** 4 - (self.nominal_diameter - self.thickness) ** 4 ) ) if self.bending: # Set up derivatives self.u = 1 * self.opti.variable(self.n) self.du = 0.1 * self.opti.variable(self.n) self.ddu = 0.01 * self.opti.variable(self.n) self.dEIddu = 1 * self.opti.variable(self.n) self.opti.set_initial(self.u, 0) self.opti.set_initial(self.du, 0) self.opti.set_initial(self.ddu, 0) ```