Base Orbit Class

The base Orbit class

Overview

class orbithunter.core.Orbit(state=None, basis=None, parameters=None, discretization=None, constraints=None, **kwargs)[source]

Base class for orbits.

Parameters
statendarray, default None

If an array, it should contain the state values congruent with the ‘basis’ argument.

basisstr, default None

Which basis the array state is currently in. Must be str if type(state) is np.ndarray

parameterstuple, default None

Parameters required to uniquely define the Orbit.

discretizationtuple, default None

The shape of the state array in configuration space, i.e. the ‘physical’ basis.

constraintsdict, default None

Dictionary whose keys are parameter labels, and values are bool. If True, then corresponding parameter will be treated as a constant during optimization routines.

kwargs :

Extra arguments for _parse_parameters and _parse_state (future/subclass usage only).

Notes

NumPy broadcasting will occur as one would expect if relevant numerical quantities are compatible type and shape.

The common usage case of constructing instances has the user specifying the state, basis and parameter values. For advanced numerical operations, however, it is required to know which parameters are cosntrained, stored in the constraints attribute, and what the shape of the state array is, prior to any transformations, this is stored in the discretization attribute. Because of this, Orbit.__init__() parses the input and sets the constraints using defaults specified by private method Orbit._default_constraints(); and also parses the state array for its shape in the ‘physical’ basis. Take note that the discretization attribute is NOT the current shape of the state. There are many cases where the current state’s shape is not sufficient information; to avoid parsing of this type in all future calculations, it is done upon creation of the instance. This parsing takes time; it can and should be avoided. To avoid parsing, all primary attributes that would otherwise be parsed need to be passed upon creation. For Orbit this consists of: state, basis, parameters, discretization, and constraints. It is assumed that the information is coherent if it is all being passed by the user; i.e. the discretization does in fact correspond to the state array passed.

Examples

Orbit instances can be created in a multitude of ways. Typically it is acceptable to think of Orbits as a bundle of a state array and parameters.

Create an empty Orbit instance.

>>> orb = Orbit()

Create an empty Orbit instance, and then use built-in or user prescribed methods to fill its values

>>> orb = Orbit()
>>> orb.populate(seed=0) # By default all attributes are populated; seed for reproducibility
>>> print(repr(orb))
Orbit({"shape": [2, 2, 2, 2], "basis": "physical", "parameters": [0.549, 0.715, 0.603, 0.545]})

The attributes can also be specified using values ‘all’ (default), ‘state’ and ‘parameters’ for keyword ‘attr’.

>>> u = Orbit()
>>> u.populate(attr='parameters', seed=0)
>>> print(repr(orb))
Orbit({"shape": [0, 0, 0, 0], "basis": null, "parameters": [0.549, 0.715, 0.603, 0.545]})

Create and Orbit by providing state and parameter information

>>> example_state = np.ones([2, 2, 2, 2])
>>> example_parameters = (16, 16, 16, 16)
>>> u = Orbit(state=example_state, basis='physical', parameters=example_parameters)

“Fast” initialization occurs when the five main attributes: ‘state’, ‘basis’, ‘parameters’, ‘constraints’ and ‘discretization are provided. If ‘state’ and ‘basis’ are provided by ‘discretization’ is not, then ‘discretization’ is parsed from the state array. If ‘parameters’ is provided but ‘constraints’ are not, then the default constraints are used. These two parsing/argument checking routines occur independently.

>>> example_state = np.ones([2, 2, 2, 2])
>>> example_parameters = (16, 16, 16, 16)
>>> example_constraints = {'t': True, 'x': False, 'y': False, 'z': False}
>>> example_discretization = example_state.shape
>>> u = Orbit(state=example_state, basis='physical', parameters=example_parameters,
...           constraints=example_constraints, discretization=example_discretization)

Using Jupyter Lab’s cell magic %%timeit to demonstrate. No parsing is much faster on a relative basis.

>>> %%timeit
>>> u = Orbit(state=example_state, basis='physical', parameters=example_parameters,
...           constraints=example_constraints, discretization=example_discretization)
1.44 µs ± 97.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> %%timeit
>>> u = Orbit(state=example_state, basis='physical', parameters=example_parameters)
10.9 µs ± 36.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The latter is the more common usage, but when writing functions it is recommended to pass all attributes using dictionary unpacking; dictionary merging of the form {**dict1, **dict2} can be used to overwrite values of dict1 with new values in dict2 (those corresponding to the same keys, that is, the operation is otherwise a union).

>>> def example_func_(orbit_instance):
>>>     new_state_same_shape = ...
>>>     return orbit_instance.__class__(**{**vars(orbit_instance), 'state': new_state_same_shape})

Methods

Initialization

Examples of these methods are included in in Overview

Orbit.__init__([state, basis, parameters, …])

Initialize self.

Orbit.populate([attr])

Initialize random parameters or state or both.

Orbit._populate_state(**kwargs)

Should only be accessed through Orbit.populate()

Orbit._populate_parameters(**kwargs)

Should only be accessed through Orbit.populate()

Orbit._parse_state(state, basis, **kwargs)

Parse and assign ‘state’, ‘basis’ and ‘discretization’ attributes.

Orbit._parse_parameters(parameters, **kwargs)

Parse and set the parameters attribute.

See Python Docs for the definition of ‘special’

Special Methods

Orbit.__add__(other)

Addition of Orbit state and other numerical quantity.

Orbit.__radd__(other)

Addition of Orbit state and other numerical quantity.

Orbit.__sub__(other)

Subtraction of other numerical quantity from Orbit state.

Orbit.__rsub__(other)

Subtraction of Orbit state from other numeric quantity

Orbit.__mul__(other)

Multiplication of Orbit state and other numerical quantity

Orbit.__rmul__(other)

Multiplication of Orbit state and other numerical quantity

Orbit.__truediv__(other)

Division of Orbit state by other numerical quantity

Orbit.__floordiv__(other)

Floor division of Orbit state by other numerical quantity

Orbit.__pow__(other)

Exponentiation of Orbit state.

Orbit.__mod__(other)

Modulo of Orbit state.

Orbit.__iadd__(other)

Inplace addition of Orbit state with other

Orbit.__isub__(other)

Inplace subtraction of other from Orbit state

Orbit.__imul__(other)

Inplace multiplication of Orbit state with other

Orbit.__ipow__(other)

Inplace exponentiation of Orbit state by other

Orbit.__itruediv__(other)

Inplace division of Orbit state by other

Orbit.__ifloordiv__(other)

Inplace floor division of Orbit state by other

Orbit.__imod__(other)

In place modulo of Orbit state

Orbit.__str__()

String name

Orbit.__repr__()

More descriptive representation than __str__ with beautified parameters.

Orbit.__getattr__(attr)

Allows parameters, discretization variables to be retrieved by label directly

Orbit.__getitem__(key)

Slicing of Orbit state and corresponding dimensions

Properties

Orbit.shape

Current state array’s shape

Orbit.size

Current state array’s dimensionality

Orbit.ndim

Current state array’s number of dimensions

State Transformations

Orbit.reflection([axis, signed])

Reflect the velocity field about the spatial midpoint

Orbit.roll(shift[, axis])

Apply numpy roll along specified axis.

Orbit.cell_shift(n_cell[, axis])

Rotate by period/n_cell in either axis.

Orbit.to_fundamental_domain(**kwargs)

Placeholder/signature for possible symmetry subclasses.

Orbit.from_fundamental_domain(**kwargs)

Placeholder/signature for possible symmetry subclasses.

Orbit.resize(*new_discretization, **kwargs)

Rediscretize the current state typically via zero padding or interpolation.

Orbit._pad(size[, axis])

Increase the size of the discretization along an axis.

Orbit._truncate(size[, axis])

Decrease the size of the discretization along an axis

Math Functions

Orbit.orbit_vector()

Vector representation of Orbit instance; constants all variables required to define the Orbit instance.

Orbit.eqn(*args, **kwargs)

Return an instance whose state is an evaluation of the governing equations.

Orbit.matvec(other, **kwargs)

Matrix-vector product of Jacobian and orbit_vector from other instance.

Orbit.rmatvec(other, **kwargs)

Matrix-vector product of adjoint Jacobian and state from other instance.

Orbit.jacobian(**kwargs)

Jacobian matrix evaluated at the current state.

Orbit.hess(**kwargs)

Matrix of second derivatives of the governing equations.

Orbit.hessp(left_other, right_other, **kwargs)

Tensor product u * H * v where H is the matrix of second derivatives of governing equations.

Orbit.cost([evaleqn])

Cost function evaluated at current state.

Orbit.costgrad([eqn])

Matrix-vector product corresponding to gradient of scalar cost functional \(1/2 F^2\)

Orbit.costhess(**kwargs)

Matrix-vector product with the Hessian of the cost function.

Orbit.costhessp(other, **kwargs)

Matrix-vector product with the Hessian of the cost function.

Orbit.abs()

Orbit instance with absolute value of state.

Orbit.dot(other)

Return the L_2 inner product of two orbits

Orbit.norm([order])

Norm of spatiotemporal state via numpy.linalg.norm

Orbit.rescale(magnitude[, method])

Rescaling of the state in the ‘physical’ basis per strategy denoted by ‘method’

Orbit.from_numpy_array(cdof, *args, **kwargs)

Utility to convert from numpy array (orbit_vector) to Orbit instance for scipy wrappers.

Orbit.increment(other[, step_size])

Incrementally add Orbit instances together

Discretization and Dimension

Orbit.shapes()

The possible shapes of the current state based on discretization and basis.

Orbit.dimensions()

Dimensions of the spatiotemporal tile (configuration space).

Orbit.glue_dimensions(dimension_tuples, …)

Strategy for combining tile dimensions in gluing; default is arithmetic averaging.

Orbit.periodic_dimensions()

Bools indicating whether or not dimension is periodic for persistent homology calculations.

Orbit.dimension_based_discretization(…)

Follow orbithunter conventions for discretization size.

Reading and Writing

Orbit.filename([extension, decimals, cls_name])

Method for convenience and consistent/conventional file naming.

Orbit.to_h5([filename, groupname, dataname, …])

Export current state information to HDF5 file

Static

Orbit.bases_labels()

Labels of the different bases that ‘state’ attribute can be in.

Orbit.parameter_labels()

Strings to use to label dimensions.

Orbit.dimension_labels()

Strings to use to label dimensions/periods; typically a subset of parameter_labels.

Orbit.discretization_labels()

Strings to use to label discretization variables.

Orbit.minimal_shape()

The smallest possible discretization that can be used without methods breaking down.

Orbit.minimal_shape_increments()

The smallest valid increment to change the discretization by.

Other

Orbit.copy()

Return an instance with copies of copy-able attributes.

Orbit.mask(masking_array[, invert])

Return an Orbit instance with a numpy masked array state

Orbit.constrain(*labels)

Set self constraints based on labels provided.

Orbit.preprocess()

Check the “status” of a solution

Defaults

Orbit.defaults()

Dict of default values for constraints, parameter ranges, sizes, etc.

Orbit._default_shape()

The default array shape when dimensions are not specified.

Orbit._default_parameter_ranges()

Intervals (continuous) or iterables (discrete) used to populate parameters.

Orbit._default_constraints()

Sometimes parameters are necessary but constant; this allows for exclusion from optimization without hassle.

Utility Functions

orbithunter.core.convert_class(orbit_instance, orbit_type, **kwargs)[source]

Utility for converting between different symmetry classes.

Parameters
orbit_instanceOrbit or Orbit subclass instance

The orbit instance to be converted

orbit_typeOrbit type

The target class that orbit will be converted to.

Returns
Orbit :

New Orbit instance whose type is the provided orbit_type

Notes

This is for all practical purposes deprecated but it still provides readability so it has been kept as a convenience. To avoid conflicts with projections onto symmetry invariant subspaces, the orbit is always transformed into the physical basis prior to conversion; the instance is returned in the basis of the input, however.

Include any and all attributes that might be relevant to the new orbit and those which transfer over from old orbit via usage of vars(orbit_instance) and kwargs. If for some reason an attribute should not be passed, then providing attr=None in the function call is how to handle it, as the values in kwargs overwrite the values in vars(orbit_instance) via dictionary unpacking.