amisc.variable
Provides an object-oriented interface for model inputs/outputs, random variables, scalars, and field quantities.
Includes:
Variable
— an object that stores information about a variable and includes methods for sampling, pdf evaluation, normalization, compression, loading from file, etc. Variables can mostly be treated as strings that have some additional information and utilities attached to them.VariableList
— a container forVariables
that provides dict-like access ofVariables
byname
along with normal indexing and slicing.
The preferred serialization of Variable
and VariableList
is to/from yaml. This is done by default with the
!Variable
and !VariableList
yaml tags.
Variable(name=None, **kwargs)
Bases: BaseModel
, Serializable
Object for storing information about variables and providing methods for pdf evaluation, sampling, etc. All fields will undergo pydantic validation and conversion to the correct types.
A simple variable object can be created with var = Variable()
. All initialization options are optional and will
be given good defaults. You should probably at the very least give a memorable name
and a domain
. Variables
can mostly be treated as strings with some extra information/utilities attached.
With the pyyaml
library installed, all Variable
objects can be saved or loaded directly from a .yml
file by
using the !Variable
yaml tag (which is loaded by default with amisc
).
- Use
Variable.distribution
to specify PDFs, such as for random variables. See theDistribution
classes. - Use
Variable.norm
to specify a transformed-space that is more amenable to surrogate construction (e.g. mapping to the range (0,1)). See theTransform
classes. - Use
Variable.compression
to specify high-dimensional, coordinate-based field quantities, such as from the output of many simulation software programs. See theCompression
classes. - Use
Variable.category
as an additional layer for using Variable's in different ways (e.g. set a "calibration" category for Bayesian inference).
Example
# Random variable
temp = Variable(name='T', description='Temperature', units='K', distribution='Uniform(280, 320)')
samples = temp.sample(100)
pdf = temp.pdf(samples)
# Field quantity
vel = Variable(name='u', description='Velocity', units='m/s', compression={'fields': ['ux', 'uy', 'uz']})
vel_data = ... # from a simulation
reduced_vel = vel.compress(vel_data)
Warning
Changes to collection fields (like Variable.norm
) should completely reassign the whole
collection to trigger the correct validation, rather than editing particular entries. For example, reassign
norm=['log', 'linear(2, 2)']
rather than editing norm via norm.append('linear(2, 2)')
.
ATTRIBUTE | DESCRIPTION |
---|---|
name |
an identifier for the variable, can compare variables directly with strings for indexing purposes
TYPE:
|
nominal |
a typical value for this variable
TYPE:
|
description |
a lengthier description of the variable
TYPE:
|
units |
assumed units for the variable (if applicable)
TYPE:
|
category |
an additional descriptor for how this variable is used, e.g. calibration, operating, design, etc.
TYPE:
|
tex |
latex format for the variable, i.e. "\(x_i\)"
TYPE:
|
compression |
specifies field quantities and links to relevant compression data
TYPE:
|
distribution |
a string specifier of a probability distribution function (see the
TYPE:
|
domain |
the explicit domain bounds of the variable (limits of where you expect to use it); for field quantities, this is a list of domains for each latent dimension
TYPE:
|
norm |
specifier of a map to a transformed-space for surrogate construction (see the
TYPE:
|
Source code in src/amisc/variable.py
get_tex(units=False, symbol=True)
Return a raw string that is well-formatted for plotting (with latex).
PARAMETER | DESCRIPTION |
---|---|
units |
whether to include the units in the string
TYPE:
|
symbol |
just latex symbol if true, otherwise the full description
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
the latex formatted string |
Source code in src/amisc/variable.py
get_nominal()
Return the nominal value of the variable. Defaults to the mean for a normal distribution or the
center of the domain if var.nominal
is not specified. Returns a list of nominal values for each latent
dimension if this is a field quantity with compression.
RETURNS | DESCRIPTION |
---|---|
float | list | None
|
the nominal value(s) |
Source code in src/amisc/variable.py
get_domain()
Return a tuple of the defined domain of this variable. Returns a list of domains for each latent dimension if this is a field quantity with compression.
RETURNS | DESCRIPTION |
---|---|
tuple | list | None
|
the domain(s) of this variable |
Source code in src/amisc/variable.py
sample_domain(shape)
Return an array of the given shape
for uniform samples over the domain of this variable. Returns
samples for each latent dimension if this is a field quantity with compression.
Note
The last dim of the returned samples will be the latent space size for field quantities.
PARAMETER | DESCRIPTION |
---|---|
shape |
the shape of samples to return
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ndarray
|
the random samples over the domain of the variable |
Source code in src/amisc/variable.py
update_domain(domain, override=False)
Update the domain of this variable by taking the minimum or maximum of the new domain with the current domain
for the lower and upper bounds, respectively. Will attempt to update the domain of each latent dimension
if this is a field quantity with compression. If the variable has a Uniform
distribution, this will
update the distribution's bounds too.
PARAMETER | DESCRIPTION |
---|---|
domain |
the new domain(s) to update with
TYPE:
|
override |
will simply set the domain to the new values rather than update against the current domain; (default
TYPE:
|
Source code in src/amisc/variable.py
pdf(x)
Compute the PDF of the Variable at the given x
locations. Will just return one's if the variable
does not have a distribution.
PARAMETER | DESCRIPTION |
---|---|
x |
locations to compute the PDF at
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ndarray
|
the PDF evaluations at |
Source code in src/amisc/variable.py
sample(shape, nominal=None)
Draw samples from this Variable's
distribution. Just returns the nominal value of the given shape if
this Variable
has no distribution.
PARAMETER | DESCRIPTION |
---|---|
shape |
the shape of the returned samples
TYPE:
|
nominal |
a nominal value to use if applicable (i.e. a center for relative, tolerance, or normal)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ndarray
|
samples from the PDF of this |
Source code in src/amisc/variable.py
normalize(values, denorm=False)
Normalize values
based on this Variable's
norm
method(s). See Transform
for available norm methods.
Note
If this Variable's self.norm
was specified as a list of norm methods, then each will be applied in
sequence in the original order (and in reverse for denorm=True
). When self.distribution
is involved in
the transforms (only for minmax
and zscore
), the dist_args
will get normalized too at each
transform before applying the next transform.
PARAMETER | DESCRIPTION |
---|---|
values |
the values to normalize (array-like)
TYPE:
|
denorm |
whether to denormalize instead using the inverse of the original normalization method
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ArrayLike | None
|
the normalized (or unnormalized) values |
Source code in src/amisc/variable.py
denormalize(values)
compress(values, coords=None, reconstruct=False)
Compress or reconstruct field quantity values using this Variable's
compression info.
Specifying compression values
If only one field quantity is associated with this variable, then
specify values
as dict(coords=..., name=...)
for this Variable's name
. If coords
is not specified,
then this assumes the locations are the same as the reconstruction data (and skips interpolation).
Compression workflow
Generally, compression follows interpolate -> normalize -> compress
to take raw values into the compressed
"latent" space. The interpolation step is required to make sure values
align with the coordinates used
when building the compression map in the first place (such as through SVD).
PARAMETER | DESCRIPTION |
---|---|
values |
a
TYPE:
|
coords |
the coordinates of each point in
TYPE:
|
reconstruct |
whether to reconstruct values instead of compress
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
CompressionData
|
the compressed values with key |
Source code in src/amisc/variable.py
reconstruct(values, coords=None)
Alias for compress(reconstruct=True)
. See compress
for more details.
serialize(save_path='.')
Convert a Variable
to a dict
with only standard Python types
(i.e. convert custom objects like dist
and norm
to strings and save compression
to a .pkl
).
PARAMETER | DESCRIPTION |
---|---|
save_path |
the path to save the compression data to (defaults to current directory)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict
|
the serialized |
Source code in src/amisc/variable.py
deserialize(data, search_paths=None)
classmethod
Convert a dict
to a Variable
object. Let pydantic
handle validation and conversion of fields.
PARAMETER | DESCRIPTION |
---|---|
data |
the
TYPE:
|
search_paths |
the paths to search for compression files (if necessary)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Variable
|
the |
Source code in src/amisc/variable.py
VariableList(data=None, **kwargs)
Bases: OrderedDict
, Serializable
Store Variables
as str(var) : Variable
in the order they were passed in. You can:
- Initialize/update from a single
Variable
or a list ofVariables
- Get/set a
Variable
directly or by name viamy_vars[var]
ormy_vars[str(var)]
etc. - Retrieve the original order of insertion by
list(my_vars.items())
- Access/delete elements by order of insertion using integer/slice indexing (i.e.
my_vars[1:3]
) - Save/load from yaml file using the
!VariableList
tag
Initialize a collection of Variable
objects.
Source code in src/amisc/variable.py
get_domains(norm=True)
Get normalized variable domains (expand latent coefficient domains for field quantities). Assume a
domain of (0, 1)
for variables if their domain is not specified.
PARAMETER | DESCRIPTION |
---|---|
norm |
whether to normalize the domains using
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
a |
Source code in src/amisc/variable.py
get_pdfs(norm=True)
Get callable pdfs for all variables (skipping field quantities for now)
PARAMETER | DESCRIPTION |
---|---|
norm |
whether values passed to the pdf functions are normalized and should be denormed first before pdf evaluation (useful for surrogate construction where samples are gathered in the normalized space)
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
a |
Source code in src/amisc/variable.py
update(data=None, **kwargs)
Update from a list or dict of Variable
objects, or from key=value
pairs.
Source code in src/amisc/variable.py
get(key, default=None)
serialize(save_path='.')
Convert to a list of dict
objects for each Variable
in the list.
PARAMETER | DESCRIPTION |
---|---|
save_path |
the path to save the compression data to (defaults to current directory)
DEFAULT:
|
Source code in src/amisc/variable.py
merge(*variable_lists)
classmethod
Merge multiple sets of variables into a single VariableList
object.
Note
Variables with the same name will be merged by keeping the one with the most information provided.
PARAMETER | DESCRIPTION |
---|---|
variable_lists |
the variables/lists to merge
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
VariableList
|
the merged |
Source code in src/amisc/variable.py
deserialize(data, search_paths=None)
classmethod
Convert a dict
or list of dict
objects to a VariableList
object. Let pydantic
handle validation.