bom_analysis package¶
- bom_analysis.update_config(new_config: Type[BaseConfig])¶
Updates the configuration within the Framework class.
Using the framework in this way allows a new configuration to be supplied to the bom_analysis classes as they take the Configuration from the Framework instead of the BaseConfig.
- Parameters
new_config (BaseConfig) – A configuration class that will be used by bom_analysis.
bom_analysis.base submodule¶
- class bom_analysis.base.BaseClass¶
Bases:
objectA key feature of the Bill of Materials analysis is that objects can be written and read from a serialisable dictionary. The dictionary of the bill of materials is known as the Skeleton and a read and write to skeleton feature is included in the parent BaseClass of all bill of material objects.
The skeleton is key for transfering information. It can either be built by parsing together a set of dictionaries and then read to create a bill of materials or written as an output of a pre-assembled Bill of Materials.
The skeleton offers a number of benefits, it is generally the primary output of analysis ran on the bill of materials, therefore, recording the state of the inputs for that analysis (this can be particularly important for transfering data in between Model Based System Engieering workflows).
- from_dict(data: dict)¶
Reads and populates from json.
- Parameters
data (dict) – Loaded json.
- to_dict(exclusions: list = []) dict¶
Exports the data of the base class as a dictionary for use in a skeleton of the BOM.
- Parameters
exclusions (list, optional) – A list of attribute strings to be excluded from the dump to dictionary.
- Returns
A dictionary containing the base class data.
- Return type
dict
- class bom_analysis.base.BaseConfig¶
Bases:
BaseConfigMethodsHaving a configuration that can be shared across all analysis ran on the bill of materials is key to running complex workflows. The configuration could include features of the Bill of Materials such as being able to dynamically add new parameters or information for analysis tools such as working directory or login details.
Bill of Materials Analysis features such a class that can be imported without initialisation and with data shared using it.
- class bom_analysis.base.BaseConfigMethods¶
Bases:
objectBaseConfigMethods contains methods that will be used by a configuration class.
- _login_details¶
Login details that could be supplied by the config.
- Type
dict
- _materials¶
The class for selecting a material library from a string.
- Type
- _translations¶
The list of translation file locations.
- Type
list
- _default_param_type¶
The class string for the default parameterframe type that will be used by the bill of materials.
- Type
str
- _default_material¶
The class string for the default material class that will be used by the bill of materials.
- Type
str
- _parameters¶
List of file locations that contain the parameters that can be used to build a skeleton.
- Type
list
- _parts¶
List of file locations that contain the parts that can be used to build as skeleton.
- Type
list
- _temp_dir¶
Location of the temporary directory.
- Type
str
- _plot_dir¶
Location of the directory which plots will be output to.
- Type
str
- _data_dir¶
Location of the directory which contains data used by the analysis.
- Type
str
- _restrict_param¶
True/False on whether parameters can be added to the parameter frame on the fly.
- Type
boolean
- classmethod define_config(config_dict: dict = {}, config_path: Optional[Union[str, Path]] = None)¶
defines the config file.
The config can be loaded from a supplied dictioanry or from a path. The intention in using a classmethod is that the config can be imported at any stage in a process after initialisation without reloading.
- Parameters
config_dict (dict) – A dictionary containing the config file.
config_path (str) – A string containing the config file location.
- classmethod input_login_details(domain: str = '')¶
Inputs login details.
This method stores login details if they are required.
- Parameters
domain (str, optional) – The domain for any login details.
- classmethod login_details() dict¶
Runs the login details update if any of the values are None.
- Returns
The populated login details.
- Return type
dict
- classmethod to_dict() dict¶
Converts the configuration into a dictionary format.
A check is used so that properties, instances and variables within the BaseCLass are not output.
- Returns
A dictionary containing all the variables specific to the class.
- Return type
dict
- classmethod update_config(**kwargs)¶
Updates the config from given key word arguments.
As Config utilises classmethods an classmethod is required to update it.
- Parameters
kwargs (dict, optional) – Key is attribute, value will be set.
- class bom_analysis.base.BaseFramework¶
Bases:
objectA base framework class that contains a config attribute that can be referenced by BOM analysis or other codes.
A basic framework was created and is the parent to a number of classes within BOM analysis to allow for external configurations to be assigned without having to Monkey Patch.
- _configuration¶
The configuration that will be used throughout BOM Analysis.
- Type
- exception bom_analysis.base.ConfigurationNotFullyPopulated¶
Bases:
ExceptionAn exception for when the configuration is not populated correctly with all the information required for a method to function correctly.
- class bom_analysis.base.DFClass¶
Bases:
BaseClass,PrintParamsTableThe DFClass is included in BOM analysis to allow for data to be stored in a dataframe but with some additional functionality.
This functionality includes printing with tabulate, reading and writing to a serialisable dictionary, and loading pint quantities.
- add_to_col(col: int, data_dict: dict)¶
Adds data to preexisting rows.
- Parameters
data_dict (dict) – Dictionary with self._variables as keys containing data to add.
col (int) – An integer for the DataFrame column number to be added.
- assign(assignee: ndarray)¶
A method for assigning columns to a dataframe.
- Parameters
assignee (np.ndarray) – The array to be assigned to the dataframe.
Note
See for additional information on pandas method used to merge the dataframe.
- property col_count¶
The column count in the wrapped dataframe.
- Returns
Interger if a dataframe exists.
- Return type
int
Note
As the DataFrame is checked and mypy finds it to return Any, the output of the shape is also found to return any.
- compile_all_df(assembly: Any, child_str: str)¶
Compiles all dataframes for a given storage_str into a mutable top level dataframe.
- Parameters
child_str (str) – a string attribute name for the information to be extracted from.
assembly (Any) – the assembly which contains the storage information.
- create_df(number_of_cols: int, *args)¶
Defines the dataframe.
- Parameters
number_of_cols (int) – Number of columns in the DataFrame.
args (arguments, optional) – The row titles of the DataFrame.
See also
pandas.DataFrameMain storage class.
- from_dict(data: dict)¶
Reads and populates from json.
Loads in the parent class and then populates the dataframe if required.
- Parameters
data (dict) – loaded json.
- property header: list¶
Used for printing the dataframe.
- to_dict(exclusions=[]) dict¶
Exports the data for storage in a json file.
The encoding to a json serialisable form has to be defined, it is not applied as an encoder to the json funciton.
- Returns
dump – A dictionary containing all the class inforamtion in a json serialisable format.
- Return type
dict
See also
framework.utils.encoderConverts objects to json serialisable.
Note
The orient=split is to ensure that the correct order is maintained - this can be used for visualising thermal resistors.
- property vars: ndarray¶
The variables in the data.
- Returns
An array of the dataframe index, if exist.
- Return type
np.ndarray
- class bom_analysis.base.MetaConfig¶
Bases:
typeConfiguring different analyse is critical to a workflow functioning correctly. Bill of Materials analysis has a the base Configuration which is inherits a number of methods for the Config and a Meta class for properties and setters. An analysis workflow can use the BaseConfig directly or inherit the BaseConfigMethods and the MetaConfig to customise the configuration parameters.
The base config includes a number of variables which can be used by BOM Analysis and are covered in the other sections such as the MaterialsSelector, the defaults for the Material and the Parameters, and a number of different working directories.
A configuration can also be loaded and dumped to a dictionary using the same method names as the Engineering Components.
The Meta class which defines properies and setters that can be used on the configuration without initialising it and our shared like class properties.
Including properties and setters allows for better error handling and defaulting of values. If a calculation is performed that called a translation but the translator has not been defined within the configuration then a specific error will be raised. If a plot directory is called then but it has not been defined then it will default to the working directory.
- property data_dir: Union[str, Path]¶
The data directory for outputs.
- Returns
Path to the data directory.
- Return type
str
- property default_param_type: str¶
The default parameter type that will be assigned to all components and assemblies attribute params.
- Returns
String path to the param type.
- Return type
str
- property materials: MaterialSelector¶
The property for the materials data.
- Returns
The priority order and location of the materials.
- Return type
_materials
- Raises
ConfigurationNotFullyPopulated – Error if the private variable populated with None.
- property parameters: list¶
A property for the location of any parameter files that can be used to build the skeleton of the bill of materials.
- Returns
A list of locations of the .json that make up the paramaters to be assembled into the skeleton.
- Return type
list
- Raises
ConfigurationNotFullyPopulated – If the property is called but the configuration has not been populated and has the property is None.
- property parts: list¶
The parts section of the configuration are used by the parsers to contain information about parts to be parsed to form the skeleton (dictionary form) of a Bill of Materials.
- Returns
The object assigned to parts.
- Return type
list
- Raises
ConfigurationNotFullyPopulated – If the property is called but the configuration has not been populated and has the property is None.
- property plot_dir: Union[str, Path]¶
The plot directory for outputs.
- Returns
Path to the plot directory.
- Return type
str
- property restrict_param¶
Boolean whether the parameters can be edited on the fly.
Locking down parameters so that they have to be predefined offers some advantages as it prevents a mash up of spelling mistakes and poorly thought out parameters. It does, however, reduce ease of use.
- property temp_dir: Union[str, Path]¶
The temporary directory for outputs.
- Returns
Path to the temporary directory.
- Return type
str
- to_dict() dict¶
Converts the configuration to a dictionary but is not implemented in the MetaConfig as it is only meant as a metaclass for the actual configuration.
- Returns
Dictionary of the configuration.
- Return type
dict
- Raises
NotImplementedError – Not implemented in the MetaConfig.
- property translations: list¶
A property for the locations of the .json that will be loaded into the transaltor.
- Returns
Location of translation file.
- Return type
list
- Raises
ConfigurationNotFullyPopulated – If the property is called but the configuration has not been populated and has the property is None.
- property working_dir: str¶
The working directory for the Configuration.
- Returns
Path to working directory.
- Return type
str
- bom_analysis.base.add_base_class(existing_object: Any, import_method: Callable[[Any], Any], export_method: Callable[[Any], Any])¶
Adds an import and export function to a class under the name export_data and import_data.
This is currently unused and maybe should be removed. The original intention was to be able to add methods to allow json compatible output dictionaries to external functions.
- Parameters
existing_object (Any) – data for which the methods will be added to.
import_method (function) – the import method.
export_method (function) – the export method.
Note
For more information on add a method to an instance see link.
bom_analysis.bom submodule¶
- class bom_analysis.bom.Assembly(ref: Optional[str] = None, assignment: Optional[str] = None)¶
Bases:
EngineeringObjectAn assembly can be made up of multiple sub components which assemble together to form the assembly. The assembly does not have a material assigned to it as it will contain the multiple materials of the components.
An assembly can generally be considered to be made up of multiple other assemblies/components, for example a nut and bolt assembly or an assembly of nut and bolt assemblies with a flange component.
- add_children(skeleton: dict)¶
Creates and adds to _sub_assembly.
Uses the class factory and recursion to add all components in the below it in the hierarchy. This means that, if this instance is a car, the wheel sub assembly instance would be created, as well as the hub cap sub assembly of the wheel.
- Parameters
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
- add_component(component: Any, ref: Optional[str] = None)¶
Add components to the _sub_assembly, meant to allow for non-skeleton assembly creation.
- Parameters
component (instance) – An object to be added to the sub assembly.
ref (str, optional) – A reference for the component to be added.
- add_components(components: Optional[ndarray] = None)¶
Add components to the _sub_assembly, meant to allow for non-skeleton assembly creation.
- Parameters
components (np.ndarray) – An object to be added to the sub assembly.
- add_to_register(component: Any)¶
Aims to add a component to a master register if the componnet is not already within the master register.
If the component already exists within the register it is checked against the rules of the reference. If it does not, a weak reference to the component is added to the masterregister.
- Parameters
component (EngineeringObject) – The component or assembly which is to be added to the master register.
- component_from_string(string: str) EngineeringObject¶
Returns a component within the nested sub assembly based on a . delimited string.
- Parameters
string (str) – A . delimited string which gives the hierarchical path to the component.
- Returns
A populated assembly instance.
- Return type
- count_ref(reference: str) int¶
Counts the number of times a reference has been added to the sub-assembly.
This allows multiple part numbers to be referencen within the same assembly. As BOM analysis is for analysis components with different attributes (such as temperature) will need to be considered carefully.
- Parameters
reference (str) – The reference for the component that will be checked for in the counter.
- Returns
The number of this component that has been added to the assembly.
- Return type
int
- create_class_from_data(ref: Optional[str], skeleton: dict, self_copied: bool = False) Any¶
To correctly create a class from data more some additional changes must me made in addition to loading in the class and then using from_dict. This is to allow the master registers to be merged so that duplicate components are not created (and fail due to not being unique).
- Parameters
ref (str) – The reference for the engineering object, must be unique.
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
self_copied (boolean) – A boolean on whether the instance is being copied. If an instance is being copied then merging the master registers means that a true copy is not formed (as it uses the weak ref of the register).
- Returns
An initialised copy of the object.
- Return type
new_class
- flatten(flat: Optional[Dict[Optional[str], Any]] = None) dict¶
Returns a flat dict of components.
Flattening the components is very useful as it allows an object to be called by its reference no matter where it sits in the hierarchy.
- Parameters
flat (dict, optional) – A previously defined flattened dictionary to allow for recursion.
- Returns
flat – A dictionary containing all the components in the sub assembly where the keys are the component reference.
- Return type
dict
Note
Previous releases fuction used flat={} but ran into this problem.
- from_dict(skeleton: dict, ref: Optional[str] = None)¶
Checks the assembly for children.
This function uses super to call the BaseClass from_dict and then adds any children it the instance has.
- Parameters
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
ref (str) – From_dict is used recursively, if supplied a reference it looks up the skeleton top level keys with the ref.__base__.
- hierarchy(tree: Optional[Tree] = None, parent_node: Optional[Node] = None) Tree¶
Creates a nice graph showing the hierachy.
- Parameters
tree (treelib.Tree, optional) – A treelib instance which may contain nodes, defaults to None.
parent_node (treelib.Node, optional) – A node within a tree that has is the parent of a component, defaults to None.
- Returns
Tree of the component hierarchy.
- Return type
treelib.Tree
- lookup(*args) dict¶
Searches the sub_assembly for chosen data.
- Parameters
args (str) – Parameter strings that will be extracted.
- Returns
Parameter dictionary with the keys as the component ref.
- Return type
dict
Note
This allows for part consistancy to be checked i.e. that part references are unique to a component (there can still be multiple components using the same reference).
- lookup_params(*args) dict¶
Searches the sub_assembly for chosen data.
- Parameters
args (str) – Parameter strings that will be extracted.
- Returns
Parameter dictionary with the keys as the component ref.
- Return type
dict
Note
This allows for part consistancy to be checked i.e. that part references are unique to a component (there can still be multiple components using the same reference).
- merge_register()¶
Merges to registers together from an assembly.
In order to have a master register that contains all component references throughout the entire assembly (not just at the level of self) the master registers are merged. flatten() is used to do this and also contains a check duplicate check. There is a compulational overhead in calling flatten each time but flatten is relatively quick to run.
- property part_count: Counter¶
- plot_hierarchy()¶
Creates a nice graph showing the hierachy.
Note
When using jupyter, the treelib.show() may not show as it has to be called to build a printable tree but also contains a print instead of returning the printable object.
- remove_component(component_ref: str)¶
removes a component from a sub assembly.
To remove a component from the sub assembly is important as the part count and master register can change.
The master register on assemblies above this component are not updated (as there is no link up the tree), instead, self.update_all_sub_assemblies() should be used to rebuild the register on the top level component.
- Parameters
component_ref (str) – The unique reference of teh component to be removed.
- sub_assembly_to_child(ref: str, child_dictionary: dict) dict¶
Converts a sub assembly to a child that can be written to a skeleton.
As a skeleton is flat (no hierarchy) defining a sub assembly on a component within a dumped dictionary is not appropriate as it would (by definition) be very nested. To avoid this the children are used to represent the sub assembly, containing the child reference and a type (if exists).
- Parameters
ref (str) – The reference of the child.
child_dictionary – The childs skeleton.
- Returns
A dictionary containing a the reference and a type of that reference.
- Return type
dict
Note
The type of component only usually exists if it the skeleton has been parsed together.
- to_dict(exclusions: list = ['master_register', '_sub_assembly']) dict¶
Converts the component to a dictionary.
This method uses super to call the to_dict from the BaseClass.
- Parameters
exclusions (list, optional) – A list of attibutes that will be excluded from the conversion to the dictionary.
- Returns
A dictionary containing all the component information.
- Return type
dict
- update_all_sub_asseblies()¶
Updates all sub assemblies in a assembly.
- update_sub_assembly()¶
A class for updating a subassembly.
This method alls the updating of the sub assembly, part count and master register if the ref has changed. .ref are not connected to the same datapoint as the key in sub assembly therefore it is ncessary to use this method.
- class bom_analysis.bom.Component(ref: Optional[str] = None, material: Optional[str] = None, assignment: Optional[str] = None)¶
Bases:
EngineeringObjectThe component is the lowest level Engineering Object in the Bill of Materials and, critically has a material assigned to it.
A Component can generally be considered a physical object made up of a single material, for example a bolt made of high strength steel.
- hierarchy(tree: Optional[Tree] = None, parent_node: Optional[Node] = None) Optional[Tree]¶
Used to create a hierarch of a BOM.
This is a basic return due so that the main hierarchy of an assembly does not need to distinguish between components or assemblies.
- Parameters
tree (Union[treelib.Tree, None], optional) – A hierachy treelib instance.
parent_node (Union[treelib.Node, None], optional) – The parent node within the tree.
- Returns
A hierachy treelib instance.
- Return type
treelib.Tree
- to_dict(exclusions: list = []) dict¶
Converts the component to a dictionary.
This method uses super to call the to_dict from the BaseClass.
- Parameters
exclusions (list, optional) – A list of attibutes that will be excluded from the conversion to the dictionary.
- Returns
A dictionary containing all the component information.
- Return type
dict
- class bom_analysis.bom.EngineeringObject(ref: Optional[str] = None, assignment: Optional[Any] = None)¶
Bases:
BaseClassThe Engineering Object is a parent class for parts within the bill of materials. It contains key variables and methods which allow the bill of materials to function.
- add_class(class_name: str, class_data: dict)¶
Adds a class from data to the class instance.
This function utilises the class factory in the framework.utils to create a new class with type.
- Parameters
class_name (string) – The name of the class.
class_data (dict) – The data that will be added to a new class.
- add_default_material()¶
Adds a material class to the engineering object.
Similar to adding the default parameter, this method adds a default material class to the engineering object. The default is a dummy database that does not have any data extraction capibility.
- add_default_params()¶
Adds a default parameter to the engineering object.
The default parameter is taken from the Configuration class in the BaseFramework. An unmodified BOM Analysis will default to a PintFrame which has native Pint units.
- add_defaults(defaults: dict)¶
Calls the add_defaults method in the ParameterFrame to populate it from a dictionary.
The dictionary based parameter population allows for a full skeleton format {<ref>:{‘params’:{‘data’:{‘mass’:{‘value’:10}}}}} or just {<ref>:{‘mass’:10}}.
- Parameters
defaults (dict) – The dictionary of defaults that will be added to the EngineeringObject.
- property assembly: bool¶
Bolean as to whether it has sub components.
A sub assembly is assumed to differentiate itself from a component on whether or not it has the _sub_assembly attribute.
- Returns
Boolean on whether it has the _sub_assembly attribute.
- Return type
bool
- assign_all_materials()¶
Loops through all engineering objects nested within the engineering object and assigns materials databases where possible.
- assign_materials_database()¶
Assigns a new material database to the engineering object based on the name of material and priority of databases.
The configuration contains a materials selector which can be searched through for a particular material string such as Helium. If this selector has been initialised and populated correctly then a new database with the previous temperature and pressure assignment will be created.
- property assignment: ndarray¶
An engineering object can be assigned values such as ‘Blanket’ or ‘Layer_2’ or ‘Yellow’ in order to provide additional information to analysis.
The aim of the assignment is to provide a list of strings that can be used in the calculation. For example, an engineering object may always want to be assigned the color “Yellow”.
Assignments are stored as numpy array but can be given a string as which the setter will add to the assignment.
- check_duplicate(component_1: Any, component_2: Any)¶
Check whether a two components adhere to the bill of materials rules on the names of _ref.
Within a bill of materials components must have different references if they are different. If a component is used in a different assembly in the bill of materials it can still have the same reference if the object is the same. This is checked by this method.
- Parameters
component_1 (EngineeringObject) – First Component for comparison.
component_2 (EngineeringObject) – Second Component for comparison.
- Raises
NonUniqueComponentReference – If the component has a different id and the same reference.
Note
The Statically Typed Python format for this and other modules has Any as an input to the method. Using BOM analysis this should be an EngineeringObject (as per docstring) but requires self to be input into this function which is only easily implemented in >3.9.
- copy_part() Any¶
Creates a copy of the component.
For the complex classess, using copy.deepcopy(x) did not work, therefore a in-built method was created. This function works by converting the class with to_dict copying that and then using the class factory to recreate it.
- Returns
new_class – Copy of the part.
- Return type
instance
- create_class_from_data(ref: Optional[str], skeleton: dict, self_copied: bool = False) Any¶
Creating a class from data is relatively simple for EngineeringObjects as they do not have master registers or sub assemblies.
- Parameters
ref (str) – The reference for the engineering object, must be unique.
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
self_copied (boolean) – A boolean on whether the instance is being copied. If an instance is being copied then merging the master registers means that a true copy is not formed (as it uses the weak ref of the register).
- Returns
An initialised copy of the object.
- Return type
new_class
- create_top_level(ref: Optional[str], skeleton: dict) Any¶
Creates a top level EngineeringObject from a skeleton.
- Parameters
ref (str) – The reference for the engineering object, must be unique.
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
- Returns
A new EngineeringObject based on the Skeleton.
- Return type
- flatten(flat: Optional[Dict[Optional[str], Any]] = None) dict¶
Returns a flat dict of components.
- Parameters
flat (dict) – A pre build dictionary, used when flatten is operated recursively.
- Returns
flat – A updated dictionary with the engineering objects flatteded self.
- Return type
dict
- from_dict(skeleton: dict, ref: Optional[str] = None)¶
Builds the part from the json.
- Parameters
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
ref (str) – From_dict is used recursively, if supplied a reference it looks up the skeleton top level keys with the ref.__base__.
- lookup(*args) dict¶
Searches the sub_assembly for chosen data.
This fuction looks up the attributes within an engineering object where the attributes are supplied as arguments.
- Parameters
args (str, optional) – Parameter strings that will be extracted.
- Returns
lookup – A dictionary of the lookup values with the first key as the engineering object reference.
- Return type
dict
Note
This allows for part consistancy to be checked i.e. that part references are unique to a component (there can still be multiple components using the same reference).
- lookup_params(*args) dict¶
Searches the sub_assembly for chosen data.
- Parameters
args (str) – Parameter strings that will be extracted.
- Returns
A dictionary of the component and any lookup parameters.
- Return type
dict
Note
This allows for part consistancy to be checked i.e. that part references are unique to a component (there can still be multiple components using the same reference).
- property material: MaterialData¶
The material property of the engineering object.
The material is key to the bill of materials. Components have specific materials such as eurofer or helium while assemblies may have homogenised materials for neutronics assessment.
- Returns
A class for the materials that contains access to the material data.
- Return type
- property params: Optional[ParameterFrame]¶
The property which represents the parameters of the engineering object.
The parameters hold specific variables of an engineering object in a ParameterFrame class to allow for easy reference, display, and access to key engineering variables such as mass or volume.
- Returns
The parameterframe of the parameters.
- Return type
- property ref: Optional[str]¶
A reference which represents a unique variable for an engineering component such as a part number. The reference can be any string, the key is that it is unique to the part. Multiple assemblies within a system can have the same reference within them but the Engineering Object with this reference in all assemblies must be the same.
For example, a bolt made of Carbon Steel and a bolt made up of Stainless Steel may have exactly the same dimensions and in the same system on different assemblies must not have the same reference because the object is not the same.
Practically, a hierarchy has a master register of references with weakref to the object. When assemblies are added to one another, or a component is added to an assembly at any level in the hierarchy, the master register is consulted and checked to ensure that the reference has not been used on another part. The reference is a property of all Engineering Objects.
- class bom_analysis.bom.HomogenisedAssembly(ref: Optional[str] = None, assignment: Optional[str] = None)¶
Bases:
AssemblyA homogenised assembly is a special type of assembly which does not exist in the physical world but instead is analytical (particularly for neutronics analysis). A Homogenised assembly can have both sub components and materials assigned to it.
An example of the analytical use of a Homogenised assembly would be a bolt and nut assembly represented as a single body in structural FEA to simplifly the analysis.
- exception bom_analysis.bom.NonUniqueComponentReference¶
Bases:
ExceptionError for when there is a non-unique reference to the required coomponents i.e. two components within the same body that have the same assignment.
- class bom_analysis.bom.SubAssembly¶
Bases:
dictDictionary with an export.
Note
This maybe depricated as it can be replaced with a dictionary.
bom_analysis.build submodule¶
- class bom_analysis.build.Framework(config_path: Optional[Union[str, Path]] = None, config_dict: dict = {})¶
Bases:
BaseFrameworkThe framework offers an automated way of populating configurations, translators, settings, and parsing skeletons uting dictionaries. Following poplulation of the various different required information it can then getnerate the bill of materials and solve the analysis workflow.
- classmethod initialise_cross_class(login: bool = False, config_path: Optional[Union[str, Path]] = None, config_dict: dict = {})¶
Initialises the classes that supply information and funcitonality across the bom_analysis.
- Parameters
loggin (bool, optional) – Login details required.
config_dict (dict, optional) – A dictionary containing the config file.
config_path (str, optional) – A string containing the config file location.
- classmethod load(top: str, skeleton: dict) EngineeringObject¶
Simple load of a skeleton to BoM structure.
This loads the skeleton but does not load the settings or config.
- Parameters
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
top (str, optional) – Reference of the instance sitting at the top of the hierarchy.
- Returns
A populated assembly from framework.bom.
- Return type
- classmethod reader(skeleton: dict, top: Optional[str] = None, settings: dict = {}, config_path: Optional[Union[str, Path]] = None, config_dict: dict = {}) EngineeringObject¶
Returns a class representing the populated bill of materials by parsing information from loaded from the config and settings.
This class reads defines teh config, and uses the settings to take a skeleton and populate bill of materials object. The skeleton can be supplied if a modification on an existing skeleton is requried.
- Parameters
skeleton (dict) – A dictionary containing all the information about an engineering object. The first level keys are the names of the parts which make up the engineering object.
top (str, optional) – Reference of the instance sitting at the top of the hierarchy.
settings (dict, optional) – A dictionary of the settings for framework.
config_dict (dict, optional) – A dictionary containing the config file.
config_path (str, optional) – A string containing the config file location.
- Returns
assembly – A populated assembly from framework.bom.
- Return type
bom_analysis instance
See also
framework.bom.AssemblyAn engineering object with a sub assembly.
- settings() dict¶
Return a dictionary of the settings that have been used in the solver.
- Returns
A dicitionary containing all the solver settings.
- Return type
dict
- classmethod solver(settings: dict = {}, assembly: Optional[EngineeringObject] = None) Solver¶
Creates a solver based on the settings.
Creates a solver object from the settings (which define the modules that will be run) and the assembly.
- Parameters
assembly (bom_analysis instance) – A populated assembly from framework.bom.
settings (dict) – The settings for the framework containing the modules that will be run.
- Returns
ordered_run – A solver object which has assigned parts of the assembly to solvers and defined an order to run in.
- Return type
type
See also
framework.solverA solver object.
bom_analysis.materials submodule¶
- class bom_analysis.materials.Composition(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, irradiation: ~pint.quantity.Quantity = <Quantity(0.0, 'displacements_per_atom')>, **kwargs)¶
Bases:
MaterialDataA homogenised material composition.
- class bom_analysis.materials.CoolPropsWrap(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, irradiation: ~pint.quantity.Quantity = <Quantity(0.0, 'displacements_per_atom')>, **kwargs)¶
Bases:
MaterialDataA wrapper for CoolProps with pint units.
- to¶
The string argument that will be used by the translator.
- Type
str
- static check(mat: str, **kwargs) bool¶
Checks CoolProps for a material name.
The material name can be supplied alongside a translate_to key word argument to allow the name to be translated into a particular form.
- Parameters
kwargs (key word arguements) – Supplied keyword arguments.
- Returns
A True/False on whether the material exists in the library.
- Return type
bool
See also
CoolPropCoolant material data.
Note
Translate_to must be supplied therefore this should be reflected format of the method.
- extract_property(property_name: str) Quantity¶
Extracts a property from CoolProp and returns the quivalent Pint Quantity.
Uses the global parameter COOLPROPUNITS to define the units (the test suite will fail if later versions of coolprops change this). Only outputs properties by that need pressure and temperature inputs and not properties that need other inputs such as surface tension. Will translate a property_name into the CoolProp format if included in the translator.
- Parameters
property_name (str) – The string of the property to be used by CoolProp or to be translated into the string used by CoolProp.
- Returns
Quantity for the property at the material temperature and pressure.
- Return type
- to = 'CoolProps'¶
- class bom_analysis.materials.DFLibraryWrap(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, **kwargs)¶
Bases:
MaterialDataA material data which pulls from a DataFrame.
- static check(mat: str, **kwargs) bool¶
Checks the underlying dataframe for a material name.
The material name can be supplied alongside a translate_to key word argument to allow the name to be translated into a particular form.
- Parameters
kwargs (key word arguements) – Supplied keyword arguments.
- Returns
A True/False on whether the material exists in the library.
- Return type
bool
Note
Translate_to must be supplied therefore this should be reflected format of the method.
- extract_property(property_name: str) Quantity¶
Primary method for extracting data from the materials database.
- Parameters
property_name (str) – The name of the proprty to be extracted from the material data.
- Returns
The output of the material data for the property name.
- Return type
Quantity
- from_dict(data: dict)¶
Imports from a json and populates the material.
Runs the parent class then uses the dataframe read_json method.
- Parameters
data (dict) – A dictionary containing the material data.
See also
pandas.DataFrame.read_jsonThe method for reading a json.
- to_dict(exclusions=['_mat_data']) dict¶
Exports the data for storage in a json file.
Runs the to_dict method excluding the material data.
See also
base.BaseClass.to_dictParent to_dict.
- class bom_analysis.materials.Fluid(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, irradiation: ~pint.quantity.Quantity = <Quantity(0.0, 'displacements_per_atom')>, **kwargs)¶
Bases:
MaterialDataA class defining a fluid material wrapping a generic material from the library with fluid specific ease of use property access.
- class bom_analysis.materials.MaterialData(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, irradiation: ~pint.quantity.Quantity = <Quantity(0.0, 'displacements_per_atom')>, **kwargs)¶
Bases:
BaseClassA parent material data class MaterialData is provided in BOM Analysis (alongside CoolProp and DataFrame children). The MaterialData class is added by default to Components and Homogenised Assemblies in the BOM.
- The materials have four key properties:
mat - the name of the material
temperature - the temperature of the material
pressure - the pressure of the material
irradiation - the Displacement per Atom of the material
These four properties can be supplied to a data source to extract material data at the input values using the extract_property method. The material also has a feature to check whether a material exists in the database - to do this successfully it is likely that the translation class is utilised as different databases tend to use different naming formats.
Additional, the material classes have the data_warpper method which calls the extract_property for the instance with the benefit that if the property (or material) does not exist in the database of that instance it will check the other databases within the MaterialSelector.
- SetLibMaterial(mat: str)¶
Sets the material name under the private material variable _mat.
- Parameters
mat (str) – A string of the material name.
Note
This naming and function was based on a now depricated material property in the external library.
- SetRefPressure(pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>)¶
Sets the component pressure.
- Parameters
pressure (pint instance, optional) – A pint instance for the component pressure.
Note
This naming and function was based on a now depricated material property in the external library analysislib.
- SetRefTemp(Temp: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>)¶
Sets the component temperature.
- Parameters
Temp (pint instance, optional) – A pint instance for the component temperature.
Note
This naming and function was based on a now depricated material property in an external library.
- add_defaults(data: dict)¶
- static check(mat: str, **kwargs) bool¶
Checks a library for a material, not implemented within the parent class.
- Raises
NotImplementedError – Not implemented within the parent class.
- data_wrapper(property_name: str, i_database: int = 0) Quantity¶
Wraps the material data from the MaterailData extract property with a try except.
The except is raised if a NoMaterialDataExtraction is raised (i.e. if a material property cannot be extracted from this class). If this exception is raised the method will attempt to extract the property from the next class in the MaterialSelector.priority_order. The MaterialSelector is in the framework.base.BaseFramework._configuration.materials.
- Parameters
property_name (str) – The name of the property which will be extracted.
i_database (int, optional) – The integer which calls the material class in the MaterialSelector.priority_order , by default 0.
- Returns
The extracted material property at the pressure and temperature of the material.
- Return type
Q_, float
- Raises
MaterialPropertyDoesNotExistError – If the material property does not exist in any of the classes in the MaterialSelector.priority_order.
- extract_property(property_name: str) Quantity¶
Extracts a property from the MaterialData, not implemented in the parent class.
- Parameters
property_name (str) – The property to be extracted from the material data.
- Raises
NotImplementedError – Not implemented in the parent class.
- from_dict(data: dict)¶
Imports from a json and populates the material.
- Parameters
data (dict) – A dictionary containing the material data.
- property irradiation: Quantity¶
The irradiation of the material.
- Return type
The irradiation of the material.
- property mat: Optional[str]¶
The name of the material.
- Returns
The name of the material.
- Return type
str
- property pressure: Quantity¶
The pressure of the material.
- Returns
The pressure of the material.
- Return type
Quantity
- property reftemp: Quantity¶
Reftemp is legacy to fit with some older external codes.
- Return type
The temperature of the material.
- property temperature: Quantity¶
The temperature of the material.
- Returns
The temperature of the material.
- Return type
Quantity
- to = ''¶
- exception bom_analysis.materials.MaterialPropertyDoesNotExistError¶
Bases:
Exception
- exception bom_analysis.materials.NoMaterialDataException¶
Bases:
Exception
- class bom_analysis.materials.Solid(mat: ~typing.Optional[str] = None, temperature: ~pint.quantity.Quantity = <Quantity(293.0, 'kelvin')>, pressure: ~pint.quantity.Quantity = <Quantity(100000.0, 'pascal')>, irradiation: ~pint.quantity.Quantity = <Quantity(0.0, 'displacements_per_atom')>, **kwargs)¶
Bases:
MaterialDataThe material object may want to bring the tritium and temperature information within.
- bom_analysis.materials.exception_handler(func: Callable) Callable¶
A custom descriptor that returns an error when a function fails.
This raises a NoMaterialDataException when the the method which is wrapped fails.
- Parameters
func (Callable) – The function wrapped by the descriptor.
- Returns
The wrapper for the function.
- Return type
Callable
- Raises
NoMaterialDataException – if the method has failed.
Note
Information about creating an exception handler can be found here.
bom_analysis.parameters submodule¶
- class bom_analysis.parameters.FlexParam(val: Box)¶
Bases:
objectFlexible parmeter is a wrapper for a non-mutable box.
The keys of the box are flexible and utilise class attributes so that the keys are shared across all instances.
- _required_keys¶
The keys required by the parameter, will raise a key error if not supplied.
- Type
np.array
- _additional_keys¶
The additional keys that are shared across all instances of the flexible parameter.
- Type
np.array
Note
The recommended keys are below.
- var: str
The short parameter name.
- name: str
The long parameter name.
- value: float
The value of the parameter.
- unit: str
The unit of the parameter.
- source: str
The source (reference and/or code) of the parameter.
- asdict() dict¶
Converts the frozen box to a dictionary by using the boxes in-built method.
- Returns
The dictionary of the ParameterFrame _data attibute.
- Return type
dict
- check_inputs(data: Union[dict, Box])¶
Checks that the input is correct by comparing the ._required_keys attribute to the data.
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
- Raises
KeyError – If the keys do not match.
- property data: Box¶
Property for the primary data store that contains the frozen box under the private _data variable.
The property runs and update before returning the private _data to add any additional keys to the returned box.
- Returns
The parameter data store.
- Return type
Box
- property fields: ndarray¶
Property that returns all the keys in the data store by appending the _required_keys and _additional_keys.
- Returns
The appended _required_keys and _additional_keys.
- Return type
np.ndarray
- parameter() Box¶
returns the frozon box.
This function is included for backwards compatibility.
- Returns
A frozen box containing the parameter information.
- Return type
Box
- classmethod process_inputs(value: Union[dict, Box]) dict¶
Processes the inputs to the data to extract any new keys and write them to the _additional keys class attribute.
Also assigns None if any of the additional keys are not supplied.
- Parameters
value (Union[dict, Box]) – Input variable to the box data store.
- Returns
The processed input with full _required_keys and _additional_keys.
- Return type
dict
- replace(**kwargs)¶
Replaces any of the variables in the data store with a new value.
As the data store is designed to be non-mutable a new box is created based on the old boxes dictionary and the kwargs supplied.
- update()¶
Updates the private _data with a frozon box for a new data set and adds any additional keys that were input but not captured in _additional_keys attribute.
Checks fields and updates if they do not match.
- exception bom_analysis.parameters.MissingParamError¶
Bases:
AttributeErrorError when a parameter is not in the data.
- class bom_analysis.parameters.ParameterFrame(**kwargs)¶
Bases:
PrintParamsTableThe Parameter class aims to be the primary method for storing parameters within the Engineering Objects. A version (either Pint integrated or not) is included with every Engineering Object using the attribute params. The default is with Pint integration is set within the Config.
Having a structured method for storing parameters is key to sharing data - it allows additional information to be supplied such as the source or an improved description.
Individual parameters use namedtuple and the parameter database use DataFrames. In addition to the name and value that needs to be supplied to the individual parameter any futher information can be added as mentioned. If an additional bit of information is included (such as devaiation) all parameters will be updated with a empty placeholder for that information.
The design for parameter handling was inspired by BLUEPRINT (publication)
- add_basic_parameters(parameter_dict: dict)¶
To simplify adding multiple parameters quickly this method can be use but does not allow the assignment of anything other than the value and var.
Legacy method that uses the .add_defaults method.
- Parameters
parameter_dict (dict) – dictionary of values to be added to the frame where the key is the var.
- add_defaults(data: dict)¶
Adds default parameters to the parameterframe.
If the parameter is not in the data and the config allows data to be added then the parameters will be created from the input dictionary. If the data is already in the _data then the parameters will be updated.
- Parameters
data (dict) – The data which will be added to the parameterframe.
- add_parameter(**kwargs)¶
Adds a parameter to the underlying _data, must be supplied with a var key. If not supplied with a value a value of None will be added.
The kwargs are used to be flexible in the addition of variables with the checks that the correct keys are supplied beiing conducted in the Parameter.
- check_param(attr: str) bool¶
Checks a parameter exists within the database.
- Parameters
attr (str) – the attibute name to be checked to see if a wrapped named tuple exists in _data or as attribute.
- Returns
True/False on whether the parameter exists in _data.
- Return type
bool
- class_str = ['bom_analysis.parameters.ParameterFrame']¶
- convert_parameter_dictionary_to_list(parameter_dicts: dict) list¶
Converts the paramters contained within _data to a list of parameters.
Includes a try except to caputure any supplied dictionaries that contain the var as the key and the value as the value of that key e.g. {mass:Q_(1, ‘kg’)}.
- Parameters
parameter_dicts (dict) – The dictionary of paramters to be converted to a list.
- Returns
List of the paramter dictionaries.
- Return type
List
- default_from_dict(data: dict) list¶
Extracts the information from the data.
This class allows differnet formats of dictionaries to be extracted. This is so that the method can accept a skeleton format or a format which is simpler for a used.
- Parameters
data (dict) – The dictionary containing the parameter data.
- Returns
A list of dictionaries in the format from which a Parameter can be created ({var:mass, value:10, unit:10}).
- Return type
list
- extract_dictionary_of_parameters(data: dict) dict¶
Extracts a dictionary of the different parameters supplied in the data dictionary.
Different (and legacy) skeletons can have the parameters in different stages of a nested dictionary with different keys. This function returns the parameter dictionary for each of the various locations.
- Parameters
data (dict) – Nested dictionary containing the parameters.
- Returns
Dictionary of the parameters only.
- Return type
dict
- from_dict(class_data: dict)¶
Builds the fuction from the stored information.
- Parameters
class_data (dict) – The dictionary which is input to populate the parameter frame.
See also
utils.decoderDecodes a json serialisable dict into numpy format.
- get_param(attr: Optional[str], key: Optional[str] = None) Any¶
Gets a chosen parameter from the parameterframe instead of the value.
This allows return of other parts of the parameter so that things like the unit can be accesseed.
- Parameters
attr (Optional[str]) – The attibute name to be checked to see if a wrapped named tuple exists in _data or as attribute.
key (Optional[str]) – The field in the parameter which will be returned.
- Returns
The parameter for the given attibute name, can be the Box if no key is supplied or the item in the box for the given key.
- Return type
Any
- Raises
MissingParamError – If the parameter does not exist in the _data or the key does not exist in the parameter.
- property header: ndarray¶
The order which the table output will be given based on the order in the _required_keys followed by the order in the _additional_keys.
- Returns
a list in order of the headers for printing the parameter frame.
- Return type
np.array
- property order: ndarray¶
The order which the params have been added to the parameterframe.
- Returns
the order the params have been added.
- Return type
array
- to_dict() dict¶
Dumps the parameter frame to a json serilisable dictionary.
The class string is included to allow for the BOM analysis to recreate the ParameterFrame from a skeleton.
- Returns
A json serialisable dict containing all the data from the parameter frame.
- Return type
dict
See also
utils.encoderEncodes to json serialisable dict from the numpy format.
- update_parameter(var: Optional[str] = None, **kwargs)¶
Update full Parameter information (except for var).
- Parameters
kwargs (key word arguments, optional) – The data which makes up a new parameter.
- class bom_analysis.parameters.PintFrame(**kwargs)¶
Bases:
ParameterFramePint integrated version of the parameter frame.
- add_parameter(**kwargs)¶
Adds a parameter to the underlying _data, must be supplied with a var key. If not supplied with a value a value of None will be added.
The kwargs are used to be flexible in the addition of variables with the checks that the correct keys are supplied beiing conducted in the Parameter.
- class_str = ['bom_analysis.parameters.PintFrame']¶
- class bom_analysis.parameters.PintParam(val: Box)¶
Bases:
FlexParamParameter with pint integration.
A child of FlexParam with pint type enforcement for the value.
- asdict() dict¶
As the parent class, uses the in-built to_dict method of the box to return the parameter as a dictionary. Additionally the method tries to extract the unit from the quantity in the ‘value’ key and return it under the ‘unit’ key as a string.
- Returns
The dictionary of the ParameterFrame.
- Return type
dict
- check_dimensionality(data: Union[dict, Box])¶
A parameter cannot change dimensionality, i.e. cannot go from being 1m (with the dimensionality [length]) to 1s (with the dimensionality [time]). This function checks that changes to the _data to not violate this.
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
- Raises
AssertionError – If the dimensionality is not the same.
- check_for_pint(data: Union[dict, Box])¶
Checks that the correct unit is being supplied.
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
- Raises
ValueError – If a pint unit is not supplied.
pint.DimensionalityError – If the wrong type is supplied.
- check_inputs(data: Union[dict, Box])¶
Checks that the input is correct by comparing the ._required_keys attribute to the data as per the parent class but also checks whether the input has a pint quantity, if the input should, and whether it is appropriate (consistant dimensionality).
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
- Raises
KeyError – If the keys do not match.
- check_non_string(data: Union[dict, Box])¶
Checks that a non-strings is supplied with the information to create a pint quanitity within the input data under the “value” key.
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
- Raises
ValueError – If not a quantity or a unit is not supplied in data.
- check_string(data: Union[dict, Box])¶
Checks whether a supplied string in the “value” key of the data can form a pint quantity.
Pint can form a quantity from an input string such as ‘1 meter’ which will be interpreted by this parameter.
- Parameters
data (Union[dict, Box]) – The data dictionary to be checked.
bom_analysis.parsers submodule¶
- class bom_analysis.parsers.ConfigParser(skeleton: dict, operate: bool = True)¶
Bases:
SkeletonParserParses config to create basic skeleton.
- defaults¶
Default parameters which will be applied to the skeleton.
- Type
dict, optional
- paramters¶
Any additional parameters defined by params_name.
- Type
dict, optional
- storage¶
Any other attribututes to be added to a function where inherits is present.
- Type
dict, optional
- modules¶
The modules which will be ran assessing the skeleton.
- Type
dict, optional
- add_bones_from_config(*args)¶
Adds bones to the skelton such as the parameters from a config file.
- Parameters
args (tuple) – A tuple of the dictionary containing the data location, usually a config.
- add_default_param(component: dict)¶
Adds the default parameter to the component dictionary.
- Parameters
component (dict) – The component dictionary which will have the default added to it.
- add_spine()¶
Defines the components, the spine of the skeleton.
This is performed by indentifying the top component in the hierarchy and then using recursion to add all the components below. The components are loaded from the parts file locations given in the config.
- create_skeleton()¶
Parses config to create skeleton.
This is done by first building the spine of the skeleton contianing all the parts in the hierarchy. Following htis, additional bones are added containing the parameters and inherited part information.
- load_data_files(ordered_titles: Iterable, *args) tuple¶
Loads the required data files.
This is performed by checking the ordered titles against the dictionaries supplied in args. This means that the args could have multiple different file locations using the same key (such as a config and settings) and all would be loaded by this function.
- Parameters
ordered_titles (iterable) – A list or tuple of the ordered titles for files which will be loaded form the corresponding key in the supplied args.
args (tuple) – A tuple of dicionaries which contain the locations of the files to be loaded where the ordered titles are the keys.
- Returns
output – A tuple of dictionarys of all the loaded data from the ordered titles, same length and order as ordered_titles.
- Return type
tuple
Note
It was recommended not using lists unless necessary perhaps a concatenated string is better but could run into problems with string.
- update_config()¶
Updates the classes _config.
This adds the Config class as a dictionary to the parser. Transforming this to a dictionary is used to align with children of this class.
- class bom_analysis.parsers.SettingsParser(settings: dict, skeleton: dict, operate: bool = True)¶
Bases:
ConfigParserA class to parse a settings file and create a skeleton based on it and a base skeleton. Also checks the input.
- add_marrow()¶
Adds default parameters and makes changes to the system.
This adds any non-structural changes and then introduces default parameters, materials, and data storage.
- alter_vertebrae()¶
Alters the all component vertebrae which may or may not make up the skeleton.
Initially updates the vertebrae with any changes, then adds the unchanged skeleton to the vertebrae. This allows the structure to be changed without all the inputs being supplied.
- check_settings()¶
Checks the user settings are ok and populates the settings with an empty type in the correct format when a key is missing.
- create_vertebrae_pool()¶
Loads any vertebrae from a file, defaults to an empty dictionary.
- vertebrae¶
The vertebrae that will make up the spint of the skeleton, basically all the parts.
- Type
dict
- define_marrow()¶
Loads any vertebrae from a file, defaults to an empty dictionary.
- defaults¶
Default parameter values which can be added to the skeleton.
- Type
dict
- parameters¶
The parameters which can make up the skeleton.
- Type
dict
- storage¶
Any additional storage which can be added.
- Type
dict
- modules¶
Data on the modules which will be run on the skeleton.
- Type
dict
- load_defaults(ref: str, component: dict, defaults: dict)¶
Loads the defaults if they exist within the component.
- Parameters
ref (str) – The unique component reference.
component (dict) – Dictionary with all component information.
defaults (dict) – The defaults parameters to be added to the component.
- load_module_requirements(all_modules: dict)¶
Loads any data requirements a module has.
This method is to allow the BOM Analysis Skeletons to be used by modules contained within the settings. It means that a module may require a particular component for assessment (such as a coolant) and that the skeleton can then be checked for it. Equally, if the part exists in the skeleton, parameter or storage requirements for the module can be added to the skeleton.
- Parameters
all_modules (dict) – All the modules, even the ones not in going to assessed i.e. the ones not included in the order.
- Raises
ValueError – Raised if the required module is not in the skeleton.
- load_storage(component: dict, storage: dict)¶
Loads the storage on a component.
This allows additional storage types to be loaded into a component. As the skeleton is nothing more than a nested dictionary with particular, basic data types, the storage can be load in and will come with a class_str key if they are anything more than the basic data types.
- Parameters
component (dict) – Dictionary with all component information.
storage (dict) – The storage dictionary to be loaded into the component.
- rebuild_spine(all_comp: dict)¶
Rebuilds the spine with only the required components.
- Parameters
all_comp (dict) – All the components which the rearranged spine can be added from.
- select_library(material: dict)¶
Chooses materials library.
Choses the material library for a given material string by searching each one to determine whether the material exists within in. The config also provides an order to the materials library, which will be search for and the loop stopped when the material is found.
- Parameters
material (str) – The material name.
- Raises
ValueError – Fails when the material does not exist in any of the databases.
- surgery()¶
Performs surgery on the skeleton by rearranging the components, simplifying, populating based on the _settings.
The analogy used to help undestanding continues from the skeleton. Initially, the settings may rearrange the vertebrae i.e. they may alter the hierarchy. Then the bones can be added like in the config file, followed by additional information (the marrow) such as particular data structures.
- to_type_skeleton(skeleton: dict) dict¶
Converts the skeleton to an input parts format with the keys swapped from the reference to the type.
This is required so that data from a previously built skeleton can be used as input.
- Parameters
skeleton (dict) – A dictionary of the components within the hierarchy.
- Returns
The skeleton with type as input.
- Return type
dict
- update_settings(settings: dict)¶
Updates the parser settings.
- Parameters
settings (dict) – The settings which will be used to created the skeleton modifications.
- class bom_analysis.parsers.SkeletonParser¶
Bases:
BaseFrameworkParsing a skeleton is a way of building a skeleton without building the bill of materials. It can help speed up the creation of new BOM but, as it parsers a number of files, operates mostly with .json and is therefore not object orientated.
The skeleton can be parsed from a a config and setting dictionary which contains all the information needed. The config dictionary can also be read into the Configuration class.
The parsers can be found in the parser.py section of BOM analysis.
- add_bone(component: dict, parents: dict, parameters: dict)¶
Add a bone based on the basic information.
- Parameters
parents (dict) – A dictionary of components which the items will be inherited.
parameters (dict) – A dictionary which any params_name will be looked up in.
component (dict) – A dictionary for the component being assessed.
Note
Copy required as a new memory location for each item requred.
- add_bones(parents: dict, parameters: dict)¶
Adds the more detailed information (the bones) to the skeletons.
- Parameters
parents (dict) – A dictionary of components which the items will be inherited.
parameters (dict) – A dictionary which any params_name will be looked up in.
- add_default_param(component: dict)¶
Adds the default parameter to the component dictionary.
- Parameters
component (dict) – The component dictionary which will have the default added to it.
- all_params(component: dict, parameters: dict)¶
Adds parameters to the component.
As with inheritance, params can be added by loading in from an external dictionary which are checked for values given by within the key param_str. When the params are loaded in the param_str is then deleted so that params are not loaded multiple times. The partucular parameter class (such as one with Pint integration) is also loaded in by the special string class_str.
- Parameters
component (dict) – The component which will be checked for an inherits key.
parameters (dict) – All the parametrs which will be searched for for the values given by the parama_str key of the component.
Note
The switch from params to _params is to correctly parse for the updated components with params as a property.
- children(skeleton: dict, component_database: Dict[str, Dict], reference: str, child_input: dict)¶
Imports the children into the skeleton.
This function relies heavily on recursion to search down through all the children in order to populate the skeleton.
- Parameters
skeleton (dict) – A dictionary of the components within the hierarchy.
component_database (dict) – Dictionary of all components.
reference (str) – Unique reference for the part which is being assessed.
child_input (dict) – Dictionary with type of the child, used to lookup component_database.
Note
Copy necessary when you have the same part ref used for different parts.
- component_data(component_ref: str, component_type: str, component_database: Dict[str, Dict]) Dict[str, Union[dict, str]]¶
Extracts a component from a component_database with the type used as the key in the dict.
- Parameters
component_ref (str) – The reference for the component which will be created.
component_type (str) – The type of component that will be created.
component_database (dict) – The database of components which contains all the parts.
- Returns
A dictionary of the component with the key as the ref.
- Return type
dict
- component_dictionary(component_ref: str, component_type: str, component_database: Dict[str, Dict], parameter_dictionary: dict) dict¶
Creates a dictionary for a components or assembly.
The component dictionary can be a simpler way of buildin a bill of materials component.
- Parameters
component_ref (str) – The reference for the component which will be created.
component_type (str) – The type of component that will be created.
component_database (dict) – The database of components which can be inheritted or child of the component type.
parameter_dictionary (dict) – A dictionary of parameters where the keys are the params_name in the component_database.
- Returns
A dictionary of the component, this is known as a skeleton.
- Return type
dict
- database(database_files: list) dict¶
Method for loading and merging a list of database files.
- Parameters
database_files (list) – List of jsons that will be loaded into the returned object.
- Returns
A dictionary of the merged jsons in the database_files.
- Return type
dict
- inherit(component: dict, parents: Dict[str, dict])¶
Adds inherited information to the skeleton.
This inherited information is important as there is it allows for some level of inheritance from within the jsons loaded i.e. a Brand of Car specified as an assembly in a supplied dictionary can inherit parameters, information and other data from Car if that is also supplied as a dictionary. It does this by looking for an inherits key.
- Parameters
component (dict) – The component which will be checked for an inherits key.
parents (dict) – All the components which will be searched for for the values given by the inherits key.
- merge_component_defined_with_skeleton(defined_in_component_database: dict, defined_on_child: dict) dict¶
Merges a dictionary of components defined on a child and within the parent[“skeleton”].
Information about a component can be defined on a child within the component dictionary or in a dictionary on the child key of a dictionary.
- Parameters
defined_in_component_database (dict) – Component dictionary within the component_database such as {breeder:{first:foo}}.
defined_on_child (dict) – Child dictionary within a component_dictionary such as {blanket:{children:breeder:second:bar}}.
- Returns
A merged dictionary for the component such as {breeder:{first:foo, second:bar}}.
- Return type
dict
- rm_inherits(item: dict)¶
Having inherit left after the inheritance has taken place means running on an already populated skeleton is challenging, so it has to be replaced with inherited.
- Parameters
item (dict) – Contains the component from with the inheritance will be removed.
- spine(component_ref: str, component_type: str, component_database: Dict[str, Dict])¶
Creates the basic part of the skeleton by populating the children.
- Parameters
component_ref (str) – The reference for the component which will be created.
component_type (str) – The type of component that will be created.
component_database (dict) – The database of components which contains all the parts.
bom_analysis.solver submodule¶
- class bom_analysis.solver.Solver¶
Bases:
BaseClassThe solver contains an ordered dictionary which should be made up of the steps that the analysis will go through. It can be populated manually or build from a settings file.
As with the engineering objects the solver can be written to a dictionary using the same method names.
- build_from_settings(settings: dict, assembly: EngineeringObject)¶
Builds the ordered dictionary by taking the required modules from the settings and defining json and building a class from string.
If the module settings call for a particular reference, and that reference is in the flattened assembly the solver will be provided with that part of the assembly. The solver initialises the module but does not run any functions outside the __init__.
- Parameters
settings (dict) – The settings for the build.
assembly (EngineeringObject) – The assembly which the buid will take place for.
- build_from_step_list(step_list: list)¶
Builds a run array from a list of steps.
- Parameters
step_list (list) – List of Step classes that will be ran in order.
- replace_with_comp(item: Union[dict, list, tuple, EngineeringObject], flat: dict) Union[dict, list, tuple, EngineeringObject]¶
Replaces a string with a component in the args/kwargs to allow dictionary/list to be supplied.
- Parameters
flat (dict) – Flattened components in BoM.
item (Union[dict, list, tuple, EngineeringObject]) – An instance which might contain the reference of a component.
- Returns
An instance with the reference replaced with the component the type of which is the same as the input.
- Return type
Union[dict, list, tuple, EngineeringObject]
- solve()¶
Solves the functions in the ordered dict.
- to_dict(exclusions: list = []) dict¶
Outputs the full dictionary of the solver Steps.
- Parameters
exclusions (list, optional) – Anything to be excluded from the dictionary by default [].
- Returns
The dictionary representing the sovler.
- Return type
dict
- update_args(module: dict, flat: dict)¶
Updates any args with the component if exists in flat.
- Parameters
flat (dict) – Flattened components in BoM.
module (dict) – Information about the module.
- update_kwargs(module: dict, flat: dict)¶
Updates any kwargs with the component if exists in flat.
- Parameters
flat (dict) – Flattened components in BoM.
module (dict) – Information about the module.
- class bom_analysis.solver.Step(class_object: type, method_str: str, *args, **kwargs)¶
Bases:
objectThe solver implemented in BOM Analysis is made up of a series of steps ran in linear order. Each step requires the class (not initialised) to be initialised, the method within the class that will be run plus and arguments or key word arguments. The solve function can then be run to execute the step.
- arg_to_str_list() list¶
Converts the input arguements to a list with any components being written as references instead of the object.
- Returns
A list of arguments.
- Return type
list
- kwarg_to_str_dict() dict¶
Converts the input keywords to a list with any components being written as references instead of the object.
- Returns
A list of dictionary of key words.
- Return type
dict
- property name: str¶
The name of the class defined within the step.
- Returns
String for the name in step class.
- Return type
str
- solve()¶
Solves the class within the step class and records the time taken for the step to solve in the run log.
- to_dict() dict¶
Returns a deifnition of the step to a dictionary.
- Returns
A dictionary defining the step.
- Return type
dict
bom_analysis.utils submodule¶
- class bom_analysis.utils.MaterialSelector¶
Bases:
objectThe MaterialSelector can select a material database based on a priority order and the availability of the material within the database. To perform this function the material selector should be supplied with the databases (generally children of the MaterialData class).
To add the databases to the material selector the add_database method can be used with the add order assumed to be the priority.
If the selector was provided a ASME materials database followed by a CoolProp database followed by a in-house database during setup, then the material for a component can be returned by the select_database method. Say the material is Beryllium, the MaterialSelector will check the ASME database, then the CoolProps, then the in-house until it finds (or not) Beryllium.
One of the benefits of using MaterialSelector (and storing it in the Configuration) is that when a material is not within one database the next can be checked as discussed in the MaterialData.
- add_database(database_class, additional_data: dict = {})¶
Adds a database to the prioritity order in the correct fromat.
- Parameters
database_class (MaterialData) – Class of material data.
additional_data (dict, optional) – Any additional data within will be added to the database_class.__dict__, by default {}.
- clear_database()¶
Clears the material databases within the materials selector.
- priority_order¶
An array contianing information about each of the material data class.
- Type
np.ndarray
- from_dict(data: dict)¶
Reads a dictionary and populates the MaterialSelector.
Resets the priority order so that the same MaterialData classes are not added numerous times.
- Parameters
data (dict) – A database with the information to form the MaterialSelector.
- intialised_database(material_str: Optional[str], database: dict)¶
Initialises a datbase class and sets the attributes from the extra data suplied.
- Parameters
material_str (str) – A string of the material name.
database (dict) – The database contiaing the class and extra data {material:class, data:extra data dict}.
- Returns
An initialised class, meant to be material data.
- Return type
Any
- old_style_from_dict(data: dict)¶
Older versions of settings files contain a non-object orientated materl priority order which can be imported by this method.
- Parameters
data (dict) – An old style dictionary containin an ‘order’ key.
- Raises
ValueError – If a class str has more that on class_str as it cannot inherit a single name.
- select_database(material_str: Optional[str])¶
Selects a material database from a material name.
- Parameters
material_str (str) – A string of the material name which will be checked within a database.
- Returns
An initialised database that has been found for a material_str.
- Return type
instance
- Raises
ValueError – If a database cannot be found.
- to_dict() dict¶
Converts the MaterialSelector to a dictionary.
Adds a set of class_str so the the priority order can be created from a string.
- Returns
A dictionary of the material selector.
- Return type
dict
- class bom_analysis.utils.PrintParamsTable¶
Bases:
object- format_params(list_of_params: list) list¶
Formats the dictionary representation of the parameters to allow for nice string represntation.
If being used in a terminal, the size will be checked to split the strings of the information in the parameter so that the output does not extend over multiple lines (and can be read). The in-built pint formater is used to convert the strings representing a unit (if supplied) to symbolic i.e. meter to m.
- Parameters
list_of_params (list) – A list of dictionaries with the _data parameters.
- Returns
A formated list of dictionaries with the _data parameters.
- Return type
list
- get_max_column_width(list_of_params: list) Optional[int]¶
Gets the maximum column size for printing of a tabular dataframe.
The maximum column size is important as it allows a string to be split over multiple lines and, therefore, displayed nicely.
- Parameters
list_of_params (list) – List of parameters that will be used to determine the maximum size of the columns in the print.
- Returns
int – The maximum column size for a given terminal width.
None – If an OSError is raised (due to no terminal) or an index error is raised (due to an empty input list).
- property header: Iterable¶
Property for the header of the table that will be printed.
- Returns
The header of the table to be printed.
- Return type
np.ndarray
- Raises
NotImplementedError – Not implemented in parent class.
- new_line_in_string(input: Any, max_character: Optional[int] = None) Any¶
Splits the input into multiple lines based on a supplied max character interger.
- Parameters
input (Any) – The parameter item to be split.
max_character (int, optional) – The maximum number of characters before adding the new line, by default None.
- Returns
The parameter item with the split accross new lines added.
- Return type
Any
- shorten_unit(quantity: Any) Any¶
Shortens the format of the units in a pint unit and returns as string.
- Parameters
quantity (Any) – Any input to be tried to have the units converted to symbolic via the format.
- Returns
String for quantity with shortened units.
- Return type
str
- class bom_analysis.utils.Translator(name: Optional[str], output_format: Optional[str])¶
Bases:
objectTranslating strings can be very important to a bill of materials and a workflow due to mismatches in the naming is common across material libraries (both the name and the parameters).
The translator can be defined from a dictionary and utilises classmethods so can be used without initialisation. After the underlying data has been populated, the input for translation can be supplied alongside the output format.
- classmethod available_inputs() list¶
Produces a list of all the input translations for the loaded translator.
- Returns
The input translations.
- Return type
list
- classmethod define_translations(locations: list)¶
Defines the translations for the class.
- Parameters
locations (list) – List of translation file locations.
- class bom_analysis.utils.UpdateDict(main: dict, *args, **kwargs)¶
Bases:
objectUpdating a dictionary with more control over than the inbuilt is important when parsing jsons to build the skeleton.
This function allows for that control.
- build()¶
Updates the main dictionary with the input attribute.
- unique_keys(input_tuple: tuple) Iterable¶
Defines the unique keys in all the input dict.
- Parameters
input_tuple (dict) – Tuple of input dictionaries.
- Returns
A dictionary of the input keys, a dictionary for legacy reasons.
- Return type
dict
- update_key(main: dict, key: Union[str, int], data: dict)¶
Updates the data in the main dictionary with a key.
- Parameters
main (dictionary) – The main dictionary which will be updated.
key (Union[str, int]) – The key in the main dictioanry which will have the value updated with data.
data (type) – The data which will be added to the main dict with key.
- Raises
ValueError – If data type in .locked is trying to be overwritten.
- update_main(main: dict, input_tuple: tuple)¶
Updates the main dictionary with the input dictionary.
- Parameters
input_dict (tuple) – A tuple of input dictionaries.
main (dictionary) – The main dictionary which will be updated.
- bom_analysis.utils.access_nested(obj: Any, location: Union[list, tuple], pos: int = 0)¶
Accesses data within a nested object by searching for attribute or item down a list/tuple/array.
- Parameters
obj (Any) – The object to be accessed.
location (Iterable) – The iterable location of the data.
pos (int, optional) – The position of the nested dictionary to be accessed, defaults to 0.
- Returns
data – The data which is returned.
- Return type
instance
- bom_analysis.utils.change_handler(new_path: str)¶
Changes the logging handler.
When running a parameter sweep, it is beneficial to have the log for a run in the output files of that run. This is done within bom_analysis by changing the logging handler path.
- Parameters
new_path (str) – The new path for the run log to be stored.
- bom_analysis.utils.class_factory(name, class_strings: list, class_data: dict = {}) Any¶
Method for dynamically creating classes.
The classes are specified as a list of strings within the class_strings. The class based on the string is created with type and initialised.
- Parameters
class_strings (list) – List of class strings.
data (class) – The data to be added as attributes to the created class.
- Returns
A new, initialised class created from the input class list and data.
- Return type
Any
- bom_analysis.utils.class_from_string(string: str) Any¶
Creates a class from a string in order to assign custom classes to a sub assembly.
- Parameters
string (str) – A string representing a class location.
- Returns
The uninitialised class corresoponding to the input string.
- Return type
Any
Note
The importlib must be supplied a package, if the class_str starts with .. .. allows for the module to specified and the code could be changed as follows: module = importlib.import_module(module_name, package=”.materials_model”).
- bom_analysis.utils.decoder(obj: Any) Any¶
Creates a consistance data type for strings, floats, ints and list.
The aim is to use numpy types throughout the bom_analysis - decoder helps ensure this standard format.
- Parameters
obj (type) – An instance to be converted into the standard bom format.
- Returns
An object in the standard bom format.
- Return type
type
Note
Does not return the string as pint converts to int or float The check to see if first value is a float to ensure, particularly mass being converted to milliarcsecond, does not convert pure strings to units.
- bom_analysis.utils.encoder(obj: Any) Any¶
An encoder to ensure all outputs are serialisable.
Could be turned into a json encoder but problems with all the data types with recursion.
- Parameters
obj (Any) – An instance of an object which will be converted to a serialisable if exist in list.
- Returns
The serialisable version of the input instance, if the type is specified in the list.
- Return type
Any
Note
See here for how to turn into a proper encoders.
- bom_analysis.utils.load_and_merge(location_list: list) dict¶
Merges multiple json dicts into a single dictionary.
This is used for when parsing jsons to build the skeleton. It allows a list of locations to be supplied within the settings or config.
- Parameters
location_list (list) – List of the locations of json which will be loaded and merged.
- Returns
merged – A merged dictionary of all the json in the location list.
- Return type
dict