State, Mesh and Functions#

API reference for the Mesh, State, and Function classes.

See also

Class-Reference#

class neuralmag.Mesh(n, dx, origin=(0, 0, 0), pbc=(0, 0, 0))#

Regular cuboid mesh for nodal finite differences.

If the number of cells in all principal directions is provided, a 3D mesh is created with \((n_1 + 1) \times (n_2 + 1) \times (n_3 + 1)\) nodes. If only \(n_1\) and \(n_2\) are provided, a 2D mesh is created with a single layer of nodes, but finite thickness. If only \(n_1\) is provided, a 1D mesh is created with a single line of nodes, but finite thickness and width.

Parameters:
  • n (tuple) – Number of cells in each principal direction.

  • dx (tuple) – Cell size in each principal direction, in metres.

  • origin (tuple, optional) – Coordinate of the bottom-left corner of the mesh.

  • pbc (bool or tuple, optional) – Periodic boundary conditions. True enables true PBC in all spatial dimensions, False (or 0) means open boundaries. A tuple gives per-direction control: 0/False = open, positive integer = pseudo-PBC with that many image copies, True/float("inf") = true PBC. See the PBC user guide for details.

Examples

>>> # 3D mesh with one cell thickness, leading to 2 nodes in z-direction
>>> mesh_3d = Mesh((100, 25, 1), (5e-9, 5e-9, 3e-9))
>>> # 2D mesh with one cell thickness, leading to 1 node in z-direction
>>> mesh_2d = Mesh((100, 25), (5e-9, 5e-9, 3e-9))
property cell_volume#

The cell volume

property dim#

Spatial dimension (read-only).

discretization = 'fd'#

Name of the discretization this mesh uses; selects the Discretization strategy in the form compiler and is part of the generated-code cache key.

property dx#

Cell size per principal direction in metres (read-only).

field_shape(spaces, shape=())#

Full tensor shape of a field on this mesh: one entry per axis (cell axes get n[i] entries, node axes n[i]+1, or n[i] under periodic boundaries) followed by the trailing component shape.

property n#

Number of cells per principal direction (read-only).

property num_cells#

The total number of simulation cells

property num_nodes#

The total number of simulation nodes

property origin#

Coordinate of the mesh’s bottom-left corner (read-only).

property pbc#

Normalised periodic-boundary configuration per direction (read-only): 0 open, positive integer pseudo-PBC image count, float('inf') true PBC.

property volume#

The total volume of the mesh

class neuralmag.State(mesh, device=None, dtype=None)#

Carries the spatial discretization, parameters, and simulation state.

This class carries all information of the spatial discretization, parameters and the current state of the simulation.

Parameters:
  • mesh (Mesh) – The mesh for the simulation.

  • device (str, optional) – The device to be used, defaults to “cpu” (torch backend only).

  • dtype (str, optional) – The dtype to be used, defaults to “float64” (torch backend only).

add_domain(id, condition)#

Assign a domain id to all cells satisfying a condition.

The first call resets the default all-ones domain field to zero before marking the selected cells.

Parameters:
  • id (int) – The domain id to assign to the selected cells.

  • condition (Tensor) – Boolean mask over the mesh; cells where it is True are assigned to the domain.

coordinates(spaces=None, numpy=False)#

Return 3 tensors with the x, y, z coordinates of each cell/node.

In the case of cell discretization the coordinates at the cell centers are provided. In the case of node discretization the node positions are returned.

Parameters:
  • spaces (str, optional) – Function spaces, e.g. “ccc”, “nnn”.

  • numpy (bool, optional) – Return numpy arrays instead of backend arrays.

Returns:

The coordinates.

Return type:

tuple of Tensor

Examples

state = nm.State(nm.Mesh((10, 10, 10), (1e-9, 1e-9, 1e-9)))
x, y, z = state.coordinates('nnn')

# initialize magnetization based on coordinate function
state.m = VectorFunction(state)
state.m.tensor[..., 0] = torch.sin(x/20e-9)
state.m.tensor[..., 1] = torch.cos(x/20e-9)
property device#

The PyTorch device used for all tensors.

domains_from_file(filename, scale=1.0)#

Build a cell-space domain field by sampling an unstructured mesh file.

Each cell center is located in the unstructured mesh read from filename and assigned the corresponding cell-data value. Cell centers that fall outside the unstructured mesh are assigned -1.

Parameters:
  • filename (str) – Path to the unstructured mesh file (read via pyvista).

  • scale (float, optional) – Factor applied to the mesh coordinates before sampling, i.e. the inverse of the scale used when writing coordinates.

Returns:

Cell-space domain-id field on this state’s mesh.

Return type:

Function

property dtype#

The PyTorch dtype used for all tensors.

getattr(name)#

Return the attribute for the given name.

Attributes in namespaces can be accessed by using “.” as a seperator, e.g. material.Ms.

Parameters:

name (str) – The name of the attribute.

Return type:

The value of the attribute.

property material#

The material namespace.

The namespace supports the same functionality as the State class to set and get regular and dynamic attributes.

Examples

mesh = nm.Mesh((10, 10, 1), (5e-9, 5e-9, 3e-9))
state = nm.State(mesh)

# Set saturation magnetization Ms according to Bloch's law
Ms0 = 8e5
Tc = 400.0
state.T = 200.0
state.material.Ms = lambda T: Ms0 * (1 - T/Tc)**1.5
property mesh#

The mesh.

read_vti(filename, name=None, scale=1.0)#

Read field data from VTI file.

Parameters:
  • filename (str) – The filename of the VTI file.

  • name (str or None, optional) – The name of the attribute in the VTI file. If not provided, the first field in the VTI file will be read.

  • scale (float, optional) – The scale factor that was used when writing the file. Used to verify that the stored spacing matches the state mesh (after undoing the scale). Must match the scale passed to write_vti().

Returns:

The function.

Return type:

Function

static remap(f, mapping)#

Remap the arguments of a given function according to a mapping.

Parameters:
  • f (callable) – The function to be remapped.

  • mapping (dict) – The name mapping of the arguments.

Returns:

The remapped function.

Return type:

callable

Examples

state = nm.State(nm.Mesh((10, 10, 10), (1e-9, 1e-9, 1e-9)))

def f(a, b):
    return a + b

g = state.remap(f, {"a": "x", "b": "y"})
# g is a function with arguments "x" and "y"
resolve(func, func_args=None, remap={}, inject={})#

Analyse arguments of a function and build one depending on func_args.

Analyse arguments of supplied function and create Python function that depends solely on func_args if provided. If func_args is None the returned function will depend on all static state attributes that are dependencies of func.

Parameters:
  • func (callable or str) – The function to be analyzed, if string is provided the state attribute with the respective name is used.

  • func_args (list, optional) – Arguments of the returned function. If not set, function takes all dependent attributes.

  • remap (dict, optional) – Applies mapping to function and all dependent subfunctions.

  • inject (dict, optional) – Callables to be injected instead of named attributes.

Returns:

New function that takes args as arguments, if args is None the function has all dependencies as arguments.

Return type:

tuple

tensor(value, **kwargs)#

Create a tensor with device and dtype set according to state defaults.

Parameters:
  • value (Tensor or list) – The value of the tensor.

  • **kwargs – Parameters passed to the backend tensor routine.

Returns:

The tensor.

Return type:

Tensor

write_vti(fields, filename, scale=1.0)#

Write field data into VTI file.

Parameters:
  • fields (str, Function, or list) – The field data to be written. The field can be provided either as a Function or as attribute name(s) of state attributes.

  • filename (str) – The name of the VTI file.

  • scale (float, optional) – Factor applied to mesh spacing and origin before writing, e.g. use 1e9 to store coordinates in nanometres when the mesh is defined in SI metres.

Examples

state = nm.State(nm.Mesh((10, 10, 10), (1e-9, 1e-9, 1e-9)))

state.material.Ms = CellFunction(state).fill(8e5)
state.m = VectorFunction(state).fill([0, 0, 1])

# Write m into m.vti
state.write_vti("m", "m.vti")

# Write Ms and m into data.vti
state.write_vti(["material.Ms", "m"], "data.vti")

# Write some function f into f.vti
f = Function(state)
state.write_vti(f, "f.vti")

# Write m with coordinates in nanometres
state.write_vti("m", "m_nm.vti", scale=1e9)
zeros(shape, **kwargs)#

Create an empty tensor of given shape with default dtype and device.

Parameters:
  • shape (tuple) – The shape of the tensor.

  • **kwargs – Parameters passed to the backend routine.

Returns:

The tensor.

Return type:

Tensor

class neuralmag.Function(state, spaces=None, shape=(), tensor=None, name=None, dtype=None)#

Discretized field on the mesh of a state object.

If the instance is not initialized with a tensor, the tensor is lazily initialized with zeros on first access.

Parameters:
  • state (State) – The state that is used to construct the function.

  • spaces (str, optional) – The function spaces in each principal direction (defaults to "nnn" for 3D meshes and "nn" for 2D meshes).

  • shape (tuple, optional) – The shape of the function (either () for scalars or (3,) for vectors is currently supported).

  • tensor (Tensor or callable, optional) – Tensor with discretized function values, or a callable that depends on state attributes.

  • name (str, optional) – Name of the function.

  • dtype (optional) – dtype to be used for the tensor.

avg(domain_id=None)#

Return the componentwise average of the function over the mesh.

Parameters:

domain_id (int, optional) – Id of the domain to average over. If None, the average is computed over all domains with id > 0.

Returns:

The componentwise average.

Return type:

Tensor

fill(constant, expand=False)#

Fill the tensor of the function with a constant value.

Parameters:
  • constant (int or list) – The constant to fill the tensor with.

  • expand (bool, optional) – If True, the tensor is set by expanding the constant to the size of the mesh using torch.Tensor.expand, resulting in minimal storage consumption.

Returns:

The function itself.

Return type:

Function

Examples

>>> state = nm.State(nm.Mesh((10, 10, 10), (1e-9, 1e-9, 1e-9)))
>>> f = nm.Function(state, shape=(3,)).fill([1.0, 2.0, 3.0])
fill_by_domain(values)#

Fill the function with per-domain values.

Each cell takes the entry of values selected by its domain id, i.e. the tensor becomes values[domains]. Only supported for cell-space functions; other function spaces raise NotImplementedError.

Parameters:

values (list or Tensor) – Values indexed by domain id.

Returns:

The function itself.

Return type:

Function

property name#

The name of the function

property shape#

The shape of the function

property spaces#

The function spaces of the function

property state#

The state object used for the construction of the function

property tensor#

The tensor containing the discretized values of the function

property tensor_shape#

The shape of the tensor with the discretized field values

to_cell(weight=None)#

Project this function to cell space via mass-lumped L² projection.

Parameters:

weight (Function, optional) – Optional scalar cell-based weight for a weighted projection.

Returns:

The projected function in cell space.

Return type:

Function

to_node(weight=None)#

Project this function to node space via mass-lumped L² projection.

Parameters:

weight (Function, optional) – Optional scalar cell-based weight for a weighted projection.

Returns:

The projected function in node space.

Return type:

Function

class neuralmag.VectorFunction(state, **kwargs)#

Function with the shape set to (3,).

Parameters:
  • state (State) – The state that is used to construct the function.

  • spaces (str, optional) – The function spaces in each principal direction (defaults to "nnn" for 3D meshes and "nn" for 2D meshes).

  • tensor (Tensor or callable, optional) – Tensor with discretized function values.

  • name (str, optional) – Name of the function.

class neuralmag.CellFunction(state, **kwargs)#

Function with the function space set to cellwise in each dimension.

Parameters:
  • state (State) – The state that is used to construct the function.

  • shape (tuple, optional) – The shape of the function (either () for scalars or (3,) for vectors is currently supported).

  • tensor (Tensor or callable, optional) – Tensor with discretized function values.

  • name (str, optional) – Name of the function.

class neuralmag.VectorCellFunction(state, **kwargs)#

Function with shape (3,) and cellwise function space in each dimension.

Parameters:
  • state (State) – The state that is used to construct the function.

  • tensor (Tensor or callable, optional) – Tensor with discretized function values.

  • name (str, optional) – Name of the function.