coordinates.mixins.mathops.CoordinateSystemMathMixin.compute_expression_from_coordinates#
- CoordinateSystemMathMixin.compute_expression_from_coordinates(expression: str, coordinates: Sequence[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]], fixed_axes: Dict[str, float] | None = None, sparse: bool = False) _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] [source]#
Evaluate a named expression over 1D coordinate arrays with optional fixed axes.
This method creates a broadcasted meshgrid internally from 1D input arrays and evaluates the expression over it.
- Parameters:
expression (
str
) – The name of the symbolic expression to evaluate.coordinates (
list
ofarray-like
) – 1D arrays representing coordinate values for free axes.fixed_axes (
dict
of{str: float}
, optional) – Dictionary of scalar axis values for fixed axes.sparse (
bool
, optional) –If True the shape of the returned coordinate array for dimension i is reduced from
(N1, ..., Ni, ... Nn)
to(1, ..., 1, Ni, 1, ..., 1)
. These sparse coordinate grids are intended to be use with Broadcasting. When all coordinates are used in an expression, broadcasting still leads to a fully-dimensional result array.Default is False.
- Returns:
The evaluated result over the broadcasted grid.
- Return type:
array-like
- Raises:
KeyError – If the expression is not available.
ValueError – If axis names are inconsistent.
Examples
In spherical coordinates, the metric density is \(r^2\sin \theta\). Thus, we can fairly easily create a plot of this!
>>> # Imports >>> from pymetric.coordinates import SphericalCoordinateSystem >>> from scipy.interpolate import NearestNDInterpolator >>> import matplotlib.pyplot as plt >>> from pymetric.utilities.logging import pg_log >>> pg_log.level = 50 >>> u = SphericalCoordinateSystem() >>> >>> # Create the r,theta coordinate grids. >>> r = np.linspace(0,1,100) >>> theta = np.linspace(0,np.pi,100) >>> R,THETA = np.meshgrid(r,theta, indexing='ij') >>> >>> # Compute the metric density on the grid. >>> md = u.compute_expression_from_coordinates("metric_density", [r, theta], fixed_axes={"phi": np.pi / 4}) >>> >>> # Use SciPy to interpolate to a cartesian coordinate system. >>> x,z = np.linspace(-1/np.sqrt(2),1/np.sqrt(2),100),np.linspace(-1/np.sqrt(2),1/np.sqrt(2),100) >>> X,Z = np.meshgrid(x,z,indexing='ij') >>> cart_grid_r, cart_grid_theta, _ = u._convert_cartesian_to_native(X, 0, Z) >>> interp = NearestNDInterpolator(np.stack([R.ravel(), THETA.ravel()],axis=-1), md.ravel()) >>> Z = interp(cart_grid_r, cart_grid_theta) >>> >>> # Create the plot. >>> ext = [-1/np.sqrt(2),1/np.sqrt(2),-1/np.sqrt(2),1/np.sqrt(2)] >>> plt.imshow(Z.T,extent=ext,origin='lower') >>> plt.show()