API Documentation

Crossover

class gastop.crossover.Crossover(crossover_params)[source]

Mixes attributes belonging to two different parents to produce two children with specific characteristics from both parents.

When creating a new Crossover() object, it must be initialized with dictionary crossover_params (containing crossover method). The Crossover() object can then be used as a function that produces children according to the specified crossover method, such as uniform_crossover, single_point_split or two_points_split.

__call__(truss_1, truss_2)[source]

Calls a crossover object on two trusses to combine them.

Crossover object must have been instantiated specifying which methods to use.

Parameters:
  • truss_1 (Truss object) – First truss to be combined.
  • truss_2 (Truss object) – Second truss to be combined.
Returns:

child_1, child_2 (Truss objects) – Children trusses produced by crossover.

__init__(crossover_params)[source]

Creates a Crossover object.

Once instantiated, the Crossover object can be called as a function to combine two trusses using the specified methods and parameters.

Parameters:crossover_params (dict) –

Dictionary containing:

  • 'node_crossover_method' (str): Name of method to use for node crossover.
  • 'edge_crossover_method' (str): Name of method to use for edge crossover.
  • 'property_crossover_method' (str): Name of method to use for property crossover.
  • 'user_spec_nodes' (ndarray): Array of user specified nodes that should be passed on unaltered.
Returns:Crossover callable object.
static single_point_split(array_1, array_2)[source]

Performs a single point split crossover between two parents

The single split crossover method takes specific information from two parents and returns two children containing characteristics from both parents. In order to achieve this, it chooses a random point and splits the two parents into two different parts. Then it merges the first half of the first parent with the second half of the second parent and vice versa.

Parameters:
  • array_1 (ndarray) – Numpy array containing information for parent 1.
  • array_2 (ndarray) – Numpy array containing information for parent 2.
Returns:

child1, child2 (ndarrays) – Numpy arrays containing information for children.

static two_points_split(array_1, array_2)[source]

Takes specific values of two parents and return two children containing characteristics from both parents.

The two points split method chooses two random points and splits the two parents into three different parts. Then, it replaces the central part of the first parent with the central part of the second parent.

Parameters:
  • array_1 (ndarray) – Numpy array containing information for parent 1.
  • array_2 (ndarray) – Numpy array containing information for parent 2.
Returns:

child_1, child_2 (ndarrays) – Numpy arrays containing information for children.

static uniform_crossover(parent_1, parent_2)[source]

Performs a uniform crossover on the two parents

The uniform crossover method creates two child arrays by randomly mixing together information taken from two parent arrays. To do this, the uniform crossover method creates two arrays of ones and zeros -one being the complement of the other- with the same shape as the parent arrays. The first array is multiplied with parent1 and the complementary array is multiplied with parent2 before adding the results together to make child1. The exact opposite multiplication is done to make child2.

Parameters:
  • parent_1 (ndarray) – Numpy array containing information for parent 1.
  • parent_2 (ndarray) – Numpy array containing information for parent 2.
Returns:

child1, child2 (ndarrays) – Numpy arrays containing information for children.

Evaluator

class gastop.evaluator.Evaluator(struct_solver, mass_solver, interferences_solver, cost_solver, boundary_conditions, properties_dict)[source]

Implements various methods for scoring the truss in different areas.

Methods include calculations of mass, factor of safety, deflections, and interference with user specified areas.

The class is designed to be instantiated as an Evaluator object which will fully evaluate a Truss object using specified methods and parameters.

__call__(truss)[source]

Computes mass, deflections, etc, and stores it in truss object.

Used when an Evaluator object has been created with the methods to be used and any necessary parameters.

Parameters:truss (Truss object) – truss to be evaluated.
Returns:None
__init__(struct_solver, mass_solver, interferences_solver, cost_solver, boundary_conditions, properties_dict)[source]

Creates an Evaluator callable object.

Once created, the Evaluator can be called on a Truss object to calculate and assign mass, factor of safety, deflections, etc to the truss.

Parameters:
  • struct_solver (str) – Name of the method to be used for structural analysis and calculating fos and deflections, as a string. e.g. 'mat_struct_analysis_DSM'.
  • mass_solver (str) – Name of the method to be used to calculate mass. e.g. 'mass_basic'.
  • interferences_solver (str) – Name of method to be used to determine interferences. e.g. 'interferences_ray_tracing'.
  • boundary_conditions (dict) –

    Dictionary containing:

    • 'loads' (ndarray): Array of loads applied to the structure. First index corresponds to the node where the load is applied, second index is the force in x,y,z and moment about x,y,z, third index is for multiple loading scenarios.
    • 'fixtures' (ndarray): Array of flags denoting whether a node is fixed or free. First index corresponds to the node, the second index corresponds to fixing displacements in x,y,z and rotations about x,y,z. The third index corresponds to multiple loading scenarios with different fixtures for each. Values of the array are 0 (free) or 1 (fixed).
  • properties_dict (dict) – Dictionary containing beam properties.
  • should be 1D arrays, with length equal to the number of (Entries) –
  • options. Each entry in the array is the value of the key (beam) –
  • for the specified beam type. Properties include (property) –
    • 'OD': Outer diameter of the beam, in meters.
    • 'ID': Inner diameter of the beam, in meters.
    • 'elastic_modulus': Elastic or Young’s modulus of the material, in Pascals.
    • 'yield_strength': Yield or failure strength of the material, in Pascals.
    • 'shear_modulus': Shear modulus of the material, in Pascals.
    • 'poisson_ratio': Poisson ratio of the material, dimensionless.
    • 'x_section_area': Cross sectional area of the beam, in square meters.
    • 'moment_inertia_y': Area moment of inertia about beams y axis, in meters^4.
    • 'moment_inertia_z': Area moment of inertia about beams z axis, in meters^4.
    • 'polar_moment_inertia': Area moment of inertia about beams polar axis, in meters^4.
    • 'dens': Density of the material, in kilograms per cubic meter.
  • cost_solver (str) – Name of the method to be used to calculate cost. e.g. 'cost_calc'.
Returns:

callable Evaluator object.

static blank_test(truss, *args, **kwargs)[source]

Blank function used for testing GA when no evaluation needed

Parameters:truss (Truss object) – Dummy Truss object, no attributes required.
Returns:2-element tuple of (None, None)
static cost_calc(truss, properties_dict)[source]

Calculates cost of structure

Considers only members, does not account for additional cost due to welds or connection hardware.

Parameters:truss – Truss to be evaluated. Must have nodes, edges, and properties defined.
Returns:cost (float) – Cost of the structure in $.
static interference_ray_tracing(truss)[source]

Not implemented yet.

TODO: method to determine if truss members are crossing into user specified areas. Used when a structure must be designed around something, such as a passenger compartment or other design components.

static mass_basic(truss, properties_dict)[source]

Calculates mass of structure

Considers only members, does not account for additional mass due to welds or connection hardware.

Parameters:truss – Truss to be evaluated. Must have nodes, edges, and properties defined.
Returns:mass (float) – Mass of the structure in kilograms.
static mat_struct_analysis_DSM(truss, boundary_conditions, properties_dict)[source]

Calculates deflections and stresses using direct stiffness method.

Constructs global stiffness matrix from nodes and connections, and computes deflections under each loading scenario. From deflections, calculates internal forces, stresses, and factor of safety in each member under each loading scenario

Parameters:
  • truss (Truss object) – Truss to be evaluated. Must have nodes, edges, and properties defined.
  • boundary_conditions (dict) –

    Dictionary containing:

    • 'loads' (ndarray): Array of loads applied to the structure. First index corresponds to the node where the load is applied, second index is the force in x,y,z and moment about x,y,z, third index is for multiple loading scenarios.
    • 'fixtures' (ndarray): Array of flags denoting whether a node is fixed or free. First index corresponds to the node, the second index corresponds to fixing displacements in x,y,z and rotations about x,y,z. The third index corresponds to multiple loading scenarios with different fixtures for each. Values of the array are 0 (free) or 1 (fixed).
  • properties_dict (dict) – Dictionary containing beam properties.
  • should be 1D arrays, with length equal to the number of (Entries) –
  • options. Each entry in the array is the value of the key (beam) –
  • for the specified beam type. Properties include (property) –
    • 'OD': Outer diameter of the beam, in meters.
    • 'ID': Inner diameter of the beam, in meters.
    • 'elastic_modulus': Elastic or Young’s modulus of the material, in Pascals.
    • 'yield_strength': Yield or failure strength of the material, in Pascals.
    • 'shear_modulus': Shear modulus of the material, in Pascals.
    • 'poisson_ratio': Poisson ratio of the material, dimensionless.
    • 'x_section_area': Cross sectional area of the beam, in square meters.
    • 'moment_inertia_y': Area moment of inertia about beams y axis, in meters^4.
    • 'moment_inertia_z': Area moment of inertia about beams z axis, in meters^4.
    • 'polar_moment_inertia': Area moment of inertia about beams polar axis, in meters^4.
    • 'dens': Density of the material, in kilograms per cubic meter.
Returns:

2-element tuple containing

  • fos (ndarray): 2D array of factor of safety values. First index corresponds to members, second index corresponds to different loading scenarios. Factor of safety is defined as the materials yield strength divided by the von Mises stress in the member. If structure is statically indeterminate under a given loading scenario, fos will be zero.

    Factor of safety in member i under loading j is fos[i, j]

  • deflections (ndarray): 3D array of node deflections. Distances in meters, angles in radians. First index corresponds to node number, second index is deflections in global x,y,z coordinates, and rotations about global x,y,z axes. The third axis corresponds to different loading scenarios.

    Deflection at node i under loading j is deflections[i, :, j] = [dx, dy, dz, d_theta_x, d_theta_y, d_theta_z]

FitnessFunction

class gastop.fitness.FitnessFunction(equation, parameters)[source]

Implements fitness functions for computing fitness scores.

The fitness function assigns a single value to each truss based on various parameters, so that comparisons between trusses can be made.

The class is designed to be instantiated as a FitnessFunction object which operates on Truss objects to assign a fitness score, though methods from the class may also be called directly.

__call__(truss)[source]

Computes fitness score and stores it in truss object.

Used when a FitnessFunction object has been created with the method to be used and any necessary parameters.

Parameters:truss (Truss object) – truss to be scored.
Returns:None
__init__(equation, parameters)[source]

Creates a FitnessFunction object

Once created, the object acts like a function and can be called on a Truss object to assign it a fitness score.

Parameters:
  • equation (string) – The name of the method to be used to compute fitness, as a string. eg, 'weighted_sum' or 'rosenbrock'.
  • parameters (dict) – Dictionary of keyword parameter values for the method specified in equation.
Returns:

FitnessFunction callable object

static rastrigin(truss)[source]

n-dimensional Restrigin function.

Global min at x=0 where f=0. This method is primarily supplied for testing of the genetic algorithm, and should not be used for structural design.

Parameters:truss (Truss object) – only uses truss object as container for nodes. No other attributes needed.
Returns:float – fitness score. Computed as \(f(x) = 10n + \Sigma_{i=1}^n (x_i^2 -10\cos{(2 \pi x_i)})\)

\(n\) is determined from size of nodes array, \(x_i\) are entries of node array.

static rosenbrock(truss)[source]

n-dimensional Rosenbrock function.

Sum of n/2 2D Rosenbrock functions. Global min at x=1 where f=0. This method is primarily supplied for testing of the genetic algorithm, and should not be used for structural design.

Parameters:truss (Truss object) – only uses truss object as container for nodes. No other attributes needed.
Returns:float – Fitness score. Computed as \(f(x) = \Sigma_{i=1}^{n/2}(100*(x_{2i-1}^2 - x_{2i}^2)^2 + (x_{2i-1} - 1)^2)\)

\(n\) is determined from size of nodes array, \(x_i\) are entries of node array.

static sphere(truss)[source]

Sum of squares of node array elements. aka, sphere function.

Global min at x = 0 where f = 0. This method is primarily supplied for testing of the genetic algorithm, and should not be used for structural design.

Parameters:truss (Truss object) – only uses truss object as container for nodes. No other attributes needed.
Returns:float – Fitness score. Computed as \(f(x) = \Sigma_{i=1}^n x_i^2\)

\(n\) is determined from size of nodes array, \(x_i\) are entries of node array.

static weighted_sum(truss, goal_fos, critical_nodes, w_fos, w_mass, w_deflection)[source]

Computes fitness score using a weighted sum of parameters.

Parameters:
  • truss (Truss object) – truss to be scored. Must have mass, fos, and deflections attributes defined (for example, by using evaluator).
  • goal_fos (float >= 0) – Desired factor of safety. Trusses with a smaller fos will be penalized according to w_fos.
  • critical_nodes (int, array) – Array of nodes #s for which deflection should be minimized. If empty, defaults to all.
  • w_fos (float >= 0) – Penalty weight for low fos. Only applied if truss.fos < goal_fos.
  • w_mass (float >= 0) –

    Penalty applied to mass. Relative magnitude of w_mass and w_fos determines importance of

    minimizing mass vs maximizing fos.
  • w_deflection (float >=0, array) – Penalty applied to deflections. If scalar, applies the same penalty to all critical nodes. Can also be an array the same size as critical_nodes in which case different penalties will be applied to each node.
Returns:

float – Fitness score. Computed as: \(f = w_{m} m + w_{fos}\max{(\mathrm{fos}_{goal}-\mathrm{fos}_{min}, 0)} + w_{def} ||\mathrm{deflections}||_2\)

\(m\) is the mass of the stucture, \(\mathrm{fos}_{min}\) is the lowest fos for the structure under all load conditions. If \(\mathrm{fos}_{min} > \mathrm{fos}_{goal}\), no fos penalty is applied, so f depends only on mass and deflections.

GenAlg

class gastop.genalg.GenAlg(config)[source]

Creates, updates, tracks, loads, and saves populations.

The GenAlg Class orchestrates all of the other functions that perform functions to change the population and its elements. In this case, such classes are crossover, evaluator, encoders, fitness, mutator, selector, and truss.

In brief, GenAlg calls many other functions in order to create a generation which is then analyzed to fully determine its relavant properties. These properties are then used to create a new generation and the process repeats until a final solution is reached.

__init__(config)[source]

Creates a GenAlg object

Once created, the object will store all of the relavant information about a population. The object also contains the necessary functions to modify itself, evaluate its ‘goodness’, and then create new members for the next generation.

Parameters:
  • Either
  • config (str) – Configuration dictionary with parameters, such as one created by gastop.utilities.init_file_parser()
  • config – File path to config file to be parsed. Used instead of passing config dictionary directly.
Returns:

GenAlg callable object

generate_random()[source]

Generates and returns new truss objects with random properties

The random method first determines the desired ranges of all values that will be calculated. Then, random numbers for the node locations, connections, and properties are all determined with the numpy.random methods.

Parameters:None
Returns:(Truss object) – Truss object with the newly determined values
initialize_population(pop_size=None)[source]

Initializes population with randomly creates Truss objects.

Population is stored in instance of GenAlg object as population attribute.

Parameters:pop_size (int) – size of the population. If not specified, it defaults to what is in the config dict.
Returns:None
static load_state(dest_config='config.json', dest_pop='population.json')[source]

Loads the current population and config settings from JSON files.

Parameters:
  • dest_config (string) – Path to config data file.
  • dest_pop (string) – Path to population data file.
Returns:

ga (GenAlg object)

run(num_generations=None, progress_fitness=None, progress_truss=None, num_threads=None)[source]

Runs the genetic algorithm over all populations and generations

Parameters:
  • num_generations (int) – number of generations to be performed.
  • progress_fitness (bool) – Whether to show display window showing fitness score vs generation.
  • progress_truss (bool) – Whether to show display window showing truss evolution.
  • num_threads (int) – number of threads the multiprocessing should employ. If zero or None, it will use the number returned by os.cpu_count().
Returns:

2-element tuple containing

  • best (Truss): The Truss with the best fitness score after elapsed generations.

  • pop_progress (dict): Dictionary of dictionaries containing:

    • 'Generation 1' (dict): Dictionary of info about generation 1.
    • 'Generation 2' (dict): Dictionary of info about generation 2, etc.

save_state(dest_config='config.json', dest_pop='population.json')[source]

Saves the current population and config settings to JSON files.

Parameters:
  • dest_config (string) – Path to save config data file. If file doesn’t exist, creates it.
  • dest_pop (string) – Path to save population data file. If file doesn’t exist, creates it.
Returns:

None

update_population()[source]

Creates new population by performing crossover and mutation, as well as taking elites and randomly generating trusses.

First sorts the population by fitness score, from most fit to least fit. Creates selector object from population and method. Calls selector to get list of parents for crossover and mutation. Performs crossover and mutation.

Parameters:None
Returns:None

Mutator

class gastop.mutator.Mutator(mutator_params)[source]

Randomly mutates the whole/specific attributes belonging to the parents.

When creating a new Mutator() obejct, it must be initialized with dictionary mutator_params (containing mutation method). The Mutator() Object can then be used as a function that mutates parents according to the specified method, such as gaussian, pseudo_bit_flip and shuffle_index.

__call__(truss)[source]

Calls a mutator object on a truss to change it.

Mutator object must have been instantiated specifying which methods to use.

Parameters:truss (Truss object) – Truss to be mutated.
Returns:child (Truss object) – Child truss produced by mutation.
__init__(mutator_params)[source]

Creates a Mutator object.

Once instantiated, the Mutator object can be called as a function to alter the parent array using the specified methods and parameters

Parameters:mutator_params (dict) –

Dictionary containing:

  • 'node_mutator_method' (str): Name of method to use for node mutation.
  • 'edge_mutator_method' (str): Name of method to use for edge mutation.
  • 'property_mutator_method' (str): Name of method to use for property mutation.
  • 'node_mutator_params' (dict): Dictionary of parameters for node method.
  • 'edge_mutator_params' (dict): Dictionary of parameters for edge method.
  • 'property_mutator_params' (dict): Dictionary of parameters for property method.
  • 'user_spec_nodes' (ndarray): Array of user specified nodes that should be passed on unaltered.
Returns:Mutator callable object.
static gaussian(array, std, boundaries, int_flag)[source]

Performs a gaussian mutation on the given parent array

The gaussian mutator method creates a child array by mutating the given parent array. The mutation is done by adding a random value from the gaussian distribution with a user specified standard deviation to each of the elements in the parent array. Since values need to be within a specified boundary, any elements that are mutated out of bounds on one side are looped inside the other side by the same amount, assuming a periodic boundary.

Parameters:
  • array (ndarray) – Numpy array containing the information for the parent array that is being mutated.
  • std (float or array-like) – Standard deviation for mutation. If array-like, std[i] is used as the standard deviation for array[:,i].
  • boundaries (array-like) – Domain of allowable values. If a value is mutated outside this region, it is looped back around to the other side.
  • int_flag (bool) – flag specifying whether output should be ints.
Returns:

new_array (ndarray) – Numpy array containing information for the mutated child.

static pseudo_bit_flip(parent, boundaries, proportions, int_flag)[source]

Mutate specific values of the parent and return the mutant child.

The pseudo_bit_flip method creates a random binary matrix with a fixed ratio of 1s and 0s as specified by the user. It also creates another random matrix with elements within the domain specified by the user. It then replaces the elements from the original matrix with the corresponding elements in the new matrix only if the corresponding element in the binary matrix is 1.

Parameters:
  • parent (ndarray) – Numpy array containing the information for the parent array that is being mutated.
  • boundaries (array-like) – Domain of allowable values.
  • proportions (float) – Ratio of 1s and 0s in the binary matrix used in the pseudo bit flip algorithm
  • int_flat (bool) – flag specifying whether output should be ints.
Returns:

child (numpy array) – Numpy array containing information for the mutated child.

static shuffle_index(parent)[source]

Mutate the parent by swapping an index with another within the same array.

First, the shuffle_index method creates two random matrices. It then compares the two matrices. If the entry in the first matrix is greater than the entry in the second matrix, then it permutes the corresponding elements in the original matrix.

Parameters:parent (numpy array) – Numpy array containing the information for the parent array that is being mutated.
Returns:child (numpy array) – Numpy array containing information for the mutated child.

Progress Monitor

class gastop.progmon.ProgMon(progress_fitness, progress_truss, num_generations, domain=None, loads=None, fixtures=None)[source]

Plots fitness score or truss evolution and stores population statistics.

This class takes in the current sorted population and displays information based on the user requests. If truss monitoring is requested it calls the plot method. The population stats are returned via GenAlg and written to a json file, allowing the user to plot the evolution after the optimization is complete.

__init__(progress_fitness, progress_truss, num_generations, domain=None, loads=None, fixtures=None)[source]

Creates a ProgMon object

Once created, the object will store all of the relavant information about a progess monitor. The figures are also initialized upon object instatiation.

Parameters:
  • progress_fitness (boolean) – if true the minimum fitness score of the population is plotted each iteration
  • progress_truss (boolean) – if true the truss corresponding to the minimum fitness score is displayed each iteration
  • num_generations (integer) – indicates the number of generations, used when initializing the fitness figure
  • domain (numpy array) – indicates bounds of design area, used when progress_truss is true
  • loads (numpy array) – indicates magnitude and direction of loads applied to user_spec_nodes, used when progress_truss is true
  • fixtures (numpy array) – indicates fixed DOFs of user_spec_nodes, used when progress_truss is true
Returns:

Nothing

progress_monitor(current_gen, population)[source]

Updates progress monitor plots

Function is passed the sorted population and plots either the current generation’s best fitness score, best truss, or both. If the truss is displayed, the plot method of the truss object is called but passed the figure instantiated in the init method.

Parameters:
  • progress_fitness (boolean) – if true the minimum fitness score of the population is plotted each iteration
  • progress_truss (boolean) – if true the truss corresponding to the minimum fitness score is displayed each iteration
  • num_generations (integer) – indicates the number of generations, used when initializing the progress_fitness figure
  • domain (numpy array) – indicates bounds of design area, used when progress_truss is true
  • loads (numpy array) – indicates magnitude and direction of loads applied to user_spec_nodes, used when progress_truss is true
  • fixtures (numpy array) – indicates fixed DOFs of user_spec_nodes, used when progress_truss is true
Returns:

Nothing

Selector

class gastop.selector.Selector(sel_params)[source]

Selects parents to be used for crossover and mutation.

When creating a new Selector() obejct, must be initialized with dictionary sel_params (containing selection method). Object can then be used as a function that selects parents according to the specified method.

__call__(num_parents, population)[source]

Calls selector object on a population to get parent indices.

Parameters:
  • num_parents (int) – Number of parents to select.
  • population (list) – Population of trusses to select from, must be sorted by fitness score in ascending order.
Returns:

parents (ndarray) – Array of indices of parents in population list.

__init__(sel_params)[source]

Creates a Selector object.

Parameters:sel_params (dict) –

Dictionary containing:

  • 'method' (str): Name of chosen selection method.
  • 'method_params' (dict): Dictionary of parameters required by chosen method.
Returns:selector (Selector object)
static inverse_square_rank_probability(num_parents, population)[source]

Selects parents according to inverse square rank method.

Creates a cdf, with each entry the cumulative sum of 1/sqrt(N) for N = 1, … Random values are then produced between the largest and smallest elements of the list. Each parent is chosen as the index in the cdf that the corresponding random value falls. In this way, the most probable parents are those with the highest fitness scores.

Parameters:
  • num_parents (int) – The number of parents to select.
  • population (list) – List of Truss objects that constitutes the current generation.
Returns:

parents (ndarray) – Numpy array of indices in population corresponding to selected parents.

static tournament(num_parents, population, tourn_size, tourn_prob)[source]

Selects parents according to tournament method.

Randomly selects truss indices from population in groups called tournaments according to “tourn_size.” Each tournament is then sorted by index (lower means more fit) in ascending order and a single index from each tournament is selected. The selection from each tournament is chosen probabilistically, assigning the first, most fit, index with probability p = tourn_prob, and then subsequent indices by p*(1-p)^n. The winners of each tournament are then returned as the parents array.

Parameters:
  • num_parents (int) – The number of parents to select.
  • population (list) – List of Truss objects that constitutes the current generation.
  • tourn_size (int) – Number of trusses to include in a given tournament. Must be <= 31.
  • tourn_prob (float) – Probability of selecting first index in each tournament. Must be between 0 and 1.
Returns:

parents (ndarray) – Numpy array of indices in population corresponding to selected parents.

Truss

class gastop.truss.Truss(user_spec_nodes, rand_nodes, edges, properties, fos=None, deflection=None, mass=None, interference=None, cost=None, num_joints=None, fitness_score=None)[source]

Implements the Truss object, which is the fundamental object/data type in GASTOp.

Each truss is defined by a collection of nodes (points in x,y,z space), edges (connections between nodes), and properties (material and geometric properties of the connections between nodes).

A truss can also have assigned attributes such as factor of safety, deflections, mass, cost, or fitness score. These attributes are calculated based on the nodes, edges, and properties.

__init__(user_spec_nodes, rand_nodes, edges, properties, fos=None, deflection=None, mass=None, interference=None, cost=None, num_joints=None, fitness_score=None)[source]

Creates a Truss object

Parameters:
  • user_spec_nodes (ndarray) – Array of user specified nodes, such as where loads are applied or where the structure is supported. Array shape should be nx3, where n is the number of specified nodes. Each row should contain the x,y,z coordinates of a node.
  • rand_nodes (ndarray) – Randomly generated nodes. No loads or supports should be assigned to random nodes, as their position may change. Array shape should be mx3 where m is the number of random nodes. Each row should contain the x,y,z coordinates of a node.
  • edges (ndarray) – Array of connections between nodes. Array shape should be kx2, where k is the number of connections or beams in the structure. Each row should be 2 integers, the first being number of the starting node and the second being the ending node. A value of -1 indicates no connection, and will be ignored.
  • properties (ndarray) – Array of indices for beam properties. Array shape should be a 1d array of length k, where k is the number of connections or beams in the structure. Each entry should be an integer index into the properties dictionary, with values between [0, number of beam types].
  • fos (ndarray) – Array of factor of safety values. Default None.
  • deflection (ndarray) – Array of node deflections under load, in meters. Default None.
  • mass (float) – Mass of the structure, in kilograms. Default None.
  • interference (float) – Total length of members passing through user specified areas. Default None.
  • cost (float) – Cost of the structure in dollars. Default None.
  • num_joints (int) – Number of connections between members. Default None.
  • fitness_score (float) – Fitness score of the truss. Default None.
Returns:

Truss object.

__str__()[source]

Prints the truss to the terminal as a formatted array.

Prints node numbers and locations, edge numbers and connections, and beam material property ID’s

If deflections, mass, fos, or cost are defined, they will be printed as well.

Parameters:None
Returns:None
cleaned_params()[source]

Returns cleaned copies of node, edge, and property arrays.

Parameters:None
Returns:3-element tuple containing
  • nodes (ndarray): Concatenation of user_spec_nodes and rand_nodes.
  • edges (ndarray): Edges array after removing rows with -1 values.
  • properties (ndarray): Properties corresponding to remaining edges.
mark_duplicates()[source]

Checks truss for duplicate edges or self connected nodes and marks them.

Any edge that connects a node to itself, or any duplicate edges are changed to -1.

Parameters:None
Returns:None
plot(domain=None, loads=None, fixtures=None, deflection=False, load_scale=None, def_scale=100, ax=None, fig=None, setup_only=False)[source]

Plots a truss object as a 3D wireframe

Parameters:
  • self (Truss object) – truss to be plotted. Must have user_spec_nodes, rand_nodes, edges defined.
  • domain (ndarray) – (optional) axis limits in x,y,z, specified as a 3x2 array: [[xmin, xmax],[ymin,ymax],[zmin,zmax]].
  • loads (ndarray) – (optional) Array of loads to be plotted as arrows. Specified as nx6 array, each row corresponding to the load at the node matching the row #. Load format: [Fx,Fy,Fz,Mx,My,Mz]
  • fixtures (ndarray) – (optional) Array of fixtures to be plotted as blobs. Specified as an nx6 array, each row corresponding to fixtures at the node matching the row #. Format: [Dx,Dy,Dz,Rx,Ry,Rz] value of 1 means fixed in that direction, value of zero is free.
  • deflection (bool) – If True, deflections will be plotted superposed on the undeformed structure. Relative size of deflections is governed by def_scale.
  • load_scale (float) – Size load vector arrows should be scaled by.
  • def_scale (float) – Scaling for deflections. *def_scale*=1 means actual size, larger than 1 magnifies.
  • ax (axis) – Axis to plot truss on, if an axis is passed to the function, the function is being called by ProgMon and prog is set to 1. If axis is none, a new one is created.
  • fig (fig) – Figure belonging to the axis.
  • setup_only (boolean) – If true, only the loads and fixtures are plotted.
Returns:

None

encoders

class gastop.encoders.ConfigEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Encodes config file in JSON format.

If the object is a numpy array, converts it to a list and appends ‘__numpy__’ metadata for decoding.

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
class gastop.encoders.PopulationEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Encodes population file in JSON format.

If the object is a numpy array, converts it to a list and appends ‘__numpy__’ metadata for decoding. Handles that population is composed of truss objects.

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
gastop.encoders.numpy_decoder(dct)[source]

Decodes JSON files to config and population.

If the object is has ‘__numpy__’ metadata, converts it to a numpy array.

Parameters:dct (dict) – Dictionary in JSON file.
Returns:dct (dict) – Dictionary with numpy arrays decoded.

utilities

gastop.utilities.beam_file_parser(properties_path)[source]

Parses csv file of beam material properties

Each line of the properties file denotes one type of beam, with a specified cross section and material properties.

Property entries should be formatted as: beam #, material name, OD (m), ID (m), elastic_modulus (Pa), yield_strength (Pa), density (kg/m^3), poisson_ratio, cost ($)

Parameters:properties_path (str) – Path to the properties csv file, relative to the directory GASTOp is being executed from.
Returns:properties_dict (dict) – Dictionary of property values. Each entry is an ndarray of the keyed property of each beam. For example, properties_dict[‘dens’] is an ndarray of the density of each beam type.
gastop.utilities.init_file_parser(init_file_path)[source]

Parse init file for input parameters.

Creates ConfigObj object, which reads input parameters as a nested dictionary of strings. The string are then converted to their correct types using the ConfigObj walk method and a transform function. Defaults are then set with if statements.

Parameters:init_file_path (string) – Path to the init file, relative to the directory GASTOp is being executed from.
Returns:config (ConfigObj object) – Nested dicitonary of input parameters.
gastop.utilities.load_progress_history(path_progress_history='progress_history.json')[source]

Loads the population history (progress_history) from a JSON file.

Parameters:path_progress_history (string) – Path to progress_history data file.
Returns:progress_history (dict) – History of each generation, including generation number, fittest truss, etc.
gastop.utilities.save_gif(progress_history, progress_fitness, progress_truss, animation_path, num_gens, config, gif_pause=0.5)[source]

Saves progress history to gif

Clears contents of folder specified then creates png of each generation of the evolution and then combines the png’s into a gif. Accomplishes this by creating progress monitor instance and passing it the truss object stored in the progress history.

Parameters:
  • progress_history (dictionary of dictionaries) – population statistics and best truss from each generation.
  • progress_fitness (boolean) – indicates whether to plot the fitness score.
  • progress_truss (boolean) – indicates whether to plot the current truss.
  • animation_path (string) – path to the file where the gif should be created.
  • num_gens (integer) – total number of generations
  • config (dictionary of dictionaries) – stores domain, loads, and fixtures
  • gif_pause (float) – pause between images in the gif
Returns:

Nothing

gastop.utilities.save_progress_history(progress_history, path_progress_history='progress_history.json')[source]

Saves the population history (progress_history) to a JSON file.

Parameters:
  • progress_history (dict) – History of each generation, including generation number, fittest truss, etc.
  • path_progress_history (string) – Path to save progress_history data file. If file doesn’t exist, creates it.
Returns:

None