e15190.utilities.geometry.RectangularBar¶
- class e15190.utilities.geometry.RectangularBar(vertices, calculate_local_vertices=True, make_vertices_dict=True)¶
Functions
__init__(vertices[, ...])Construct a rectangular bar, a.k.a.
Update bar's attribute
self.triangle_mesh.dimension([index])Returns the dimension(s) of the bar.
draw_hit_pattern2d(hits, ax[, frame, ...])Draw the hit pattern of the bar with 2D histogram.
get_geometry_efficiency_alphashape(delta, alpha)Calculate the geometry efficiency of the bar using the alphashape.
get_hit_positions([hit_t, frame, ...])Return the hit positions of the simulation.
get_theta_phi_alphashape(delta, alpha[, cut])Calculate the alphashape of the bar in (theta, phi) coordinates.
get_total_solid_angle([method])Return the total solid angle of the bar.
get_total_solid_angle_alphashape(delta, alpha)Calculate the total solid angle of the bar using the alphashape.
get_total_solid_angle_monte_carlo([n_rays, ...])Calculate the total solid angle of the bar by Monte Carlo simulation.
is_inside(coordinates[, frame, tol])Check if the given coordinates are inside the bar.
simple_simulation([n_rays, random_seed, ...])A simple ray simulation on the bar.
to_lab_coordinates(local_coordinates)Converts coordinates from local frame to lab frame.
to_local_coordinates(lab_coordinates)Converts coordinates from lab frame to local frame.
Properties
The vertices of the bar in lab frame (unit cm)
The vertices of the bar in local frame (unit cm)
The PCA of the bar vertices in lab frame
- __init__(vertices, calculate_local_vertices=True, make_vertices_dict=True)¶
Construct a rectangular bar, a.k.a. a cuboid.
- Parameters
vertices (ndarray of shape (8, 3)) – Exactly eight tuples of (x, y, z) in lab coordinates. As long as all eight vertices are distinct, i.e. can properly define a cuboid, the order of vertices does not matter because PCA will be applied to automatically identify the 1st, 2nd and 3rd principal axes of the bar.
calculate_local_vertices (bool, default True) – Whether to calculate the local vertices. Local vertices are the coordinates with respect to the bar’s x, y and z axes, defined as the 1st, 2nd and 3rd principal axes.
make_vertices_dict (bool, default True) – Whether to make the vertices dictionary. See more at
_make_vertices_dict().
- vertices¶
The vertices of the bar in lab frame (unit cm)
A length-8 dictionary of the form
{(i, j, k): (x, y, z)}- Type
dict
- pca¶
The PCA of the bar vertices in lab frame
- Type
sklearn.decomposition.PCA
- loc_vertices¶
The vertices of the bar in local frame (unit cm)
A length-8 dictionary of the form
{(i, j, k): (x', y', z')}- Type
dict
- static _get_vertices_dict(loc_vertices, vertices)¶
Convert both dictionaries into mappings from egocentric directions onto vertices.
A rectangular bar has eight vertices. To distinguish the vertices, we use 3-tuples of -1 and +1 to indicate the directions in local (bar) frame. For example,
(-1, +1, -1)implies the vertex, when observed in the local frame, is in the negative x direction, positive y direction, and negative z direction. Each vertex’s coordinates would be stored as numpy array of length 3, representing \((x, y, z)\).- Parameters
loc_vertices (array-like of shape (8, 3)) –
The local vertices of the bar, e.g. vertex coordinates in the bar frame. This array will be used to determine the egocentric directions. It is user’s responsibility to ensure that the eight coordinates form a cuboid whose center is at the origin and the edges are all parallel to one of the x, y or z axes.
This can usually be done easily by applying the
to_local_coordinates()function tovertices. Under the hood, PCA is applied to identify the three principal axes of the bar.vertices (array-like of shape (8, 3)) – The vertices in the lab frame. The order of
verticesmust match the order ofloc_vertices.
- Returns
loc_vertices_dict (dict) – A dictionary of
{(i, j, k): (x', y', z')}, where \((x', y', k')\) are the points inloc_vertices.vertices_dict (dict) – A dictionary of
{(i, j, k): (x, y, z)}, where \((x, y, z)\) are the points invertices.
- _make_vertices_dict()¶
Convert self local vertices and vertices into dictionaries.
Simply apply
_get_vertices_dict()to update bothself.loc_verticesandself.vertices.
- dimension(index: Optional[int] = None) float | tuple[float, float, float]¶
Returns the dimension(s) of the bar.
- Parameters
index (int, default None) – The index of the direction. If None, all three dimensions will be returned. Indices 1, 2 and 3 correspond to the x, y and z in the local (bar) frame.
- Returns
dimension – The dimension(s) of the bar.
- Return type
float or 3-tuple of floats
- static _deco_numpy_ndim(func)¶
Decorator for preserving numpy array’s dimensionality.
Some functions only accepts 2D arrays, i.e. rows of 1D arrays, and perform some row-wise operations. To apply this kind of functions on 1D arrays, we may use this decorator. The decorated functions can take in either a 2D array or a 1D array. If the input is a 2D array, the output will be a 2D array; if the input is a 1D array, the output will be kept as a 1D array.
- Parameters
func (function) – The function to decorate.
- Returns
func – The decorated function.
- Return type
function
Example
>>> f = lambda X: np.array([np.square(x) for x in X]) >>> from e15190.utilities import geometry as geom >>> deco_f = geom.RectangularBar._deco_numpy_ndim(f) >>> deco_f(np.array([[1, 2, 3], [4, 5, 6]])) np.array([[1, 4, 9], [16, 25, 36]]) >>> deco_f(np.array([1, 2, 3])) np.array([1, 4, 9])
- to_local_coordinates(lab_coordinates)¶
Converts coordinates from lab frame to local frame.
Always assume Cartesian coordinates in both frames.
- Parameters
lab_coordinates ((N, 3) or (3, ) array_like) – The lab coordinates \((x, y, z)\) to be converted.
- Returns
local_coordinates – The local coordinates \((x', y', z')\).
- Return type
(N, 3) or (3, ) array_like
- to_lab_coordinates(local_coordinates)¶
Converts coordinates from local frame to lab frame.
Always assume Cartesian coordinates in both frames.
- Parameters
local_coordinates ((N, 3) or (3, ) array_like) – The local coordinates \((x', y', z')\) to be converted.
- Returns
lab_coordinates – The lab coordinates \((x, y, z)\).
- Return type
(N, 3) or (3, ) array_like
- is_inside(coordinates, frame='lab', tol=0.0005)¶
Check if the given coordinates are inside the bar.
- Parameters
coordinates (array of shape (N, 3) or (3, )) – The coordinates to be checked. Only support Cartesian coordinates.
frame ('local' or 'lab', default 'lab') – The frame of the coordinates.
tol (float, default 5e-4) – The tolerance of the boundary check.
- Returns
inside –
Trueif the coordinates are inside the bar, otherwiseFalse.- Return type
bool or an array of bool
- construct_plotly_mesh3d() None¶
Update bar’s attribute
self.triangle_mesh.Construct a
TriangleMeshobject, i.e. a triangular mesh for the geometry of the bar, and save asself.triangle_mesh.
- simple_simulation(n_rays=10, random_seed=None, polar_range=None, azimuth_range=None, save_result=True)¶
A simple ray simulation on the bar.
Simple simulation means that there is no scattering, reflection, refraction, or any other actual physics consideration. Instead, we are only calculating geometrical intersections of random rays with the bar geometry.
By default, this function would first identify the smallest rectangular region in the (theta, phi) space that fully contains the entire bar geometry. Then, it would randomly emit rays toward this minimal region. Both theta range and phi range will be saved, so that user can calculate the actual solid angle later on.
- Parameters
n_rays (int, default 10) – Number of rays to be emitted. Not all of them are guaranteed to interact.
random_seed (int, default None) – Random seed to be used for random number generation. If None, a time-based seed will be used, i.e. non-reproducible.
polar_range (2-tuple of floats or None, default None) – The polar range in radians. If None, the algorithm will use the minimal range determined by the bar vertices. This allows more efficient simulation.
azimuth_range (2-tuple of floats or None, default None) – The azimuth range in radians. If None, the algorithm will use the minimal range determined by the bar vertices. This allows more efficient simulation.
save_result (bool, default True) – Whether to save the result to this object as
self.simulation_result.
- Returns
simulation_result –
- A dictionary with the following keys and array shapes:
origin: shape (3, )azimuth_range: shape (2, )polar_range: shape (2, )intersections: shape (12,n_rays, 3)
The first component of intersections has a size of 12, which comes from the 12 triangles that made up the rectangular bar (triangle mesh). Other functions like
get_hit_positions()can be used to further simplify the intersection points.- Return type
dict
- get_hit_positions(hit_t='uniform', frame='local', coordinate='cartesian', simulation_result=None, random_seed=None, tol=1e-09)¶
Return the hit positions of the simulation.
This function should be called after
self.simulation_resultis updated, e.g. by callingsimple_simulation.- Parameters
hit_t (scalar or callable or 'uniform', default 'uniform') – If scalar, its value should be within [0, 1], with 0 being at the incident point at the surface, 1 being at the exit point, and the rest being somewhere in between. If callable, it should take in an integer
n_rays, and return an array of sizen_raysthat collect thehit_tvalues in the range of [0, 1]. If ‘uniform’, thehit_tvalues will be uniformly distributed over [0, 1].frame ('local' or 'lab', default 'local') – The coordinate frame of the returned hit positions.
coordinate ('cartesian' or 'spherical', default 'cartesian') – The coordinate system of the returned hit positions.
simulation_result (dict, default None) – The simulation result to be used. If None, the function uses
self.simulation_result.random_seed (int, default None) – The random seed used to generate the
hit_tvalues. If None, a time-based seed will be used, i.e. non-reproducible.tol (float, default 1e-9) – The tolerance used to filter out hit points that are too close to the origin, i.e. there were no intersections. The default simulation setting is such that if there were no intersections, the hit position will be the origin. Here, we simply put in a non-zero tolerance to account for any floating point errors.
- Returns
hit_positions – The hit positions of the simulation.
- Return type
ndarray, shape (n_rays, 3)
- get_total_solid_angle_monte_carlo(n_rays=5000000, random_seed=None, return_error=False, verbose=False)¶
Calculate the total solid angle of the bar by Monte Carlo simulation.
- Parameters
n_rays (int, default 5_000_000) – The number of rays to simulate.
random_seed (int, default None) – The random seed of the Monte Carlo simulation. If None, a time-based seed will be used, i.e. non-reproducible.
return_error (bool, default False) – Whether to return the error (uncertainty) of the calculation.
verbose (bool, default False) – Whether to print out the progress of the calculation.
- Returns
total_solid_angle (float) – The total solid angle of the bar in steradians.
error (float, optional) – The uncertainty of the calculation. Only returned if
return_erroris True.
- get_theta_phi_alphashape(delta, alpha, cut=None)¶
Calculate the alphashape of the bar in (theta, phi) coordinates.
- Parameters
delta (int or array of size 3) – Grid spacing in cm.
alpha (float) – The alphashape parameter. The larger the value, the greater the curvature of the alphashape can be. When alpha is zero, the alphashape reduces into a convex hull; when alpha is too large, the alphashape could be “overfitted” to data points.
cut (str, default None) – The cut of the alphashape. Available variables include ‘x’, ‘y’ and ‘z’ in local frame. If None, no cut will be applied.
- Returns
alpha_shape_xy – Vertices that define the alphashape in (theta, phi) coordinates.
- Return type
ndarray, shape (n, 2)
- static _split_theta_phi_alphashape_to_upper_and_lower(ashape)¶
Split the alphashape into upper and lower parts.
After splitting, both parts should form a function of theta. This is a function written mainly to help calculating the azimuthal width \(\delta\phi\) as a function of theta, which then is used to give the geometry efficiency.
- Parameters
ashape (ndarray, shape (n, 2)) – Vertices that define the alphashape in (theta, phi) coordinates.
- Returns
split_ashape – The upper and lower parts of the alphashape. The keys are ‘upper’ and ‘lower’, the values are ndarrays of shape (n, 2).
- Return type
dict
- get_total_solid_angle_alphashape(delta, alpha, return_error=False)¶
Calculate the total solid angle of the bar using the alphashape.
- Parameters
return_error (bool, default False) – Whether to return the error (uncertainty) of the calculation.
- Returns
total_solid_angle (float) – The total solid angle of the bar in steradians.
error (float, optional) – The uncertainty of the calculation. Only returned if
return_erroris True.
- get_total_solid_angle(method='alphashape', **kwargs)¶
Return the total solid angle of the bar.
A wrapper function for the different methods of calculating the total solid angle.
- Parameters
method ('alphashape' or 'monte_carlo') – The method to use to calculate the total solid angle.
kwargs (dict()) – Keyword arguments to pass to the method.
- Returns
total_solid_angle – The total solid angle of the bar in steradians.
- Return type
float
- get_geometry_efficiency_alphashape(delta, alpha, cut=None) tuple[typing.Callable, typing.Callable]¶
Calculate the geometry efficiency of the bar using the alphashape.
The geometry efficiency is defined as the effective azimuthal coverage ratio, i.e. \(\delta\phi/(2\pi)\), as a function of theta.
- Parameters
cut (str or list of str, default None) –
Cut to apply to the dataframe of the bar. Available variables include ‘x’, ‘y’ and ‘z’ in local frame. If None, no cut is applied.
Users should make sure that the every cut string must only split the geometry of the bar into one volume, so cut like
(-10 < x & x < 10)is okay, but(-10 < x & x < 10) & (15 < x & x < 25)is not because there is a gap from x = 10 to x = 15, resulting in two unconnected volumes. To apply cuts that result in multiple volumes, supply a list of cuts instead. Socut = ['(-10 < x & x < 10)', '(15 < x & x < 25)']would be okay.- Returns
delta_phi – A function that takes theta (radian) as an argument and returns the geometry efficiency.
- Return type
callable
- draw_hit_pattern2d(hits, ax, frame='lab', coordinate='spherical', cartesian_coordinates=('x', 'y'), cmap='jet')¶
Draw the hit pattern of the bar with 2D histogram.
- Parameters
hits (ndarray, shape (n, 3)) – The hits to draw.
ax (matplotlib.axes.Axes) – The axes to draw the hits on.
frame ('lab' or 'local') – The frame of reference to use for the hits.
coordinate ('spherical' or 'cartesian') – The coordinate system to use for the hits.
cartesian_coordinates (tuple of str) – The Cartesian coordinates to use for the hits. If
coordinateis not ‘cartesian’, this argument has no effect.cmap (str or matplotlib.colors.Colormap) – The colormap to use for plotting the hits in 2D histogram.
- Returns
hist – The histogram counts of the hits.
- Return type
2D ndarray