topoptlab.utils module

topoptlab.utils.batch_kron(A: ndarray, B: ndarray) ndarray[source]

Compute the Kronecker product of two matrices acting on the last two axes, while treating all leading axes as batch dimensions.

The Kronecker product is formed exclusively over the final two dimensions. All preceding dimensions are interpreted as batch dimensions and are preserved in the output.

This function is equivalent to:

np.stack([np.kron(A[i], B[i]) for i in batch_indices])

but avoids loops and is fully vectorized via einsum.

Parameters:
  • A (np.ndarray, shape (..., d, d)) – first array of square matrices.

  • B (np.ndarray, shape (..., d, d)) – second array of square matrices..

Returns:

M – Batched Kronecker product of A and B acting on the last two axes.

Return type:

np.ndarray, shape (…, d*d, d*d)

topoptlab.utils.check_meshdata(l: float | List | ndarray, g: float | List | ndarray, ndim: int) Tuple[ndarray, ndarray][source]

Validate and normalize mesh geometry inputs.

This helper function converts the element length input l and the angle input g into one-dimensional NumPy arrays of the expected size for a mesh of dimension ndim.

Parameters:
  • l (float or list or np.ndarray) – element side lengths. Can be provided as a single float (every dimension same), a list or a np.ndarray of shape/length (ndim,).

  • g (float or list or np.ndarray) – element angles. Can be provided as a single float (every angle same), a list or a np.ndarray of shape/length (ndim-1).

  • ndim (int) – spatial dimension of the mesh.

Returns:

  • l (np.ndarray) – element side lengths with shape (ndim,).

  • g (np.ndarray) – array of element angles with shape (ndim - 1,).

topoptlab.utils.check_optimizer_kw(optimizer: str, n: int, ft: int, n_constr: int, optimizer_kw: Dict) None[source]

Check that general optimuer parameters are sensible or implemented and insert missing ones based on the default dictionary.

Parameters:
  • optimizer (str) – name of optimizer.

  • n (int) – number of design variables.

  • ft (int) – code for filter.

  • n_constr (int) – number of constraints.

  • optimizer_kw (dictionary) – contains parameters for the optimizern . All relevant values can be found in default_outputkw.

Return type:

None

topoptlab.utils.check_output_kw(output_kw: Dict) None[source]

Check that general output parameters are sensible or implemented and insert missing ones based on the default dictionary.

Parameters:

output_kw (dictionary) – contains general parameters for outputting information . All relevant values can be found in default_outputkw.

Return type:

None

topoptlab.utils.check_simulation_params(simulation_kw: Dict) None[source]

Check that general simulation parameters are sensible or implemented.

Parameters:

simulation_kw (dictionary) – contains general information about simulation. At the moment, only “grid”,”element order”, “meshfile” are supported with contents “regular”,1,None.

Return type:

None

topoptlab.utils.cholesky_inverse(A: ndarray) ndarray[source]

Form inverse via Cholesky decomposition:

A = L @ L.T

Parameters:

A (np.ndarray shape (k,k) or (n,k,k)) – Matrix/matrices to invert.

Returns:

Ainv – inverted matrix/matrices.

Return type:

np.ndarray shape (k,k) or (n,k,k)

topoptlab.utils.default_outputkw() Dict[source]

Return the default dictionary containing general parameters for output and logging in the topology_optimization.main() function.

This dictionary defines the default for output-related behavior, such as file naming, verbosity, etc. It can be used as a reference or as a source for inserting missing keys in user-defined dictionaries.

Keys and Default Values

Key

Type

Default

Description

“file” “display” “export” “write_log” “profile” “output_movie” “verbosity”

str bool bool bool bool bool int

“topopt” True True True False False 20

Base name used for output files. Display intermediary design. Export final results to disk as VTK. Write a log file. Profile code execution. Generate a movie of intermediate designs. Level of verbosity (see SimpleLogger).

returns:

dictionary containing the default output parameters.

rtype:

output_kw

topoptlab.utils.dict_without(dictionary: Dict, keys: List) Dict[source]

Return a copy of a dictionary without the given keys.

Parameters:
  • dictionary (dict) – full dictionary.

  • keys (list) – list of keys to not include in the copy

Returns:

dictionary_new – dictionary without given keys

Return type:

dict

topoptlab.utils.elid_to_coords(el: ndarray, nelx: int, nely: int, nelz: None | int = None, l: float | List | ndarray = [1.0, 1.0, 1.0], g: float | List | ndarray = [0.0, 0.0], **kwargs: Any) ndarray[source]

Map element IDs to cartesian coordinates in the usual regular grid.

Parameters:
  • el (np.ndarray) – element IDs of shape (nel).

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

  • nelz (int or None) – number of elements in z direction.

  • l (float or list) – side length of elements.

  • g (float or list) – angle of elements. if both angles zero, element is rectangular/cuboid.

Returns:

coords – element coordinates of shape shape (nel,ndim).

Return type:

np.ndarray

topoptlab.utils.even_spaced_ternary(npoints: int) ndarray[source]

Create even spaced points for a ternary phase system.

Parameters:

npoints (int) – number of points.

Returns:

fracs – phase fractions.

Return type:

np.ndarray shape (k+1,3)

topoptlab.utils.flatten_lol(lst: List) List[source]

Flatten list of lists.

Parameters:

lst (dict) – list of lists.

Returns:

lst_flat – flattened list of lists.

Return type:

dict

topoptlab.utils.map_eltoimg(quant: ndarray, nelx: int, nely: int, **kwargs: Any) ndarray[source]

Map quantity located on elements on the usual regular grid to an image.

Parameters:
  • quant (np.ndarray, shape (n,nchannel)) – some quantity defined on each element (e. g. element density).

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

Returns:

img – quantity mapped to image.

Return type:

np.ndarray, shape (nely,nelx,nchannel)

topoptlab.utils.map_eltovoxel(quant: ndarray, nelx: int, nely: int, nelz: int, **kwargs: Any) ndarray[source]

Map quantity located on elements on the usual regular grid to a voxels.

Parameters:
  • quant (np.ndarray, shape (n,nchannel)) – some quantity defined on each element (e. g. element density).

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

  • nelz (int or None) – number of elements in z direction.

Returns:

voxel – quantity mapped to voxels.

Return type:

np.ndarray shape (nelz,nely,nelx,nchannel)

topoptlab.utils.map_imgtoel(img: ndarray, nelx: int, nely: int, **kwargs: Any) ndarray[source]

Map image of quantity back to 1D np.ndarray with correct (!) ordering.

Parameters:
  • img (np.ndarray, shape (nely,nelx)) – image of quantity (e. g. of element densities).

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

Returns:

quant – quantity mapped back to 1D np.ndarray with hopefully correct ordering.

Return type:

np.ndarray, shape (n)

topoptlab.utils.map_voxeltoel(voxel: ndarray, nelx: int, nely: int, nelz: int, **kwargs: Any) ndarray[source]

Map voxels of quantity back to on elements on the usual regular grid.

Parameters:
  • voxel (np.ndarray, shape (nelz,nely,nelx,nchannel)) – voxels of quantity (e. g. of element densities).

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

  • nelz (int or None) – number of elements in z direction.

Returns:

quant – quantity mapped back to 1D np.ndarray with hopefully correct ordering.

Return type:

np.ndarray, shape (n,nchannel)

topoptlab.utils.nodeid_to_coords(nd: ndarray, nelx: int, nely: int, nelz: None | int = None, l: float | List = [1.0, 1.0, 1.0], g: float | List | ndarray = [0.0, 0.0], **kwargs: Any) ndarray[source]

Map node IDs to cartesian coordinates in the usual regular grid. Node coordinates by convention start from -0.5*l_i (sidelength of element in the respective dimension).

Parameters:
  • nd (np.ndarray, shape (n)) – node IDs.

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

  • nelz (int or None) – number of elements in z direction.

  • l (float or List) – side length of element

  • g (float or list) – angle of elements. if both angles zero, element is rectangular/cuboid.

Returns:

coords – node coordinates of shape shape (n,ndim).

Return type:

np.ndarray

topoptlab.utils.safe_inverse(A: ndarray, assume_spd: bool = False, rcond: float = 1e-12, allow_pinv: bool = True, **kwargs: Any) ndarray[source]

“Safely” invert a matrix or batch of matrices.

Strategy:
  1. Cholesky (if SPD assumed)

  2. solve(A, I)

  3. SVD with cutoff (pseudo-inverse if allowed)

Parameters:
  • A (np.ndarray, shape (k,k) or (n,k,k))

  • assume_spd (bool) – Try Cholesky first.

  • rcond (float) – Relative singular value cutoff for SVD.

  • allow_pinv (bool) – If False, raise on near-singular matrices.

Returns:

Ainv

Return type:

np.ndarray

topoptlab.utils.solve_inverse(A: ndarray) ndarray[source]

Form inverse via solving:

solve(A,eye)

Parameters:

A (np.ndarray shape (k,k) or (n,k,k)) – Matrix/matrices to invert.

Returns:

Ainv – inverted matrix/matrices.

Return type:

np.ndarray shape (k,k) or (n,k,k)

topoptlab.utils.svd_inverse(A: ndarray, check_singular: bool = True) ndarray[source]

Form inverse via singular value decomposition (SVD). Not recommended as numerically unstable.

Parameters:
  • A (np.ndarray shape (k,k) or (n,k,k)) – Matrix/matrices to invert.

  • check_singular (bool) – Check if singular. If not True, raise ValueError.

Returns:

Ainv – inverted matrix/matrices.

Return type:

np.ndarray shape (k,k) or (n,k,k)

topoptlab.utils.unique_sort(iM: ndarray, jM: ndarray, combine: bool = False) Tuple[ndarray, ndarray, ndarray][source]

Sort first according to iM, then sort values of equal value iM according to jM.

Parameters:
  • iM (np.ndarray, shape (n)) – first array.

  • jM (np.ndarray, shape (n)) – second array.

  • combine (scalar bool) – if True, stack both to to a column array of shape (n,2)

Returns:

  • iM (np.ndarray shape (n)) – if not combine returns sorted iM

  • jM (np.ndarray shape (n)) – if not combine returns sorted jM

  • M (np.ndarray shape (n,2)) – if combine returns column stack of sort iM and jM.

topoptlab.utils.upsampling(x: ndarray, magnification: float | int | List, nelx: int, nely: int, nelz: None | int = None, return_flat: bool = True, order: int = 0) ndarray[source]

Upsample current design variables defined on the standard regular grid to a larger design by interpolation. With order 0 the design is replicated on a finer scale in a volume conserving fashion, otherwise spline interpolation might violate this.

Parameters:
  • x (np.ndarray shape (n,nchannel)) – design variables.

  • magnification (float) – magnification factor.

  • nelx (int) – number of elements in x direction.

  • nely (int) – number of elements in y direction.

  • nelz (int or None, optional) – number of elements in z direction. The default is None.

  • return_flat (bool, optional) – return the design variables flattened. If false returns an image or a voxel graphic. The default is True.

  • order (int, optional) – order of spline interpolation for upsampling. The default is 0.

Returns:

x_new – upsampled design variables.

Return type:

np.ndarray shape (n) or shape (nely,nelx) or shape (nelz,nely,nelx)