The mvmlib API reference
Margin Value Method Library
A library based on the margin value method for computing design margins using fuzzy logic and probabilistic methods for uncertainty modelling
The “DOELib” module
- mvm.DOELib.get_design(name: str) Design
returns an a Design object initialized using the input folder
- Parameters:
file (str) – the folder name to be used to load the data which includes * settings.json * scale.csv * unscale.csv
- mvm.DOELib.gridsamp(bounds: ndarray, q: int | ndarray | List[int]) ndarray
GRIDSAMP n-dimensional grid over given range
- Parameters:
bounds (np.ndarray) – 2*n matrix with lower and upper limits
q (np.ndarray) – n-vector, q(j) is the number of points in the j’th direction. If q is a scalar, then all q(j) = q
- Returns:
S – m*n array with points, m = prod(q)
- Return type:
np.ndarray
- mvm.DOELib.scaling(x: ndarray, lb: ndarray, ub: ndarray, operation: int) ndarray
Scaling by a range
- Parameters:
x (np.ndarray) – 2d array of size n * nsamples of datapoints
lb (np.ndarray) – 1d array of length n specifying lower range of features
ub (np.ndarray) – 1d array of length n = len(l) specifying upper range of features
operation (int) – The flag type indicates whether to scale (1) or unscale (2)
- Returns:
x_out – 2d array of size n * nsamples of unscaled datapoints
- Return type:
np.ndarray
- class mvm.DOELib.Design(lb: ndarray, ub: ndarray, nsamples: int | List[int] | ndarray, doe_type: str, random_seed: int | None = None)
Contains the experimental design limits, samples and other relevant statistics
- Parameters:
lb (np.ndarray) – 1d array of length n specifying lower range of features
ub (np.ndarray) – 1d array of length n = len(lb) specifying upper range of features
nsamples (Union[int,List[int],np.ndarray]) – The number of samples to generate for each factor, if array_like and type specificed is ‘fullfact’ then samples each variable according to its sampling vector
doe_type (str, optional) – Allowable values are “LHS” and “fullfact”. If no value given, the design is simply randomized.
random_seed (str, optional) – random seed for initializing LHS DOE. Does not affect ‘fullfact’ DOE’s If no value given then results are not reproducible
design_matrix (str, optional) – use the provided design_matrix instead of the one generated initially
TODO (#) –
- property design: ndarray
used to return a copy of the design matrix
- Returns:
copy of design matrix
- Return type:
np.ndarray
- load(name: str) None
loads the state of the DOE from a text file
- Parameters:
file (str) – the folder name to be used to load the data which includes * settings.json * scale.csv * unscale.csv
- save(name: str) None
saves the state of the DOE to a text file
- Parameters:
file (str) – the folder name to be used to save the data which includes * settings.json * scale.csv * unscale.csv
- scale() ndarray
return scaled latin hypercube between 0 and 1
- Returns:
scaled_LH – numpy array of size n * nsamples of LH values between 0 and 1
- Return type:
np.array
- unscale() ndarray
Unscale latin hypercube by ub and lb
- Returns:
unscaled_LH – numpy array of size n * nsamples of LH values unscaled by lb and ub
- Return type:
np.array
The “fuzzyLib” module
- class mvm.fuzzyLib.TriangularFunc(universe: ndarray, label: str = '')
Contains description and implementation of different fuzzy membership functions
- Parameters:
universe (np.ndarray) – 1d array of length n n=number of samples
label (str, optional) – string to tag instance with, by default ‘’
- get_array() ndarray
Sample an array of values from membership function
- Returns:
array – 1d array of length universe
- Return type:
np.ndarray
- interp(input_x: float | ndarray | None = None) float | ndarray
Interpret membership of input for fuzzy function
- Parameters:
input_x (Union[float,np.ndarray], optional) – value(s) at which membership is to be interpreted, by default None
- Returns:
level – interpreted membership level(s) of the input(s)
- Return type:
Union[float,np.ndarray]
- set_func(low: int, medium: int, high: int)
Create an instance of the triangular membership function
- Parameters:
low (int) – left foot of triangle
medium (int) – peak of triangle
high (int) – right foot of triangle
- class mvm.fuzzyLib.FuzzyRule(input_statements: List[Dict[str, FuzzyFunction | TriangularFunc]], output: FuzzyFunction | TriangularFunc, label: str = '')
Defines a fuzzy rules by connecting fuzzy inputs to outputs
- Parameters:
input_statements (List[Dict[str, Union[FuzzyFunction,TriangularFunc]]]) –
list of dicts, structure of each dict {
‘fun1’: FuzzyFunction OR TriangularFunc object
’fun2’: FuzzyFunction OR TriangularFunc object
operator: ‘AND’, ‘OR’
}
output (Union[FuzzyFunction,TriangularFunc]) – output fuzzy set
label (str, optional) – string to tag instance with
- apply(inputs: ndarray) ndarray
Apply rule on fuzzy sets
- Parameters:
inputs (np.ndarray) – pair(s) of values to be evaluated by rule
- Returns:
activation – 2d array with dimensions = len inputs * length universe holding activation function values
- Return type:
np.ndarray
- class mvm.fuzzyLib.FuzzySet(lo: TriangularFunc | FuzzyFunction, md: TriangularFunc | FuzzyFunction, hi: TriangularFunc | FuzzyFunction, label: str = '')
Contains all fuzzy functions describing the low, medium, and high level membership functions
- Parameters:
lo (Union[TriangularFunc,FuzzyFunction]) – low instance of fuzzyFunction class
md (Union[TriangularFunc,FuzzyFunction]) – medium instance of fuzzyFunction class
hi (Union[TriangularFunc,FuzzyFunction]) – high instance of fuzzyFunction class
label (str, optional) – string to tag instance with
- interp(inputs: float | ndarray) Tuple[float | ndarray, float | ndarray, float | ndarray]
Interpret membership of input
- Parameters:
inputs (float OR np.ndarray) – The input(s) at which membership is to be interpreted
- Returns:
level_lo (float OR np.ndarray) – The interpreted membership to the low membership function of the input(s)
level_md (float OR np.ndarray) – The interpreted membership to the medium membership function of the input(s)
level_hi (float OR np.ndarray) – The interpreted membership to the high membership function of the input(s)
- set_label(label: str)
Changes label property of fuzzy set and all its membership functions
- Parameters:
label (float) – new label name
- view()
Used to view the distribution of all associated membership functions
- class mvm.fuzzyLib.FuzzySystem(antecedents: List[FuzzySet], consequent: FuzzySet, rules: List[FuzzyRule], label: str = '')
Contains all fuzzy inputs, outputs, rules, and fuzzy logic interpreter
- Parameters:
- compute(inputs: ndarray, normalize: bool = False) Tuple[float | ndarray, ndarray, ndarray]
Compute fuzzy output of system
- Parameters:
inputs (np.ndarray) – 2d Array of inputs of shape [n, n_inputs] n = number of data points to be computed and n_inputs = len(antecedents)
normalize (bool, optional) – if True normalize aggregate output by area
- Returns:
output (float OR np.1darray) – defuzzified crisp value(s)
aggregate (np.ndarray) – array of shape [n, len universe] n = number of data points in the input len universe = len(self.universe)
output_activation (np.1darray) – activation values(s) for defuzzified output
- reset()
Resets intermediate aggregate membership function to zeros
- view()
View the aggregate membership function on the universe
The “uncertaintyLib” module
- mvm.uncertaintyLib.compute_cdf(values: ndarray, bins: int = 500, cutoff: float | None = None, buffer_limit: float | None = None)
Calculate the cumulative distribution function for the excess margin
- Parameters:
values (np.ndarray) – Values to construct cumulative pdf from
bins (int, optional) – number of discrete bins used to construct pdf and pdf curves, by default 500
cutoff (float, optional) – cutoff limit for calculating reliability, by default None
buffer_limit (float, optional) – lower bound for beginning of buffer zone, by default None
- Returns:
values (np.ndarray) – vector of value samples to use for computing the cdf
bin_centers (np.ndarray) – array of len(value) - 1 containing the x-axis values of CDF
cdf (np.ndarray) – array of len(value) - 1 containing the y-axis values of CDF
- Raises:
AssertionError – if only one of cutoff or buffer_limit is provided
- mvm.uncertaintyLib.moving_average(i: ndarray, w: ndarray) ndarray
N-moving average over 1D array
- Parameters:
i (np.ndarray) – input array to average
w (int) – number of elements to average
- Returns:
avaeraged array
- Return type:
np.ndarray
- class mvm.uncertaintyLib.GaussianFunc(mu: float | int | ndarray, sigma: float | int | ndarray, label='')
Contains description and implementation of the multivariate Gaussian PDF
- Parameters:
mu (np.ndarray) – 1d array of length n_dims containing means
sigma (np.ndarray) – 1d array of length n_dims containing standard deviations OR 2d array of length n_dims * n_dims containing standard deviations and covariances
label (str, optional) – string to tag instance with
- compute_density(samples)
Return the multivariate Gaussian probability density distribution on array samples.
- Parameters:
samples (np.ndarray) – array of shape n_samples * n_dims at which PDF will be evaluated
- Returns:
z – array of shape n_samples of PDF values
- Return type:
np.ndarray
- compute_density_r(r=3)
Returns the value of probability density at given Mahalanobis distance r
- Parameters:
r (float) – corresponds to Mahalanobis distance r for hyperellipsoids r = 1 —> 1 sigma r = 2 —> 2 sigma r = 3 —> 3 sigma
- Returns:
p – probability density at Mahalanobis distance r
- Return type:
float
- compute_volume(r=3)
The volume of the ellipsoid (x-mu)T.Sigma-1.(x-mu) = r This is the output of this method.
- Parameters:
r (float) – corresponds to Mahalanobis distance r for hyperellipsoids r = 1 —> 1 sigma r = 2 —> 2 sigma r = 3 —> 3 sigma
- Returns:
V – volume of hyperellipsoid for Mahalanobis distance r
- Return type:
float
- property eigvals
Returns the eigen values of the covariance matrix
- Returns:
eigen values
- Return type:
np.ndarray
- property ndim
Returns the number of dimensions from the input data
- Returns:
number of dimensions
- Return type:
int
- view(xlabel='', savefile=None)
view 1D or 2D plot of distribution for visual checks
- Parameters:
xlabel (str, optional) – variable names to be shown on plot axes, by default ‘’
savefile (str, optional) – if provided saves an image of the figure in directory /images/self.label/, by default None
- Raises:
ValueError – if called when ndim is > 2
- class mvm.uncertaintyLib.Distribution(pdf: ndarray, lb=-1, ub=1, sort=True, interpolation=True, label='')
Draws samples from a one dimensional probability distribution, by means of inversion of a discrete inversion of a cumulative density function, the PDF can be sorted first to prevent numerical error in the cumulative sum this is set as default; for big density functions with high contrast, it is absolutely necessary, and for small density functions, the overhead is minimal, a call to this distribution object returns indices into density array, borrowed from: https://stackoverflow.com/a/21101584
- Parameters:
pdf (np.ndarray) – 2d-array of shape n_samples * n_dims including sample density values throughout the real or discrete space
lb (np.ndarray OR float OR int, optional) – The lower bound for the pdf support, default = -1
ub (np.ndarray OR float OR int, optional) – The uppoer bound for the pdf support, default = 1
sort (bool, optional) – if True sort pdf to avoid interpolation errors when evaluating from cdf, by default True
interpolation (bool, optional) – If true, treats input density values as coming from a piecewise continuous distribution If false, then a discrete distribution is assumed, by default True
label (str, optional) – string to tag instance with
- property cdf
construct the cumulative distribution function
- Returns:
vector of cumilative distribution
- Return type:
np.ndarray
- property lb
Returns the lower bound of the pdf supports
- Returns:
lower pdf supports
- Return type:
np.ndarray
- property ndim
Returns the number of dimensions from the input data
- Returns:
number of dimensions
- Return type:
int
- property pdf
Returns pdf values
- Returns:
array of pdf values
- Return type:
np.ndarray OR np.ndarray
- random(n=1)
draw random samples from PDF
- Parameters:
n (int, optional) – Number of random samples to draw default is one sample
- Returns:
A 2D array of shape ndim * N, where N is the number of requested samples
- Return type:
np.ndarray
- reset()
Resets the stored samples
- property samples: ndarray
Sample vector getter
- Returns:
vector of sample observations
- Return type:
np.ndarray
- property sum
cached sum of all PDF values; the PDF need not sum to one, and is implicitly normalized
- Returns:
sum of all PDF values
- Return type:
float
- transform(i)
Transform discrete integer choices when sampling to their continues real valued random variable samples
- Parameters:
np.ndarray – Array of indices of shape ndim * N, where N is the number of samples
- Returns:
Array of transformed indices of same shape as input i
- Return type:
np.ndarray
- property ub
Returns the upper bound of the pdf supports
- Returns:
upper pdf supports
- Return type:
np.ndarray
- view(xlabel='', savefile=None)
view 1D or 2D plot of distribution for visual checks
- Parameters:
xlabel (str, optional) – variable names to be shown on plot axes, by default ‘’
savefile (str, optional) – if provided saves an image of the figure in directory /images/self.label/, by default None
- Raises:
ValueError – if called when ndim is > 2
- class mvm.uncertaintyLib.VisualizeDist(values: ndarray, cutoff: float | None = None, buffer_limit: float | None = None)
Contains PDF and CDF visualization tools
- Parameters:
values (np.ndarray) – vector of sample observations whose PDF is to be visualized using a histogram
cutoff (float, optional) – cutoff limit for calculating reliability, by default None
buffer_limit (float, optional) – lower bound for beginning of buffer zone, by default None
- view(xlabel: str = '', folder: str = '', file: str | None = None, img_format: str = 'pdf', bins: int | List[int | float | str] = 100, bar_width: float = 1.0)
view 1D or 2D plot of probability distribution of value
- Parameters:
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
bins (Union[int,List[Union[int,float,str]]], optional) – bins to show, by default 100
bar_width (float, optional) – relative width of histogram bars, by default 1.0
- view_cdf(xlabel: str = '', folder: str = '', file: str | None = None, img_format: str = 'pdf')
view 1D or 2D plot of probability distribution of value
- Parameters:
xlabel (str, optional) – the xlabel to display on the plot, by default ‘’
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
The “designMargins” module
- class mvm.designMarginsLib.Cache(key: str, dims: List[int])
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
- reset(n: int)
Resets accumulated random observations and value distributions
- Parameters:
n (int, optional) – if provided deletes only the last n_samples, by default None
- class mvm.designMarginsLib.InputSpec(value: float | int, key: str, universe: List[int | float], variable_type: str, description: str = '', symbol: str = '', distribution: Distribution | GaussianFunc | UniformFunc | None = None, cov_index: int = 0, inc: float = 5.0, inc_type: str = 'rel')
Contains description of an input specification could deterministic or stochastic
- Parameters:
value (Union[float,int]) – the value of the input spec
key (str) – unique identifier
universe (List[Union[int, float]]) – the possible values the design parameter can take, must be of length 2 (upper and lower bound) type(value) must be float or int
variable_type (str) – type of variable, possible values are ‘INT’, ‘FLOAT’
description (str, optional) – description string, by default ‘’
symbol (str, optional) – shorthand symbol, by default ‘’
distribution (Union[Distribution, GaussianFunc, UniformFunc], optional) – if a Distribution object is provided, then the spec can sampled by calling it Example: >>> from mvm import InputSpec, GaussianFunc >>> dist = GaussianFunc(1.0, 0.1) >>> s1 = InputSpec(1.0, ‘S1’, [0.0, 1.0], ‘FLOAT’, distribution=dist) >>> sample = s1.random()
cov_index (int, optional) – which random variable to draw from if multivariate distribution is provided, by default 0
inc (float, optional) – The value by which to increment the input specification during deterioration calculation (can be negative), by default 5.0
inc_type (str, optional) – possible values (‘rel’,’abs’) if ‘rel’ then the increment is multiplied by the nominal value, if ‘abs’ then the increment is applied directly on the input spec, by default ‘rel’
- property inc: float
returns the adjusted change increment value for the input specification
- Returns:
value of adjusted input specification change increments
- Return type:
float
- random(n: int = 1) ndarray
draw random samples from value
- Parameters:
n (int, optional) – Number of random samples to draw default is one sample
- Returns:
A 1D array of size N, where N is the number of requested samples
- Return type:
np.ndarray
- reset(n: int | str | None = None)
Resets accumulated random observations and value distributions
- Parameters:
n (Union[int,str], optional) – if provided deletes only the last n_samples and resets specs to original nominal value, if the string ‘all’ is provided deletes all samples and resets specs to original nominal value, if None is provied resets specs to original nominal value only, by default None
- class mvm.designMarginsLib.MatrixParam(key: str, dims: List[int])
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
- property values: ndarray
Impact 3D matrix getter
- Returns:
vector of matrix observations
- Return type:
np.ndarray
- view(row: int, col: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired matrix element
- Parameters:
row (int) – index of the row of matrix
col (int) – index of the column of matrix
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- view_cdf(row: int, col: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired matrix element
- Parameters:
row (int) – index of the row of matrix
col (int) – index of the column of matrix
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- class mvm.designMarginsLib.ParamFactory
Constructs different parameters based on given dimensions
- static build_param(key: str, dims: List[int], datatype: str = 'continuous') ScalarParam | VectorParam | MatrixParam
Returns appropriate parameter class based on supplied dimensions
- Parameters:
key (str) – unique string identifier
dims (List[int]) – The dimensions of the parameter
datatype (str, optional) – The type of values being stored, possible values : {‘continuous’, ‘categorical’}, by default ‘categorical’
- Returns:
an instance of the correct class
- Return type:
Union[ScalarParam,VectorParam,MatrixParam]
- class mvm.designMarginsLib.Performance(key: str = '', direction: str = 'less_is_better')
Contains all the necessary tools to calculate performance and store its values if there is stochasticity
- Parameters:
key (str, optional) – string to tag instance with, default = ‘’
direction (str, optional) – specifies the sign of the performance parameter when calculating the impact on it, possible values: (‘less_is_better’,’more_is_better’), if more_is_better is selected then the sign is negative, of less_is_better is selected then the sign is positive, by default = ‘less_is_better’
- class mvm.designMarginsLib.ScalarParam(key: str, dims: List[int], datatype: str = 'continuous')
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
datatype (str, optional) – The type of values being stored, possible values : {‘continuous’, ‘categorical’}, by default ‘categorical’
- property value_dist: Distribution
Value Distribution object
- Returns:
instance of Distribution holding value pdf
- Return type:
- property values: ndarray
value vector getter
- Returns:
vector of observations
- Return type:
np.ndarray
- view(xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf', bins: List[int | float | str] | None = None)
Views the distribution of the parameter
- Parameters:
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
bins (List[Union[int,float,str]], optional) – bins to show, by default None
- view_cdf(xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the cumulative distribution of the parameter
- Parameters:
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- class mvm.designMarginsLib.VectorParam(key: str, dims: List[int])
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
- property values: ndarray
Impact 3D matrix getter
- Returns:
vector of matrix observations
- Return type:
np.ndarray
- view(row: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired vector component
- Parameters:
row (int) – index of the row of vector
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- view_cdf(row: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired vector component
- Parameters:
row (int) – index of the row of vector
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- mvm.designMarginsLib.nearest(p1: ndarray, p2: ndarray, s: ndarray) Tuple[ndarray, float]
Find the nearest point to s along a line given by p1 and p2 https://stackoverflow.com/a/47198877 https://stackoverflow.com/a/39840218 https://math.stackexchange.com/questions/13176/how-to-find-a-point-on-a-line-closest-to-another-given-point
- Parameters:
p1 (np.ndarray) – first point on the line
p2 (np.ndarray) – second point on the line
s (np.ndarray) – point to calculate distance to
- Returns:
coordinates of the nearest point
- Return type:
np.ndarray
- class mvm.designMarginsLib.ScalarParam(key: str, dims: List[int], datatype: str = 'continuous')
Bases:
Cache
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
datatype (str, optional) – The type of values being stored, possible values : {‘continuous’, ‘categorical’}, by default ‘categorical’
- property value_dist: Distribution
Value Distribution object
- Returns:
instance of Distribution holding value pdf
- Return type:
- property values: ndarray
value vector getter
- Returns:
vector of observations
- Return type:
np.ndarray
- view(xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf', bins: List[int | float | str] | None = None)
Views the distribution of the parameter
- Parameters:
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
bins (List[Union[int,float,str]], optional) – bins to show, by default None
- view_cdf(xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the cumulative distribution of the parameter
- Parameters:
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- class mvm.designMarginsLib.VectorParam(key: str, dims: List[int])
Bases:
Cache
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
- property values: ndarray
Impact 3D matrix getter
- Returns:
vector of matrix observations
- Return type:
np.ndarray
- view(row: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired vector component
- Parameters:
row (int) – index of the row of vector
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- view_cdf(row: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired vector component
- Parameters:
row (int) – index of the row of vector
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- class mvm.designMarginsLib.MatrixParam(key: str, dims: List[int])
Bases:
Cache
Stores observations data. This class is an attribute of the MarginNetwork class, Cache subclasses are instantiated by the MarginNetwork class during its initialization
- Parameters:
key (str) – unique identifier
dims (List[int]) – The dimension along each axis (if empty then a float is assumed)
- property values: ndarray
Impact 3D matrix getter
- Returns:
vector of matrix observations
- Return type:
np.ndarray
- view(row: int, col: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired matrix element
- Parameters:
row (int) – index of the row of matrix
col (int) – index of the column of matrix
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- view_cdf(row: int, col: int, xlabel: str | None = None, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Views the distribution of the desired matrix element
- Parameters:
row (int) – index of the row of matrix
col (int) – index of the column of matrix
xlabel (str, optional) – axis label of value , if not provided uses the key of the object, by default None
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’
- class mvm.designMarginsLib.FixedParam(value: float | int | str, key: str, description: str = '', symbol: str = '')
Contains description of an input parameter to the MAN
- Parameters:
value (Union[float,int,str]) – the value of the input spec
key (str) – unique identifier
description (str, optional) – description string, by default ‘’
symbol (str, optional) – shorthand symbol, by default ‘’
- class mvm.designMarginsLib.DesignParam(value: float | int | str, key: str, universe: List[int | float], variable_type: str, description: str = '', symbol: str = '')
Contains description of an input parameter to the MAN is inherited by DesignParam, and FixedParam
- Parameters:
value (Union[float,int,str]) – the value of the input spec
key (str) – unique identifier
universe (List[Union[int, float]]) – the possible values the design parameter can take, must be of length 2 (upper and lower bound) type(value) must be float, or int
variable_type (str) – type of variable, possible values are ‘INT’, ‘FLOAT’
description (str, optional) – description string, by default ‘’
symbol (str, optional) – shorthand symbol, by default ‘’
- reset()
resets the design parameters to its initial value given at __init__
- class mvm.designMarginsLib.InputSpec(value: float | int, key: str, universe: List[int | float], variable_type: str, description: str = '', symbol: str = '', distribution: Distribution | GaussianFunc | UniformFunc | None = None, cov_index: int = 0, inc: float = 5.0, inc_type: str = 'rel')
Bases:
ScalarParam
Contains description of an input specification could deterministic or stochastic
- Parameters:
value (Union[float,int]) – the value of the input spec
key (str) – unique identifier
universe (List[Union[int, float]]) – the possible values the design parameter can take, must be of length 2 (upper and lower bound) type(value) must be float or int
variable_type (str) – type of variable, possible values are ‘INT’, ‘FLOAT’
description (str, optional) – description string, by default ‘’
symbol (str, optional) – shorthand symbol, by default ‘’
distribution (Union[Distribution, GaussianFunc, UniformFunc], optional) – if a Distribution object is provided, then the spec can sampled by calling it Example: >>> from mvm import InputSpec, GaussianFunc >>> dist = GaussianFunc(1.0, 0.1) >>> s1 = InputSpec(1.0, ‘S1’, [0.0, 1.0], ‘FLOAT’, distribution=dist) >>> sample = s1.random()
cov_index (int, optional) – which random variable to draw from if multivariate distribution is provided, by default 0
inc (float, optional) – The value by which to increment the input specification during deterioration calculation (can be negative), by default 5.0
inc_type (str, optional) – possible values (‘rel’,’abs’) if ‘rel’ then the increment is multiplied by the nominal value, if ‘abs’ then the increment is applied directly on the input spec, by default ‘rel’
- property inc: float
returns the adjusted change increment value for the input specification
- Returns:
value of adjusted input specification change increments
- Return type:
float
- random(n: int = 1) ndarray
draw random samples from value
- Parameters:
n (int, optional) – Number of random samples to draw default is one sample
- Returns:
A 1D array of size N, where N is the number of requested samples
- Return type:
np.ndarray
- reset(n: int | str | None = None)
Resets accumulated random observations and value distributions
- Parameters:
n (Union[int,str], optional) – if provided deletes only the last n_samples and resets specs to original nominal value, if the string ‘all’ is provided deletes all samples and resets specs to original nominal value, if None is provied resets specs to original nominal value only, by default None
- class mvm.designMarginsLib.Behaviour(n_i: int, n_p: int, n_dv: int, n_tt: int, key: str = '')
- This class stores the method for calculating its outputs
Intermediate parameters
Performance parameters
Decided values
target thresholds
- Parameters:
n_i (int) – number of intermediate parameters
n_p (int) – number of performance parameters
n_dv (int) – number of decided values
n_tt (int) – number of target threshold
key (str, optional) – string to tag instance with, default = ‘’
- property decided_value: float | List[float]
decided_value parameters getter
- Returns:
vector of decided_value parameters
- Return type:
np.ndarray
- property intermediate: float | List[float]
intermediate parameters getter
- Returns:
vector of intermediate parameters
- Return type:
Union[float,List[float]]
- inv_call(decided_value: float, *args)
The function that will be used to calculate the decided values based on a selected variable This method must be redefined by the user for every instance, otherwise a surrogate is used if the user has used the
train_surrogate
method earlier- Parameters:
decided_value (float) – the decided value to invert
Example
>>> # [in the plugin file] >>> from mvm import Behaviour >>> class MyBehaviour(Behaviour): >>> def inv_call(self,decided_value,r): >>> # some specific model-dependent behaviour >>> self.intermediate = decided_value >>> self.inverted = r**2
- property inverted: float | List[float]
inverted parameters getter
- Returns:
vector of inverted parameters
- Return type:
np.ndarray
- load(filename='man')
loads the Behaviour’s surrogate model and samples Performance surrogate and decision univere Saves any stored matrices
- Parameters:
filename (str, optional) – basefile path, by default ‘man’
- property performance: float | List[float]
performance parameters getter
- Returns:
vector of performance parameters
- Return type:
np.ndarray
- reset()
Resets the stored variables
- save(filename='man')
saves the Behaviour’s surrogate model and samples Performance surrogate and decision univere Saves any stored matrices
- Parameters:
filename (str, optional) – basefile path, by default ‘man’
- property threshold: float | List[float]
threshold parameters getter
- Returns:
vector of threshold parameters
- Return type:
np.ndarray
- train_inverse(key: str | None = None, bandwidth: List[float] = [0.01], sm_type: float = 'KRG')
trains a surrogate model to invert decided values back to a chosen input variable and the intermediate parameters surrogate model returns an array of shape [n_samples , (optional variables + n_intermediate) ] the inputs are [n_samples , (decided value + other arguments) ]
- Parameters:
key (str) – unique key string for the variable to be inverted
bandwidth (List[float], optional) – bandwidth of the correlation function used by Kriging, by default [0.01]
sm_type (str, optional) – type of surrogate model to train, possible values [‘KRG’,’LS’], by default ‘KRG’
- train_surrogate(variable_dict: Dict[str, Dict[str, Tuple[int, int] | Tuple[float, float] | List[str] | str]], n_samples: int, bandwidth: List[float] = [0.01], num_threads: int = 1, sm_type: float = 'KRG', random_state: int | RandomState | None = None, *args, **kwargs)
trains a Kriging surrogate model of the behaviour model to make computations less expensive surrogate model returns an array of shape [n_samples , (n_intermediate + n_performance + n_decided_value + n_target_threshold) ] the inputs are [n_samples , other arguments ]
- Parameters:
variable_dict (Dict[str, Dict[str,Union[Tuple[int,int], Tuple[float,float], List[str], str]] ]) – A dictionary with the input variables as keys and their corresponding type (‘INT’,’FLOAT’,’ENUM’) and their limits a tuple pair for the upper and lower limits or a list of ints or strings for ENUM variables
n_samples (int) – number of samples drawn from the behaviour model for training
bandwidth (List[float], optional) – bandwidth of the correlation function used by Kriging, by default [0.01]
sm_type (str, optional) – type of surrogate model to train, possible values [‘KRG’,’LS’], by default ‘KRG’
num_threads (int, optional) – number of threads to parallelize sampling the training data by, by default 1
random_state (Union[int,np.random.RandomState], optional) – Random seed or random generator instance used to generate training samples, If None is provided a random seed is used, by default None
- class mvm.designMarginsLib.Performance(key: str = '', direction: str = 'less_is_better')
Bases:
ScalarParam
Contains all the necessary tools to calculate performance and store its values if there is stochasticity
- Parameters:
key (str, optional) – string to tag instance with, default = ‘’
direction (str, optional) – specifies the sign of the performance parameter when calculating the impact on it, possible values: (‘less_is_better’,’more_is_better’), if more_is_better is selected then the sign is negative, of less_is_better is selected then the sign is positive, by default = ‘less_is_better’
- class mvm.designMarginsLib.MarginNode(key: str = '', cutoff: float = 0.9, buffer_limit: float = 0.0, direction: str = 'must_exceed')
Contains description and implementation of a Margin Node object which is the building block of a Margin Analysis Network (MAN)
- Parameters:
key (str, optional) – string to tag instance with, default = ‘’
cutoff (float, optional) – cutoff limit for calculating reliability, default = 0.9
buffer_limit (float, optional) – lower bound for beginning of buffer zone, default = 0.0
direction (str, optional) – possible values(‘must_exceed’,’must_not_exceed’), by default ‘must_exceed’
- load(filename='man')
loads the MarginNode’s stored matrices
- Parameters:
filename (str, optional) – basefile path, by default ‘man’
- reset(n: int | None = None)
Resets accumulated random observations in target, decided value, and excess attributes
- Parameters:
n (int, optional) – if provided deletes only the last n_samples, by default None
- save(filename: str = 'man')
saves the MarginNode’s stored matrices
- Parameters:
filename (str, optional) – basefile path, by default ‘man’
- class mvm.designMarginsLib.MarginNetwork(design_params: List[DesignParam], input_specs: List[InputSpec], fixed_params: List[FixedParam], behaviours: List[Behaviour], decisions: List[Decision], margin_nodes: List[MarginNode], performances: List[Performance], key: str = '')
The function that will be used to calculate a forward pass of the MAN and associated metrics of the MVM - The first metric is change absorption capability (CAC) - The second metric is the impact on performance (IoP) This class should be inherited and the forward method should be implemented by the user to describe how the input params are related to the output params (DDs,TTs, and performances)
- Parameters:
design_params (List[DesignParam]) – list of DesignParam instances
input_specs (List[InputSpec]) – list of InputSpec instances
fixed_params (List[FixedParam]) – list of FixedParam instances
behaviours (List[Behaviour]) – list of Behaviour instances
decisions (List[Decision]) – list of Decision instances
margin_nodes (List[Performance]) – list of MarginNode instances
margin_nodes – list of Performance instances
distributions (List[Distribution]) – list of Distribution instances
key (str, optional) – string to tag instance with, default = ‘’
- allocate_margins(strategy: str | List[str] = 'min_excess')
allocates MAN margins according to some strategy
- Parameters:
strategy (Union[str,List[str]], optional) – Can be of value ‘min_excess’, ‘manual’ or a list of strings corresponding to each margin node. If ‘manual’, the self.decision_vector must be defined earlier. If a single string is provided all margin nodes are allocated identically, by default ‘min_excess’
- compute_absorption(num_threads: int = 1, recalculate: bool = True, method: str = 'fixed', max_iter: int = 100, **kwargs)
Computes the change absorption capability (CAC) matrix of the MVM that has a size [n_margins, n_input_specs] and appends its absorption matrix if called multiple times without a reset(). Also stores and appends the deterioration vectors
- Parameters:
num_threads (int, optional) – number of threads to parallelize sampling process, by default 1
recalculate (bool, optional) – Does not recompute the specification limits or the initial decision vector
method (bool, optional) – root finding algorithm to use, possible values [‘fixed’,’secant’], by default ‘secant’
max_iter (int, optional) – maximum number of iterations to use during root finding, by default 100
- compute_impact(use_estimate: bool = False)
Computes the impact on performance (IoP) matrix of the MVM that has a size [n_margins, n_performances] and appends its impact matrix if called multiple times without a reset(). Must be called after executing at least one forward() pass
- Parameters:
use_estimate (bool, optional) – uses the trained surrogate model from train_performance_surrogate to estimate performance at the threshold design, by default False
- compute_mvp(plot_type: str = 'scatter', show_neutral=False) float
computes the margin value map after running all Monte Carlo computations
- Parameters:
plot_type (str, optional) – possible values are (‘scatter’,’mean’,’density’) if ‘scatter’ is selected, simply plots all the sample absorptions and impacts, if ‘mean’ is selected, plots all the mean of all sample absorptions and impacts, if ‘density’ is selected, plots a Gaussian KDE of the sample absorptions and impacts, by default True
show_neutral (bool, optional) – If true displays the distance from the mean and the neutral 45 deg line
- Returns:
The aggregate distance from the neutral line
- Return type:
float
- property decision_vector: List[int | str]
returns a vector of decisions
- Returns:
List of decisions
- Return type:
List[Union[str, int]]
- property design_vector: ndarray
returns a vector of design parameters
- Returns:
vector of design parameters
- Return type:
np.ndarray
- property dv_vector: ndarray
decided value vector getter
- Returns:
vector of decided values
- Return type:
np.ndarray
- property excess_vector: ndarray
excess vector getter
- Returns:
vector of excesses
- Return type:
np.ndarray
- abstract forward(*args, **kwargs)
The function that will be used to calculate a forward pass of the MAN (design_params,input_specs,fixed_params) -> (excess,performance) This method must be redefined by the user for every instance
Example
>>> # [in the plugin file] >>> from mvm import MarginNetwork >>> class MyMarginNetwork(MarginNetwork): >>> def randomize(self): >>> pass >>> def forward(self,num_threads=1,recalculate_decisions=False,allocate_margin=False): >>> # some specific model-dependent behaviour >>> d1 = self.design_params[0] >>> s1 = self.input_specs[0] >>> p1 = self.fixed_params[0] >>> b1 = self.behaviours[0] >>> b2 = self.behaviours[1] # dependant on b1 >>> e1 = self.margin_nodes[0] >>> # Execution behaviour models >>> b1(d1.value,p1.value) >>> b2(d1.value,b1.intermediate) >>> e1(b2.decided_value,s1.random())
- init_decisions(num_threads: int = 1)
Calculates and stores the decided values of all decision nodes in the MAN
- Parameters:
num_threads (int, optional) – number of threads to parallelize sampling process, by default 1
- load(filename: str = 'man', folder: str = '/', results_only: bool = False)
loads the initial state of the MarginNetwork: Performance surrogate and decision univere loads any stored matrices
- Parameters:
filename (str, optional) – prefix before loaded files, by default ‘man’
folder (str, optional) – basefile path, by default is current directory
results_only (bool, optional) – if True only loads results related objects such as margin nodes, input specs, performances, and impact and absorption matrices, by default False
- property nominal_design_vector: ndarray
returns a vector of nominal design parameter
- Returns:
vector of nominal design parameters
- Return type:
np.ndarray
- property nominal_spec_vector: ndarray
returns a vector of nominal input specifications
- Returns:
vector of nominal input specifications
- Return type:
np.ndarray
- property perf_signs: ndarray
returns a vector of disarable performance directions
- Returns:
vector of disarable performance directions
- Return type:
np.ndarray
- property perf_vector: ndarray
performance parameter vector getter
- Returns:
vector of performance parameters
- Return type:
np.ndarray
- abstract randomize(*args, **kwargs)
The function that will be used to randomize the MAN. Include all random distribution objects here and have them draw samples by calling them. See example below
Example
>>> # [in the plugin file] >>> from mvm import MarginNetwork, InputSpec, GaussianFunc >>> dist_1 = GaussianFunc(1.0,0.1) >>> dist_2 = GaussianFunc(0.5,0.2) >>> s1 = InputSpec(1.0 ,'S1', distribution=dist_1) >>> s2 = InputSpec(0.5 ,'S2', distribution=dist_2) >>> class MyMarginNetwork(MarginNetwork): >>> def randomize(self): >>> # randomization procedure >>> s1.random() >>> s2.random() >>> def forward(self): >>> # some specific model-dependent behaviour >>> x = s1.value + s2.value # These values will be drawn from their respective distributions
- reset(n: int | None = None)
Resets all elements of the MAN by clearing their internal caches
- Parameters:
n (int, optional) – if provided deletes only the last n_samples, where possible, by default None
- reset_inputs(n: int | None = None)
Resets Design parameters and input specifications
- Parameters:
n (int, optional) – if provided deletes only the last n_samples, where possible, by default None
- reset_outputs(n: int | None = None)
Resets Impact, Absorption, Deterioration, and Utilization matrices
- Parameters:
n (int, optional) – if provided deletes only the last n_samples, by default None
- save(filename: str = 'man', folder: str = '/', results_only: bool = False)
saves the initial state of the MarginNetwork: Performance surrogate and decision univere Saves any stored matrices
- Parameters:
filename (str, optional) – prefix before saved files, by default ‘man’
folder (str, optional) – basefile path, by default is current directory
results_only (bool, optional) – if True only saves results related objects such as margin nodes, input specs, performances, and impact and absorption matrices, by default False
- property spec_signs: ndarray
returns a vector of input specifications directions
- Returns:
vector of input specification change directions
- Return type:
np.ndarray
- property spec_vector: ndarray
returns a vector of input specifications
- Returns:
vector of input specifications
- Return type:
np.ndarray
- train_performance_surrogate(n_samples: int = 100, sampling_freq: int = 1, bandwidth: List[float] = [0.01], sm_type: str = 'KRG', num_threads: int = 1, ext_samples: Tuple[ndarray, ndarray] | None = None, random_state: int | RandomState | None = None)
Constructs a surrogate model y(x), where x are the excess values and y are the performance parameters that can be used to calculate threshold performances
- Parameters:
n_samples (int, optional) – number of design space data points used for training, by default 100
sampling_freq (int, optional) – If > than 1 then the decided value is calculated as the average of N samples by calling the forward() N times and averaging the decided values, where N = sampling_freq, by default 1
bandwidth (List[float], optional) – The kernel bandwidth used in Kriging, by default [1e-2,]
sm_type (str, optional) – type of surrogate model to train, possible values [‘KRG’,’LS’], by default ‘KRG’
num_threads (int, optional) – number of threads to parallelize sampling process, by default 1
ext_samples (tuple[np.ndarray,np.ndarray], optional) – if sample data provided externally then use directly to fit the response surface, Tuple must have length 2, ext_samples[0] must have shape (N_samples,len(margin_nodes)), ext_samples[1] must have shape (N_samples,len(performances)), by default None
random_state (Union[int,np.random.RandomState], optional) – Random seed or random generator instance used to generate training samples, If None is provided a random seed is used, by default None
- property tt_vector: ndarray
target threshold vector getter
- Returns:
vector of target thresholds
- Return type:
np.ndarray
- view_perf(e_indices: List[int], p_index: int, label_1: str | None = None, label_2: str | None = None, label_p: str | None = None, n_levels: int = 100, folder: str = '', file: str | None = None, img_format: str = 'pdf')
Shows the estimated performance
- Parameters:
e_indices (list[int]) – index of the margin node values to be viewed on the plot
p_index (int) – index of the performance parameter to be viewed on the plot
label_1 (str, optional) – axis label of excess value 1if not provided uses the key of MarginNode, by default None
label_2 (str, optional) – axis label of excess value 2, if not provided uses the key of MarginNode, by default None
label_p (str, optional) – z-axis label of performance parameter, if not provided uses the key of Performance object, by default None
n_levels (int, optional) – resolution of the plot (how many full factorial levels in each direction are sampled), by default 100
folder (str, optional) – folder in which to store image, by default ‘’
file (str, optional) – name of image file, if not provide then an image is not saved, by default None
img_format (str, optional) – format of the image to be stored, by default ‘pdf’