arnica.utils package
The utils
The utils package provides helpers around CFD-related problems. They are categorized into several groups, including:
show_mat: A matplotlib helper function for fast matrix plotting with legend and axis naming.
cloud2cloud: An inverse distance interpolator without connectivity.
directed_projection: A projection of vector clouds along their directions.
vector_actions: A set of vector transformation helpers.
plot_density_mesh: A mesh rendering tool using matplotlib hist2d.
axi_shell: A 2D i-j structured mesh mapping axycylindrical splaine-based surfaces.
nparray2xmf: A 1-2-3D i-j-k structured numpy datastructure dumping facility to XDMF format.
The code also mentions several untested and deprecated routines, including:
unstructured_adjacency: An untested mesh handling routine using connectivity.
mesh_tools: An untested 2D mesh generation routine in numpy for solvers.
datadict2file: A deprecated dumping facility for dictionary-like data.
Submodules
arnica.utils.axipointcloud module
Testing a patch mapper 2D feature
The AxiPointCloud class handles axysymmetric 1D meshes with associated variables. The class also provides utility functions for calculating radius (rad), theta angle (theta), and recompute theta range from coordinates (recompute_theta_range_from_coords). Additionally, it offers methods for rotating (rotate) and duplicating (dupli_rotate) the point cloud, as well as saving to an XDMF file (dump).
- class arnica.utils.axipointcloud.AxiPointCloud(xcoor, ycoor, zcoor, name='Unnamed', vars=None, theta_range=None)
Bases:
objectHandle Axysymmetric points clouds as 1D meshs with a dict of variables
- dump(filename)
Dump an XDMF file of the pointcloud
- dupli_rotate(repeat=1)
duplicate by rotation around x, in radians
- Parameters:
repeat – number or repetitions integer
- rad()
Return radius np array from Y and Z
- recompute_theta_range_from_coords()
recompute theta range
- rotate(shift_angle)
rotate around x
- Parameters:
shift_angle – angle in radians float
- theta()
Return theta np array (radians)
range -pi/pi
0 on the y+ axis (z=0, y>0)
spanning -pi to pi
0pi=0deg Y ^ | |
-0.5pi=-90deg o——>Z 0.5pi=90deg
- vars_stack()
Stacked version numpy of variables
shape: (n, k)
- xyz()
Stacked version numpy of coordinates
shape: (n, 3)
arnica.utils.brokenlines_actions module
This module consists of several functions for 2D interactive plotting, primarily used in the opentea/acquisition2D project. The main functions are:
point_in_line: calculates point coordinates on a line based on curvilinear abscissa
link_two_lines: adds midpoint between two lines and returns segment length
is_near_point: checks proximity between points and returns distance if near
corner_coordinates: calculates minimum and maximum rectangle corner coordinates
coords_pix_2_real: converts viewport coordinates to real-world coordinates using calibration data
Additionally, the code includes functions for: - Converting between real-world and pixel coordinates (coords_real_2_pix) - Converting lines between real-world and pixel coordinates (acq_lines_2_real and acq_lines_2_pix) - Finding the closest line to a point (find_line_from_point) - Calculating distances and curvilinear abscissas in geometric calculations (closest_segment_in_line, dist_segment, project_on_line) - Calculating relative position of a point on a line segment (relative_position_segment) - Converting curvilinear abscissa to point coordinates (point_from_curvi) - Projecting a point onto a line segment (unnamed function)
WARNING : no not change the API unless you are also dealing with opentea
WARNING2 : We voluntarily avoid the use of Numpy here. Indeed, The data is expected to be extremely small (dozens of points) The cost of creating/ destroying numpy arrays is bigger than potential accelerations at this scale.
- arnica.utils.brokenlines_actions.acq_lines_2_pix(lines_list: List[List[List[float]]], calib_diag_pix: List[List[float]], calib_diag_real: List[List[float]])
Convert a list of lines stored in pixels into real worlds coordinates
- arnica.utils.brokenlines_actions.acq_lines_2_real(lines_list: List[List[List[float]]], calib_diag_pix: List[List[float]], calib_diag_real: List[List[float]])
Convert a list of lines stored in pixels into real worlds coordinates
- arnica.utils.brokenlines_actions.closest_curvi_in_line(line, x, y) Tuple[int, int, float]
return the closest line wr to a point, with the id of the closest point and the curvilineare abssica
- arnica.utils.brokenlines_actions.closest_line(lines, x, y) Tuple[int, int, float]
return the closest line wr to a point, with the id of the closest point and the curvilineare abssica
- arnica.utils.brokenlines_actions.closest_segment_in_line(line, x, y) Tuple[int, float]
Return the segment index closest to a point
- arnica.utils.brokenlines_actions.coords_pix_2_real(x_pix: float, y_pix: float, calib_diag_pix: List[List[float]], calib_diag_real: List[List[float]]) List[float]
Return coords in real world, from wiewport coords
- arnica.utils.brokenlines_actions.coords_real_2_pix(x_real: float, y_real: float, calib_diag_pix: List[List[float]], calib_diag_real: List[List[float]]) List[float]
Return coords in real world, from wiewport coords
- arnica.utils.brokenlines_actions.corner_coordinates(x0: float, y0: float, x1: float, y1: float) Tuple[float, float, float, float]
Return the minimum and maximum coordinates for the rectangle corners.
- arnica.utils.brokenlines_actions.dist_segment(x0: float, y0: float, x1: float, y1: float, x: float, y: float) Tuple[float, float, float]
Return the normal distance (distance to the line supporting the segment) the lateral distance (distance of the projection on the line to the center of the segment). and the curvilinear abscissa btw 0 and 1
- arnica.utils.brokenlines_actions.find_line_from_point(lines_list: List[List[List[float]]], point: List[float]) int | None
Return the index of the line containing the specified point.
- Parameters:
lines_list (List[List[List[float]]]): List of lines, where each line is a list of points. point (List[float]): The point to search for.
- Returns:
Optional[int]: The index of the line containing the point, or None if not found.
- arnica.utils.brokenlines_actions.is_near_point(x_1: float, y_1: float, x_2: float, y_2: float, tol: float = 0.2) float | None
return distance if within the tolerance in viewport coords
- arnica.utils.brokenlines_actions.link_two_lines(line_ext: List[List[float]], line_int: List[List[float]]) Tuple[List[List[float]], List[List[float]], float]
Add a mid point between the start of two lines to close the volume
each line is prepend by the same point
returns also the lenght of the added segment
- arnica.utils.brokenlines_actions.point_from_curvi(line, point_idx, curvi) Tuple[float, float, float]
Return coordinates and curvilinear abscissa of a position on a line
- arnica.utils.brokenlines_actions.point_in_line(line: List[List], curvi: float) Tuple[float, float]
Return coordinates of a point in a line based on curvilinear abcissa
- arnica.utils.brokenlines_actions.project_on_line(x0: float, y0: float, x1: float, y1: float, x: float, y: float) Tuple[float, float]
Project a point (x, y) onto a line defined by two points (x0, y0) and (x1, y1). Return the coordinates of the projection.
- arnica.utils.brokenlines_actions.relative_position_segment(x0: float, y0: float, x1: float, y1: float, x: float, y: float) float
Return the relative position u of a point P(x, y) with respect to P0(x0, y0) and P1(x1, y1).
Assumes P, P0, and P1 are collinear.
- Position:
u = 0 if P = P0 u = 1 if P = P1 0 < u < 1 if P is between P0 and P1 u < 0 if P is before P0 u > 1 if P is after P1
arnica.utils.cloud2cloud module
interpolate a cloud from an other cloud
- arnica.utils.cloud2cloud.cloud2cloud(source_xyz, source_val, target_xyz, stencil=3, limitsource=None, power=1.0, tol=None)
Interpolate form a cloud to an other
Parameters :
source_xyz : numpy array shape (n_s, 3) either (1000, 3 ) or (10,10,10, 3) source_val : numpy array shape (n_s, k) of k variables target_xyz : numpy array shape (n_t, 3) stencil (int): nb of neigbors to compute (1 is closest point)
Optional keyword arguments
limitsource (int) : maximum nb of source points allowed (subsample beyond) power(float) : Description tol(float) : Description Returns : ———- target_val : numpy array shape (n_t, k)
arnica.utils.cloud2cloud2 module
interpolate a cloud from an other cloud
Alternate version with Rbf for testing purpose. NOT WORKING YET
- arnica.utils.cloud2cloud2.RbfWeights(source, target, power, eps=1e-16)
- arnica.utils.cloud2cloud2.cloud2cloud2(source_xyz, source_val, target_xyz, power=1.0)
Interpolate form a cloud to an other NOT WORKING YET
Parameters :
source_xyz : numpy array shape (:, 3) or (:,:, 3) or (:,:,:, 3) source_val : numpy array shape (:, 3) or (:,:, k) or (:,:,:, k) k variables , first dims equal to source mesh. target_xyz : numpy array shape (:, 3) or (:,:, 3) or (:,:,:, 3) stencil (int): nb of neigbors to compute (1 is closest point)
Optional keyword arguments
limitsource (int) : maximum nb of source points allowed (subsample beyond) power(float) : Description tol(float) : Description Returns : ———- target_val : numpy array shape (:, 3) or (:,:, 3) or (:,:,:, 3) , first dims equal to target mesh.
arnica.utils.curve_feat_extract module
Extract features from a curve
- arnica.utils.curve_feat_extract.amax_keepshape(arr, axis)
expand “row” POS from axis AXIS of an array ARR everywhere else
- Args:
arr (np.array): source array axis (int): index of axis to expand
- Returns:
np.array: amax on the same shape
>>> a = np.array([[0, 1, 0, 0, 0], [0, 1, 1, 1, 1], [0, 1, 2, 3, 3]]) >>> amax_keepshape(a, axis=1, pos=3) array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [3, 3, 3, 3, 3]])
- arnica.utils.curve_feat_extract.amin_keepshape(arr, axis)
expand “row” POS from axis AXIS of an array ARR everywhere else
- Args:
arr (np.array): source array axis (int): index of axis to expand
- Returns:
np.array: amin on the same shape
>>> a = np.array([[0, 1, 0, 0, 0], [0, 1, -1, 1, 1], [1, 1, 2, 3, 4]]) >>> amin_keepshape(a, axis=1, pos=3) array([[0, 0, 0, 0, 0], [-1, -1, -1, -1, -1], [1, 1, 1, 1, 1]])
- arnica.utils.curve_feat_extract.mask_boundary_layer(source, eps=0.1, gain=1.0, axis=0)
Identify the cells relative to a boundary layer in a numpy multi-d array. If no fluctuation detected, only the “wall” node is set to 1.
- Args:
source (np.array): source array eps (float): ]0,1[ relative fluctuation thresold (0.1 is 10% of max curve amplitude) gain (float): >0 increase of decrease the width of the layer found axis (int): index of axis to search
- Returns:
np.array: masked array equal to one on the fluctuation side.
>>> a = np.array( [[ 0, 1, 0, 0, 0] [ 0, 1, 1, 1, 1] [ 0, 3, 2, 3, 4] [ 0, 1, -2, 3, 4] [ 0, 0, 0, 0, 0] [ 0, 1, 2, 3, 4]] ) >>> mask_boundary_layer(ource, eps=0.1, axis=1) array( [[1, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] )
- arnica.utils.curve_feat_extract.reptile(arr, axis, pos)
expand “row” POS from axis AXIS of an array ARR everywhere else
- Args:
arr (np.array): source array axis (int): index of axis to expand pos (int): index of element to expand
- Returns:
np.array: Expanded array
>>> a = np.array([[0, 1, 0, 0, 0], [0, 1, 1, 1, 1], [0, 1, 2, 3, 4]]) >>> reptile(a, axis=1, pos=3) array([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [3, 3, 3, 3, 3]])
arnica.utils.datadict2file module
This module converts dictionaries of 2D NumPy arrays into XMF files for visualization or storage.
- arnica.utils.datadict2file.dump_dico_0d(filename, data_dict)
Write statistics to file
Parameters:
- filenamethe file name to which array dictionnary are dumped
possible extensions : - .xlsx (if pandas is found)
.csv (default format)
data_dict : a dictionnary holding the data arrays
Returns:
None
- arnica.utils.datadict2file.dump_dico_1d_nparrays(filename, data_dict)
Write statistics to file
Parameters:
- filenamethe file name to which array dictionnary are dumped
possible extensions : - .xlsx (if pandas is found)
.csv (default format)
data_dict : a dictionnary holding the data arrays
Returns:
None
- arnica.utils.datadict2file.dump_dico_2d_nparrays(data_dict, filename, x_coords, y_coords, z_coords, **kw_args)
Parameters:
- data_dictdictionnary holding the 2d arrays, on the format
data_dict[key] = array(n1, n2) where (n1, n_2) is a subset of (n_x, n_y, n_z)
filename : the xmf filename
- <x|y|z>_coords2d numpy arrays for coordiantes over each axis
must be of shape (n_1, n_2)
keyword args (optional):
- timephysical time corresponding to the array
used in the xmf file as <Time Value=”time”….
- grid_namethe name of the grid to be used in the xmf file
as <Grid Name=”grid_name”….
- domain_namethe name of the domain to be used in the xmf file
as <Domain Name=domain_name….
Returns:
None
- arnica.utils.datadict2file.dump_dico_2d_time_nparrays(data_dict, root_path, prefix, x_coords, y_coords, z_coords, **kw_args)
Dumps a dictionnary of time series 2d arrays to xmf files
Parameters:
- data_dictdictionnary holding the times series 2d
arrays, on the format data_dict[key] = array(n_time, n1, n2) where:
n_time is the number of time steps
(n1, n_2) is a subset of (n_x, n_y, n_z)
prefix : the prefix to be used to generate xmf filenames
- <x|y|z>_coords2d numpy arrays for coordiantes over each axis
must be of shape (n_1, n_2)
keyword args (optional):
- stepsa list of integer time series steps
that will be used to generate xmf files on the format : <prefix>_<step>.xmf if None steps will be generated as the range of time dimension of data arrays
- timesa list of float physical times that will
be used in xmf files to describe the time of each step. if None will be generated as the range of time dimension of data arrays
- arnica.utils.datadict2file.dump_dict2xmdf(filename, grid, data_dict)
Dump 2D matrices into hdf5 file
- Parameters:
filename (str) – Name of the hdf file
grid – Array of xyz-coordinates of shape (n_v, n_u, 3)
data_dict – Dict of field arrays of shape (n_v, n_u)
- arnica.utils.datadict2file.plot_dict_data_as_file(data_dict, filename, x_data, y_data, **kw_args)
Generates and write XY-plot to file
Parameters:
- filenamethe file to which the plot is written it contains
the extension that defines the format e.g: ‘plot_toto.png’ Supported formats/extensions : png, pdf, ps, eps and svg If not provided, by default “pdf” extension is used.
data_dict : a dictionnary holding the data arrays x_data : the key to the array holding the abscissa data y_data : the key to the array holding the y data
keyword args (optional):
x_label : label of the x axis, by default x_data is used (supports latex) y_label : label of the y axis, by default y_data is used (supports latex)
arnica.utils.directed_projection module
Module to compute the directed projection of a point to a surface along a direction
___
x---->
OST : Seven nation Army (Westworld), R. Djawadi
- arnica.utils.directed_projection.compute_dists(points, directions, points_surf, normals_surf, tol)
Compute cylindrical distances
For a i-number of points coordinates, compute the cylindrical distances between the i,p-number of nodes with the i-number of axis.
The array is then clipped according to the node normals and the direction of the drills.
- Parameters:
points (np.array) – Array of dim (i,3) of drill float coordinates
directions (np.array) – Array of dim (i,3) of drill float axis components
points_surf (np.array) – Array of dim (i,p,3) of nodes float coordinates
normals_surf (np.array) – Array of dim (i,p,3) of nodes float normal components
params – Dict of parameter
- Returns:
cyl_dists - Array of dim (i,p) of float cylindrical distances
- arnica.utils.directed_projection.intersect_plan_line(xyz_line, vec_line, xyz_plan, nml_plan)
Compute intersection coordinates of a line and a plan
Line defined by a point xyz_line and a vector vec_line
Plan defined by a point xyz_plan and a normal nml_plan
Arrays dimensions must be consistent together.
- ::
- nml_plan xyz_line
A x | / | / vec_line
___x______I________sample_curve_from_cloud xyz_plan
Intersection point
- Parameters:
xyz_line – Array of coordinates of shape (3,) or (n, 3)
vec_line – Array of components of shape (3,) or (n,3)
xyz_plan – Array of coordinates of shape (3,) or (n,3)
nml_plan – Array of complonents of shape (3,) or (n,3)
- Returns:
xyz_intersect - Array of coordinates of shape (3,) or (n,3)
- arnica.utils.directed_projection.project_points(points_source, normals, points_target)
Compute the projected points, radial dists and axial dists
Compute projection from source points S of dim (k,) or (i,k),on a plan defined by normals N of dim (k,), (i,k), (p,k) or (i,p,k),and points T of dim (k,), (i,k), (p,k), (i,p,k). With :
i : Number of points to project
p : Number of points defining plans
k : Dimension of the domain
S T1 T2 \ ⁄ ⁄ \ ⁄ ⁄ axi_d1 \ ⁄\ ⁄ rad_d1 ⁄ \ ⁄ ⁄ rad_d2 \ ⁄ \ ⁄ axi_d2 \ ⁄\ ⁄ \ ⁄ X proj_pt2 \ NS : Points source N : Normal T : Points target axi_d : Axial distance of the point T projected on the axis Ax rad_d : Cylindrical or Radial distance between T and the axis Ax
——> ->
axi_dist = (T - S) . N
————–> -> -> projected_point = S + N * axi_dist
-> ————–>
rad_dist = norm(T - projected_point)
- Parameters:
points_source (np.array) – Array of source points coordinates
proj_axis (np.array) – Array of normal components defining projection plans
points_target (np.array) – Array of points coordinates defining projection plans
- Returns:
projected_points - Array of shape points_target.shape of float coordinates
axi_dists - Array of shape points_target.shape[:-1] of float distances
rad_dists - Array of shape points_target.shape[:-1] of float distances
- arnica.utils.directed_projection.projection_kdtree(points, directions, point_surface, normal_surface, **kwargs)
Project the n points following the direction on the m suface.
- Parameters:
points – Array of [p] points of shape (p,3)
directions – Array of [p] direction vectors of shape (p,3)
point_surface – Array of [n] surface nodes of shape (n,3)
normal_surface – Array of [n] surface node normals of shape (n,3)
neigbors (int) – Number [k] of neigbors to take into account
tol (float) – Maximum distance beyond cyl dist with big set to BIG
project (bool) – If True, first project points along normal.
- Returns:
projected_pts - “t” nparray of shape (n,3), projected on the surface
indexes - neigborhood of the points (n,k)
cyl_dist - cylindrical distance of p with each neighbor (n,k)
< shp_dist > ______s___________t__________________ |' . A | ' .< cyl_dist > . v .< surface_dist> 4 . / . / . p V align : alignment (pscal of two unit vectors, in [-1,1])
Algorithm :
If project bool is True, first compute [p] projection from [p] points along the [p,1] spherical closest node’s normal. If False, projected_points = points.
Reduce computation to the [p,k] spherical closest nodes of the [p] projected_points
Compute the [p,k] cylindrical distances from the [p,k] closest nodes to the [p] lines defined by the [p] projected points and the [p] direction vectors.
arnica.utils.mesh_tool module
This module contains function to create and modify meshes
- arnica.utils.mesh_tool.dilate_center(x_coor, y_coor, perturbation=0.1)
perturb cartesian mesh dilatation in the center
Parameters :
x_coor : numpy array (n,m) , x_coordinates y_coor : numpy array (n,m) , y_coordinates perturbation : float, amplitude of the perturbation perturbation
with respect to the grid size
Returns :
x_coor : numpy array (n,m) , x_coordinates shifted y_coor : numpy array (n,m) , y_coordinates shifted
- arnica.utils.mesh_tool.gen_cart_grid_2d(gridrange, gridpoints)
Generate cartesian grid.
Parameters :
gridrange : tuple of floats, dimensions of the grid gridpoints : tuple of ints (n,m), sampling on the grid
Returns :
x_coor, y_coor : numpy arrays (n,m) with coordinates
- arnica.utils.mesh_tool.gen_cyl_grid_2d(r_min, r_max, r_points, theta_min, theta_max, theta_points)
Generate a cylindrical grid center on x = 0 and y = 0
Parameters
r_min : inner radius r_max : outer radius theta_min : lower angle [0, 2 * pi] theta_max : upper angle [0, 2 * pi] r_points : number of points in the radial direction theta_points : number of points in the tangential direction
Returns
x_coor : x coordinates of the mesh y_coor : y coordinates of the mesh
arnica.utils.nparray2xmf module
This module creates EnSight-compatible files to visualize data. The main class, NpArray2Xmf, outputs data in XDMF format. It has methods for initializing the class, creating grids, and adding fields. The module also defines an XML namespace for XInclude. Other functions include xmf_dump (creates an XDMF descriptor file), dump (writes the final file), and create_time_collection_xmf (creates a single xmf file holding time collections of other xmf files).
- class arnica.utils.nparray2xmf.NpArray2Xmf(filename, domain_name=None, mesh_name=None, time=None, xmf_only=False)
Bases:
objectmain class for data output in XDMF format
- add_field(nparray_field, variable_name)
add a field, assuming same shape as nparray of coordiantes
- create_grid(nparray_x, nparray_y, nparray_z)
create the grid according to numpy arrays x, y ,z if arrays are 1D, switch to cloud point if arrays are 2D, switch to quad connectivity if arrays are 3D, switch to hexaedrons connectivity
- dump()
dump the final file
- xmf_dump()
create XDMF descriptor file
arnica.utils.plot_ave_with_interval module
Plot graphs from 1D average array with or without its confidence interval. Rotate the graph from 90 deg.
- arnica.utils.plot_ave_with_interval.plot_ave_with_interval(x_arr, average, profile='average-interval', upper=None, lower=None, **kw_args)
Plot average profile with or without confidence interval
- Parameters:
x_arr (np.array) – Array of float of x-axis
average (np.array) – Array of float of average curve
profile (str) – Plot type (average-interval, average, integral)
upper (np.array) – Array of float of upper interval values
lower – Array of float of lower interval values
Optional Keyword Args:
- Parameters:
x_label (str) – Label for x-axe
y_label (str) – Label for y-axe
style (str) – Style of the axes - plain or sci
- Returns:
plt - Matplotlib.pyplot object
arnica.utils.plot_quad2tri module
Module to plot a field on cartesian mesh through a triangular mesh
The module defines two main functions: get_connectivity and quad2tri.
get_connectivity generates connectivities for a triangular mesh given indices i, j, and shell shape. It returns an array of triangle point indexes.
quad2tri divides a Cartesian grid into an extended triangular grid, calculates the triangulation object and field values at nodes, and returns these along with the connectivity array.
- arnica.utils.plot_quad2tri.get_connectivity(i, j, shape)
Generate connectivities
- Parameters:
i (int) – Index of the cell on u-axis
j (int) – Index of the cell on v-axis
shape – Shape of the shell
- Returns:
connectivity - Array of shape (t, 3) of triangle point indexes
- arnica.utils.plot_quad2tri.plot_quad2tri(grid, title, field, shading=True)
Generate a plot of a field on a x,y shell cartesian grid
The cartesian grid is converted into a triangle grid with connectivities. The field is extended by interpolation on the new points created. The plot is generated from the points coordinates extended and the connectivity, using tripcolor of matplotlib.
If shading is True : using ‘gouraud’ from field value defined at nodes. If shading is False : using ‘flat’ from mean field value defined at the nodes or field value defined at the cell.
- Parameters:
grid – Array of shape (n_u, n_v, 2) of cartesian coordinates
title (str) – Title of the plot
field – Array of shape (n_u, n_v) of field values
shading (bool) – Define if plot is shaded of not
- Returns:
plt - Matplotlib object containing the graph
- ::
1 quad 4 tri
O———O O———O | | | / | | | | / | | | | / | | | —> | O | | | | / | | | | / | | | | / | O———O O———O
- arnica.utils.plot_quad2tri.quad2tri(grid, field)
Divide a cartesian grid into an extended triangular grid
- Parameters:
grid – Array of shape (n_u, n_v, 2) of cartesian coordinates
:param field Array of shape (n_u, n_v) of field values
- Returns:
triangulation - Matplotlib.tri.Triangulation object containing extended grid coordinates and connectivity array
field_at_node - Array of extended field values stored at the node
arnica.utils.plotcsv module
Utility to create plots of CSV data in pure terminal environments
- arnica.utils.plotcsv.plot_csv_data(filename, keys, delimiter=None)
Create a plot from a CSV file.
The FILENAME is read with Pandas KEYS is a list of headers [“y/Y”, “Cows”, “Cats”] Plot KEYS[1:] with respect to KEYS[0]
Parameters:
- param filename:
str, path to the csv file
- param keys:
list of str, names of the elements to plot
- param delimiter:
char, delimiter of the CSV file
Returns :
graph: a string representing the graph
arnica.utils.sample_curve_from_cloud module
SORT AND SAMPLE POINTS FROM CURVE
- arnica.utils.sample_curve_from_cloud.get_neighbor(kdtree, point, list_points)
Find the closiest neighbor that has not already been found
From the kdtree, find the two closiest points of ‘point’, the 1st being itself. If the second closiest point has already been found, then the number of researched points is increased until finding a point that has not already been found.
- Parameters:
kdtree – KDTree of all points.
point (np.array) – Array of dim (k,) of point float coordinates.
list_points – List of integer indexes
- Returns:
index - Index (int) of the unfound closiest point.
dist - Distance (float) of the closiest point from point.
- arnica.utils.sample_curve_from_cloud.sample_arrays_by_dist_interval(dists, samples_res, *args)
Sample data and optional args at each sample_res along data
From an array containing the distance between sorted points, and from a sample resolution defined by the distance between two samples, the function picks up the indexes corresponding to a sample, and returns an array of sampled distances and arrays of sampled arguments from those indexes.
- ::
……………. .__.__.__.__.__.
… .. .__ ..
. . | . . ……………. ===> | .__.__.__.__.__. . . . .
. ………………. . .__.__.__.__.__.__. .. ..
- …………………. 9 .__.__.__.__.__.__.__.
9 321 3 2 1
- Parameters:
dists (np.array) – Array of dim (n,) of floats
samples_res (float) – Sample resolution for sampling
args – Tuple de data of dim (n,)
- arnica.utils.sample_curve_from_cloud.sample_points_from_cloud(points_coor, starting_pt, n_samples=None, samples_res=None)
Sort and sample unsorted curve
First the point coordinates are sorted by distances. Secondly compute sample resolution if not provided. Finally sample the ordered indexes points by distance. Returns the array of coordinates ordered and sampled.
- Parameters:
points_coor – Array of dim (n,k) of points coordinates
starting_pt (np.array) – Array of dim (k,) of starting point coordinates
n_samples (int) – Number of samples to extract
sample_res (float) – Resolution of the sampling
- Returns:
skin_cyl - Array of dim (n_samples, 3) of coordinates
- arnica.utils.sample_curve_from_cloud.sort_points_by_dist(points_coor, starting_pt)
Reorder a point cloud by distances . From a starting fictive point, the first point 1 of the spline iget_neighbors found, as the closiest one. From that point, the following points are obtained with get_neighbor() until having sorted all points.
- ::
……………. ……………. r/y
… 2 8 .. … .. ^
. . . . | x . ……………. ===> . ……………. o—–> . . . .
. ………………. . ………………. .. ..
- …………………. ………………….
- 1 3 X 8 321
starting_pt
- Parameters:
points_coor (np.array) – Array of dim (n,k) of points coordinates
starting_pt (np.array) – Array of dim (k,) of starting pt coordinates
- Returns:
ordered_indexes - Array of dim (n,) of indexes
ordered_dists - Array of dim (n,) of floats
arnica.utils.show_mat module
This script contains function to properly visualize matrices
arnica.utils.structarr_io module
This module provides a way to convert between a dictionary of NumPy arrays and a structured array
- arnica.utils.structarr_io.da2sa(data_dict: dict) array
copy a dictionary of numpy arrays to a Structured array
- arnica.utils.structarr_io.sa2da(structured_array: array) dict
Convert a structured array to a dict of arrays
arnica.utils.timer_decorator module
small timer function
- arnica.utils.timer_decorator.timing(function)
lazy method to time my function
arnica.utils.unstructured_adjacency module
Efficient implementation of unstructured mesh operations
Created Feb 8th, 2018 by C. Lapeyre (lapeyre@cerfacs.fr)
- class arnica.utils.unstructured_adjacency.UnstructuredAdjacency(connectivity)
Bases:
objectEfficient scipy implementation of unstructured mesh adjacency ops
The connectivity is stored in a sparse adjencency matrix A of shape (nnode, ncell). The gather operation on vector X (nnode) yields the scattered vector Y (ncell), and the scatter operation yields the filtered vector X’ (nnode). This writes:
Y = 1/nvert . A . X X’ = 1/bincount . A^t . Y
where ^t is the transpose operation.
The gatter-scatter operation resulting in filtering X can be performed efficiently by storing:
F = 1/bincount . A^t . 1/nvert . A X’ = F . X
- get_cell2node()
Return the cell2node function
- get_filter(times=1)
Return the full gather + scatter filter operation
If you need to perform the operation N times, you can use the times attribute.
- get_node2cell()
Return the node2cell function
- property ncell
Total number of cells
- property ncell_per_nvert
Dictionary of {nvert: ncell}
For each type of element with nvert vertices, stores the nubmer of cells ncell
arnica.utils.vector_actions module
Module concerning some 3D vector manipulations in numpy
OST :Mercy in Darkness, by Two Steps From Hell
- arnica.utils.vector_actions.angle_btw_vects(np_ar_vect1, np_ar_vect2, convert_to_degree=False)
compute the angle in deg btw two UNIT vectors
- arnica.utils.vector_actions.cart_to_cyl(vects_xyz)
Transform vects from xyz-system to xrtheta-system
x -> x : x = x y -> r : r = sqrt(y^2 + z^2) z -> theta : theta = arctan2(z,y)
- Parameters:
vects_xyz (np.array) – Array of dim (n,3) of xyz components
- Returns:
vects_cyl - Array of dim (n,3) of xrtheta components
- arnica.utils.vector_actions.clip_by_bounds(points_coord, bounds_dict, keep='in', return_mask=False)
Clip a cloud by keeping only or removing a bounded region
The dict to provide must be filled as follow : bounds_dict = {component_1 : (1_min, 1_max),
compoment_2 : (2_min, 2_max), …}
component_1 = [“x”, “y”, “z”, “r”, “theta”]
The bounded region can either be :
A 1D slice if only 1 component is provided ;
A 2D box if 2 components are provided ;
A 3D box if 3 components are provided.
If keep=”in”, returns the point coordinates inside the bounds. If keep=”out”, returns the point coordinates outside the bounds.
If returns=True, returns the coordinates clipped If returns=False, returns the mask of boolean than can be applied on other arrays
- Parameters:
point_cloud (np.array) – Array of dim (n,k) of coordinates
bounds_dict – Dict of MAX lengh k of tuple of floats
keep (str) – Either keeps what is inside or outside
- Returns:
points_coord_clipped - Array of dim (m,k) with m<=n
OR - mask - Array of dim (n,) of booleans
- arnica.utils.vector_actions.cyl_to_cart(vects_cyl)
Transform vects from xrtheta-system to xyz-system
x -> x : x = x r -> y : y = r * cos(theta) theta -> z : z = r * sin(theta)
- Parameters:
vects_cyl (np.array) – Array of dim (n,3) of xrtheta components
- Returns:
vects_xyz - Array of dim (n,3) of xyz components
- arnica.utils.vector_actions.dilate_vect_around_x(azimuth, np_ar_vect, angle_deg_init=None, angle_deg_targ=360)
- dilate vectors around axis x from a specified initial range angle
to a target range angle.
Parameters :
np_ar_vect : numpy array of dim (n,3) angle_deg_targ : tuple or float
Returns :
numpy array of dim (n,3)
- arnica.utils.vector_actions.make_radial_vect(coord, vects)
Recalibrate vectors to make them radial.
The vectors are readjusted to cross x-axis. It is mainly done for nodes on the limit of the boundary for axi-cylindrical geometries.
- Parameters:
coord (np.array) – Array of dim (n,3) of float coordinates
vects (np.array) – Array of dim (n,3) of float components
- Returns:
radial_vect - Array of dim (n,3) of float components
- arnica.utils.vector_actions.mask_cloud(np_ar_xyz, axis, support)
mask a cloud of n 3D points in in xyz axis among x,y,z,theta,r support a 2 value tuple : (0,3), (-12,float(inf))
x and (0,3) reads as 0 <= x < 3 ( lower bound inclusive) z and (-12,float(inf)) reads as -12 <= z theta in degree, cyl. coordinate around x axis - range -180,180 - 0 on the y+ axis (z=0, y>0)
- arnica.utils.vector_actions.renormalize(np_ar_vect)
renormalize a numpy array of vectors considering the last axis
- arnica.utils.vector_actions.rotate_vect_around_axis(xyz, *tuples_rot)
Rotate vector around vector or series of vector
- Parameters:
xyz – Array of xyz-coordinates of shape (n,3) :param tuples_rot: List of tuple
with rotation data : Axis array of shape (3,) axis, Float angle in degree
- Returns:
Array of rotated xyz-coordinates of shape (n,3)
- arnica.utils.vector_actions.rotate_vect_around_x(np_ar_vect, angle_deg)
rotate vector around axis x in degree
- arnica.utils.vector_actions.rtheta2yz(rrr, theta)
return yz fror rtheta , theta in radians measure of ange in the yz plane,
range -pi/pi
0 on the y+ axis (z=0, y>0)
spanning -pi to pi
0pi=0deg Y ^ | | -0.5pi=-90deg o------>Z 0.5pi=90deg
- arnica.utils.vector_actions.vect_to_quat(vect_targ, vect_source)
Generate a quaternion from two vectors
A quaternion is a rotation object. From two vectors, the rotation angle and the rotation axis are computed. The rotation vector generates then a quaternion for each serie of vectors.
- Parameters:
vect_targ (np.array) – Array of dim (n,3) of vect components
vect_source (np.array) – Array of dim (n,3) of vect components
- Returns:
quat - Array of quaternion of dim (n,)
- arnica.utils.vector_actions.yz_to_theta(np_ar_vect)
return theta , a radians measure of ange in the yz plane,
range -pi/pi
0 on the y+ axis (z=0, y>0)
- spanning -pi to pi
0pi=0deg
-0.5pi=-90deg o——>Z 0.5pi=90deg