Utility Classes
- class opencsp.common.lib.geometry.EdgeXY.EdgeXY(vertices: Vxy, curve_data: dict = {'type': 'line'}, closed: bool = False)
Bases:
objectRepresentation of a 2D edge.
- __init__(vertices: Vxy, curve_data: dict = {'type': 'line'}, closed: bool = False)
Representation of a 2D edge.
- Parameters:
vertices (Vxy) – A length 2 vector of the beginning and end vertex of the edge.
curve_data (dict, optional) – Additional curve data. The default is {‘type’: ‘line’}. This is reserved for further future implementations of non-linear edge types.
closed (bool, optional) – Flag for weather or not the edge is closed or not. The default is False. This is reserved for further future implimentations of non- linear edge types.
- flip()
Returns a copy of the edge with its orientation flipped.
- flip_in_place()
Flips the edge. The data is updated within the object.
- sample(count: int) Vxy
Returns a sample of ‘count’ points evenly spaced on the edge
count must be greater than or equal to 2. egde.sample(2) should be the same as edge.vertices
- property curve
Returns the curve object used to define the edge.
- property is_closed: bool
Returns if the edge is closed or not.
- class opencsp.common.lib.geometry.FunctionXYAbstract.FunctionXYAbstract
Bases:
ABCAbstract class for a funciton of two variables
Abstract Methods
value_at(self, x: float, y: float) -> float: # "Returns the value of the function at the given x and y values." __getstate__(self): # "Returns a serializable object for pickleing." __setstate__(self, d): # "Takes in __getstate__(self)'s output to recreate the object `self` that was passed into __getstate__" in_domain(x, y) -> bool: # "Returns True if the (x,y) pair is in the domain, otherwise False."
- __init__()
- abstract in_domain(x: float, y: float) bool
Returns True if the (x,y) pair is in the domain, otherwise False.
- lift(p: Pxy) Pxyz
Takes in a Pxy point and returns the Pxyz point where the z values are the values that correspond to the functions results for value_at(p.x, p.y)
- abstract value_at(x: float, y: float) float
Returns the value of the function at the given x and y values.
- class opencsp.common.lib.geometry.FunctionXYContinuous.FunctionXYContinuous(funcXY_string: str, domain: list[RegionXY] | None = None)
Bases:
FunctionXYAbstractWrapper for function that can be pickled.
Extends the FunctionXYAbstract class.
Constructor
FunctionXYContinuous(funcXY_string: str, domain: list[RegionXY])
- param funcXY_string:
String that contains the function that is supposed to be represented.
Note: The function must use “x” and “y” as the vareiables.
- type funcXY_string:
str
- classmethod from_array(x_domain: ndarray, y_domain: ndarray, values: ndarray)
Create an instance of FunctionXYContinuous using a 2d array
- Parameters:
x_domain (array, the values of x that will be used to access values of the array)
y_domain (array, the values of y that will be used to access values of the array)
values (2d array, the values that will be returned when x and y are used)
- in_domain(x: float, y: float) bool
Returns True if the (x,y) pair is in the domain, otherwise False.
- value_at(x: float, y: float) float
Returns the value of the function at the given x and y values.
- class opencsp.common.lib.geometry.FunctionXYDiscrete.FunctionXYDiscrete(values: dict[tuple[float, float], float])
Bases:
FunctionXYAbstractA class representing a discrete function defined by scattered (x, y) points and their corresponding values.
This class allows for the evaluation of function values at specified (x, y) coordinates and provides methods for checking if points are within the function’s domain.
- __init__(values: dict[tuple[float, float], float]) None
Initializes a FunctionXYDiscrete object with the specified values.
- Parameters:
values (dict[tuple[float, float], float]) – A dictionary mapping (x, y) coordinate pairs to their corresponding function values.
- draw(view: View3d)
Draws the function in a 3D view.
- Parameters:
view (View3d) – The 3D view in which to draw the function.
- Return type:
None
- classmethod from_array(x_domain: ndarray, y_domain: ndarray, values: ndarray)
Creates an instance of FunctionXYDiscrete using a 2D array.
- Parameters:
x_domain (np.ndarray) – The values of x that will be used to access values of the array.
y_domain (np.ndarray) – The values of y that will be used to access values of the array.
values (np.ndarray) – A 2D array containing the values that will be returned when x and y are used.
- Returns:
An instance of FunctionXYDiscrete initialized with the provided domains and values.
- Return type:
- Raises:
ValueError – If the size of the domain does not match the size of the value array.
- in_domain(x: float, y: float) bool
Checks if the specified (x, y) coordinates are within the domain of the function.
- Parameters:
x (float) – The x-coordinate to check.
y (float) – The y-coordinate to check.
- Returns:
True if the (x, y) pair is within the domain, False otherwise.
- Return type:
bool
- value_at(x: float | Iterable[float], y: float | Iterable[float]) float | ndarray[float]
Retrieves the function value at the specified (x, y) coordinates.
- Parameters:
x (float or Iterable[float]) – The x-coordinate(s) at which to evaluate the function.
y (float or Iterable[float]) – The y-coordinate(s) at which to evaluate the function.
- Returns:
The function value(s) at the specified coordinates.
- Return type:
float or np.ndarray
- Raises:
ValueError – If the (x, y) pair is not within the domain of the function or if the lengths of x and y do not match.
- class opencsp.common.lib.geometry.FunctionXYGrid.FunctionXYGrid(values: ndarray, limits: tuple[float, float, float, float] | None = None)
Bases:
FunctionXYAbstractDiscrete Fuction defined by a grid. This object uses x:column and y:row. When accessing, this looks like column major.
- Parameters:
values (numpy array) – 2 dimensional
limits (4-tuple) – in the form (smallest x, largest x, smallest y, largest y)
- __init__(values: ndarray, limits: tuple[float, float, float, float] | None = None) None
Represents a discrete function of equispaced points in its domain. Defined by an array and the location of the 4 corners of that array in the funciton space.
- Parameters:
(np.ndarray) (values) – 2d array representing the values of the function.
(tuple[float (limits)
float (Defaults to None.)
float
float] (Defaults to None.)
optional) (Defaults to None.)
- draw(view: View3d, functionXY_style: RenderControlFunctionXY | None = None)
- in_domain(x: float, y: float) bool
Takes in a pair of elements in the form (x:float, y:float) and returns true if the pair is in the domain of self.
- to_index_values(x: float, y: float) tuple[int, int]
- value_at(x: float | Iterable[float], y: float | Iterable[float]) float | ndarray[float]
Returns the value of the function at the given x and y values.
- class opencsp.common.lib.geometry.Intersection.Intersection(intersection_points: Pxyz)
Bases:
objectA class representing the intersection points of light paths with a plane.
This class provides methods for calculating intersections of light paths with planes, as well as utilities for managing and analyzing these intersection points.
- __init__(intersection_points: Pxyz)
Initializes the Intersection instance with the given intersection points.
- Parameters:
intersection_points (Pxyz) – The intersection points to be stored in this instance.
- draw(view: View3d, style: RenderControlPointSeq | None = None)
Draws the intersection points in a 3D view.
- Parameters:
view (View3d) – The 3D view in which to draw the intersection points.
style (RenderControlPointSeq, optional) – The style to use for rendering the points. Defaults to None.
- draw_subset(view: View3d, count: int)
Draws a subset of intersection points in a 3D view.
- Parameters:
view (View3d) – The 3D view in which to draw the intersection points.
count (int) – The number of points to draw from the intersection points.
- classmethod empty_intersection()
Creates an empty Intersection object.
- Returns:
An Intersection object with no intersection points.
- Return type:
- classmethod from_hdf(filename: str, intersection_name: str = '000')
Loads intersection points from an HDF5 file.
- Parameters:
filename (str) – The path to the HDF5 file containing intersection data.
intersection_name (str, optional) – The name of the intersection dataset to load. Defaults to “000”.
- Returns:
An Intersection object containing the loaded intersection points.
- Return type:
- get_centroid() Pxyz
Calculates the centroid of the intersection points.
- Returns:
The centroid of the intersection points as a Pxyz object.
- Return type:
- classmethod plane_intersec_vec(ray_trace: RayTrace, plane: tuple[Pxyz, Uxyz], save_in_file: bool = False, save_name: str | None = None, verbose: bool = False)
Calculates intersection points of light paths with a specified plane.
This method uses a vectorized algorithm to find where light paths intersect with a plane defined by a point and a normal vector.
- Parameters:
ray_trace (RayTrace) – The RayTrace object containing the light paths to be analyzed.
plane (tuple[Pxyz, Uxyz]) – A tuple containing a point on the plane (Pxyz) and the normal vector to the plane (Uxyz).
save_in_file (bool, optional) – If True, saves the intersection data to a file. Defaults to False.
save_name (str, optional) – The name of the file to save the intersection data. Required if save_in_file is True.
verbose (bool, optional) – If True, enables verbose output for debugging purposes. Defaults to False.
- Returns:
An Intersection object containing the calculated intersection points.
- Return type:
- Raises:
ValueError – If the intersection calculation fails or if the input parameters are invalid.
- classmethod plane_intersect_from_ray_trace(ray_trace: RayTrace, plane: tuple[Pxyz, Uxyz], save_in_file: bool = False, save_name: str | None = None, verbose: bool = False)
Calculates intersection points of light paths with a specified plane.
This method uses a vectorized algorithm to find where light paths intersect with a plane defined by a point and a normal vector.
- Parameters:
ray_trace (RayTrace) – The RayTrace object containing the light paths to be analyzed.
plane (tuple[Pxyz, Uxyz]) – A tuple containing a point on the plane (Pxyz) and the normal vector to the plane (Uxyz).
save_in_file (bool, optional) – If True, saves the intersection data to a file. Defaults to False.
save_name (str, optional) – The name of the file to save the intersection data. Required if save_in_file is True.
verbose (bool, optional) – If True, enables verbose output for debugging purposes. Defaults to False.
- Returns:
An Intersection object containing the calculated intersection points.
- Return type:
- Raises:
ValueError – If the intersection calculation fails or if the input parameters are invalid.
- classmethod plane_lines_intersection(lines: tuple[Pxyz, Vxyz], plane: tuple[Pxyz, Uxyz]) Pxyz
Calculates intersection points of multiple lines with a specified plane.
This method determines where each line intersects with the plane defined by a point and a normal vector.
- Parameters:
lines (tuple[Pxyz, Vxyz]) – A tuple containing a point (Pxyz) and a direction vector (Vxyz) for the lines. Each index in the points should correspond to the same index in the directions. Note that only one Pxyz and Vxyz is needed to represent multiple lines.
plane (tuple[Pxyz, Uxyz]) – A tuple containing a point on the plane (Pxyz) and the normal vector to the plane (Uxyz). Each index in the points should correspond to the same index in the directions. Note that only one Pxyz and Vxyz is needed to represent multiple lines.
- Returns:
The intersection points (x, y, z) for each line with the plane. Shape (3, N), where N is the number of lines.
- Return type:
- Raises:
ValueError – If the lines are parallel to the plane or if the input parameters are invalid.
Notes
Disregards direction of line.
- save_to_hdf(hdf_filename: str, intersection_name: str = '000')
Saves the intersection points to an HDF5 file.
- Parameters:
hdf_filename (str) – The path to the HDF5 file where the intersection data will be saved.
intersection_name (str, optional) – The name of the intersection dataset to save. Defaults to “000”.
- to_flux_mapXY(bins: int) FunctionXYGrid
Generates a flux map in the XY plane from the intersection points.
- Parameters:
bins (int) – The number of bins to use for the histogram.
- Returns:
A FunctionXYGrid object representing the flux map in the XY plane.
- Return type:
- to_flux_mapXZ(bins: int) FunctionXYGrid
Generates a flux map in the XZ plane from the intersection points.
- Parameters:
bins (int) – The number of bins to use for the histogram.
- Returns:
A FunctionXYGrid object representing the flux map in the XZ plane.
- Return type:
- to_flux_mapYZ(bins: int) FunctionXYGrid
Generates a flux map in the YZ plane from the intersection points.
- Parameters:
bins (int) – The number of bins to use for the histogram.
- Returns:
A FunctionXYGrid object representing the flux map in the YZ plane.
- Return type:
- class opencsp.common.lib.geometry.LineXY.LineXY(A: float, B: float, C: float)
Bases:
objectRepresentation of a homogeneous line in 2D space.
The line is represented in the general form ( Ax + By + C = 0 ) and provides various properties and methods to work with lines, including calculating distances, intersections, and fitting lines to sets of points.
- A
Coefficient A of the line equation.
- Type:
float
- B
Coefficient B of the line equation.
- Type:
float
- C
Coefficient C of the line equation, representing the distance from the origin along the normal vector.
- Type:
float
- _original_two_points
The original two points used to create the line, if created with from_two_points.
- __init__(A: float, B: float, C: float)
- Representation of a homogenous line with the following properties:
General form: Ax + By + C = 0
Slope intercept form: y = -A/Bx - C/B
XY vector (A, B) (Line.n_vec) is normal unit vector pointing perpendicular to the line. The AB vector is normalized upon instantiation.
C is the distance along the normal vector from the line to the origin. C can be positive or negative.
- Parameters:
A (float) – Line coefficients.
B (float) – Line coefficients.
C (float) – Line coefficients.
- Return type:
LineXY.
- dist_from(Pxy: Vxy) ndarray
Calculates perpendicular distance magnitude from line to XY points.
- Parameters:
Pxy (Vxy) – Input points.
- Returns:
1d ndarray with length: len(Pxy).
- Return type:
ndarray
- dist_from_signed(Pxy: Vxy) ndarray
Calculates perpendicular distance from line to XY points. Distances are positive if in same direction from line as vector [A, B].
- Parameters:
Pxy (Vxy) – Input points.
- Returns:
1d ndarray with length: len(Pxy).
- Return type:
ndarray
- classmethod fit_from_points(Pxy: Vxy, seed: int = 1, neighbor_dist: float = 1.0)
Fits a LineXY to a set of points using Ransac method.
- flip() LineXY
Flips the orientation of a line. Returns a flipped copy of the LineXY.
- Returns:
Flipped line.
- Return type:
- flip_in_place() None
Flips the orientation of a line. The objects’s coefficients are updated internally.
- classmethod from_location_angle(location: Vxy, angle: float) LineXY
Get a new instance of this class built from the xy location + angle representation of a line.
- Parameters:
location (Vxy) – A point that the line travels through on the cartesion x/y grid.
angle (float) – The angle of the line, in radians, for the standard graphing coordinate system. 0 is on the positive x-axis to the right, and the angle increases counter-clockwise.
- classmethod from_rho_theta(rho: float, theta: float) LineXY
Get a new instance of this class built from the rho + theta representation of a line. This is particularly useful for representation of lines found via the Hough Transform of an image (https://docs.opencv.org/3.4/d9/db0/tutorial_hough_lines.html).
- Parameters:
rho (float) – The right angle distance between the line and the origin (0,0). For images, this will be the top-left corner of the image.
theta (float) – The angle between the right angle distance vector and the X axis. Units are radians on the standard graphing coordinate system (0 is on the positive x-axis to the right, and the angle increases counter-clockwise).
- x_from_y(ys: ndarray | float) ndarray | float
Returns x points that lie on line given corresponding y points.
- Parameters:
ys (ndarray) – Y points.
- Returns:
X points.
- Return type:
ndarray
- y_from_x(xs: ndarray | float) ndarray | float
Returns y points that lie on line given corresponding x points.
- Parameters:
xs (ndarray) – X points.
- Returns:
Y points.
- Return type:
ndarray
- property ABC: ndarray
Returns ABC coefficients in length 3 ndarray.
- Returns:
ABC coefficiens in array.
- Return type:
ndarray
- property angle: float
Get the angle of this vector in radians, as measured by its slope.
- As in all of OpenCSP, the angle coordinate system is defined as:
0 along the positive x axis (pointing to the right)
increasing counter-clockwise
- property slope: float
Get the slope of the line, as rise over run (could be infinity!)
- class opencsp.common.lib.geometry.LoopXY.LoopXY(edges: list[EdgeXY])
Bases:
objectRepresentation of 2D loop. The loop created by the given edges must satisfy the following:
Closed geometry (currently checked)
Must be convex (currently not checked)
Linear boundary types (only linear is supported)
The orientation of the edges must be consistent (all CCW/CW)
- __init__(edges: list[EdgeXY])
Instantiate a loop
- Parameters:
edges (list[EdgesXY, ...]) – Oriented edges of loop.
- aabbox(*args, **kwargs) tuple[float, float, float, float]
Alias for LoopXY.minnimum_bounding_envelope.
- as_mask(vx: ndarray, vy: ndarray) ndarray
Returns 2d mask given sample points on x and y axis.
- Parameters:
xv (np.ndarray) – 1d array, x sample points.
yv (np.ndarray) – 1d array, y sample points.
- Returns:
2d mask with shape (yv.size, xv.size).
- Return type:
np.ndarray
- axis_aligned_bounding_box() tuple[float, float, float, float]
Gives the minnimum bounding envelope for the region. The minnimum bounding envelope is the smallest rectangle that can fit the LoopXY in question where all sides of the rectangle are parrallel to either the X or Y axes.
- Returns:
(left, right, bottom, top) – the x and y values for the bounds
- Return type:
tuple[float, float, float, float]
- draw(ax: Axes | None = None, linecolor: str = 'black') None
Draws lines as arrows and marks starting point.
- Parameters:
ax (Axes, optional) – The axes to draw on. If not given, uses current axes.
linecolor (str, optional) – Color to draw arrows. The default is ‘black’.
- flip()
Flips the orientation of the loop. Returns a copy of the flipped loop.
- flip_in_place()
Flips the orientation of the loop. Flips the internal data of the loop.
- classmethod from_lines(lines: list[LineXY])
Returns LoopXY from list of 2d lines. Lines are intersected with each other in the order given to calculate the loop vertices. The vertices are sorted to be CCW starting from the +x axis.
- classmethod from_rectangle(x: float, y: float, width: float, height: float) LoopXY
Returns rectangular loop
- Parameters:
x/y (float) – Coordinates of lower left (minimum xy values) corner of rectangle
width (float) – Width of rectangle (x direction)
height (float) – Height of rectangle (y direction)
- Return type:
- classmethod from_vertices(vertices: Vxy)
Returns LoopXY defined from 2d points. Points are sorted to be CCW starting from the +x axis. Assumes 2d lines are the curves connecting each vertex.
- is_inside(points: Vxy) ndarray
Calculates which of the given points are within the loop. Points on the edge of the loop are not considered inside.
- Parameters:
points (Vxy) – Given points to compare to loop.
- Returns:
mask – 1D boolean array of same length as input points.
- Return type:
np.ndarray
- is_inside_or_on_border(points: Vxy, thresh: float = 1e-06) ndarray
Calculates which of the given points are within the loop. Points on the edge of the loop are not considered inside.
- Parameters:
points (Vxy) – Given points to compare to loop.
- Returns:
mask – 1D boolean array of same length as input points.
- Return type:
np.ndarray
- property is_positive_orientation: bool
Checks the orientation of the loop.
- class opencsp.common.lib.geometry.Pxy.Pxy(data, dtype=<class 'float'>)
Bases:
VxyA class representing a 2D point in space, inheriting from the Vxy class.
- __init__(data, dtype=<class 'float'>)
Initializes a Pxy object with the given data and data type.
- Parameters:
data (array-like) – The coordinates of the point in 2D space.
dtype (type, optional) – The data type of the point coordinates (default is float).
- as_Vxy()
Converts this Pxy point to a Vxy object.
- Returns:
A Vxy object representing the same point in 2D space.
- Return type:
- class opencsp.common.lib.geometry.Pxyz.Pxyz(data, dtype=<class 'float'>)
Bases:
VxyzA class representing a 3D point in space, inheriting from the Vxyz class.
- __init__(data, dtype=<class 'float'>)
Initializes a Pxyz object with the given data and data type.
- Parameters:
data (array-like) – The coordinates of the point in 3D space.
dtype (type, optional) – The data type of the point coordinates (default is float).
- as_Vxyz()
Converts this Pxyz point to a Vxyz object.
- Returns:
A Vxyz object representing the same point in 3D space.
- Return type:
- class opencsp.common.lib.geometry.RegionXY.RegionXY(loop: LoopXY)
Bases:
objectRepresentation of a 2D region
- __init__(loop: LoopXY)
Instantiates a 2d region with a 2d loop
- Parameters:
loop (LoopXY) – The first loop to define the region.
NOTE (Currently only single-loop regions can be defined.)
- aabbox() tuple[float, float, float, float]
Gives the minnimum bounding envelope for the region. The minnimum bounding envelope is the smallest rectangle that can fit the RegionXY in question where all sides of the rectangle are parrallel to either the X or Y axes.
- Returns:
(left, right, bottom, top) – the x and y values for the bounds
- Return type:
tuple[float, float, float, float]
- add_loop(loop: LoopXY) None
Appends a loop to the current region. Currently not implimented.
- Parameters:
loop (LoopXY) – Loop to append to the region.
- as_mask(vx: ndarray, vy: ndarray)
Returns the mask representation of a region given X and Y sample points.
- Parameters:
vx/vy (np.ndarray) – The X and Y sample points.
- axis_aligned_bounding_box() tuple[float, float, float, float]
Gives the minnimum bounding envelope for the region. The minnimum bounding envelope is the smallest rectangle that can fit the RegionXY in question where all sides of the rectangle are parrallel to either the X or Y axes.
- Returns:
(left, right, bottom, top) – the x and y values for the bounds
- Return type:
tuple[float, float, float, float]
- draw(ax: Axes | None = None)
Draws all loops on given axes.
- Parameters:
ax (plt.Axes) – Axes to draw on. If no Axes given, draws on current axes.
- edge_sample(count: int)
Returns a Vxy of count points per edge per loop defining the region
- filter_points(p: Pxy) Pxy
Returns only the subset of given points that are inside or on the border of the region.
- classmethod from_vertices(vertices: Pxy)
Creates a single loop region defined by the vertices given.
- is_inside(P: Vxy) ndarray
Calculates if given points are inside the region.
- Parameters:
P (Vxy) – Sample points
- Returns:
mask – 1D array of booleans.
- Return type:
np.ndarray
- is_inside_or_on_border(P: Vxy, thresh: float = 1e-06) ndarray
Calculates if given points are inside the region or ono the border.
- Parameters:
P (Vxy) – Sample points
- Returns:
mask – 1D array of booleans.
- Return type:
np.ndarray
- points_sample(resolution: Resolution) Pxy
Returns a Pxy object of points sampled from inside the region.
- Parameters:
resolution (int) – Spacing between points
resolution_type (str, optional) – {‘random’, ‘pixelY’, ‘pixelX’}, by default ‘pixelX’
random_seed (int | None, optional) – _description_, by default None
- Returns:
_description_
- Return type:
- classmethod rectangle(size: float | tuple[float, float])
Create a rectangular region centered at (0,0)
- Parameters:
size (float | Iterable[float]) – If ‘size’ is a scalar the region will be a square with side lengths of ‘size’. If it is an iterable of length 2 the width (x direction) will be length size[0] and the height (y direction) will be of length size[1].
- class opencsp.common.lib.geometry.RegionXY.Resolution(points: Pxy)
Bases:
objectAllows options for defining a set of points needed. To choose a type of Resolution use a class method with keeps the type of unresolved resolution stored until the bouning box containing the resolution is known.
- self.points
The points that the resolution cares about. These are the xy points that will be used in whatever the resolution is for.
- Type:
- self.unresolved
The description of the properties the resolution should have once it is given a bounding box to axt on.
- Type:
tuple[str, …]
- classmethod center() Resolution
Gives the center point of a bounding box. This resolution cannot be ‘resolved’ since there is not a set of points that can represent what it is trying to do.
- change_frame_and_copy(frame_transform: TransformXYZ) Resolution
- is_resolved() bool
- is_unresolved() bool
- classmethod pixelX(points_along_x: int) Resolution
Will have points_along_x points along x and equispaced points along y.
- classmethod random(number_of_points: int, seed: int | None = None) Resolution
There will be number_of_points uniformly randomly in the region. Can choose to add a seed.
- resolve_and_copy(bounding_box: tuple[float, float, float, float] | RegionXY) Resolution
If the Resolution object is “unresolved” this is the function that resolves it to a set of points in xy space (Pxy). If there is no unresolved tag, this function just filters out points that do not fall in bounding box. Produces a new Resolution object.
- resolve_in_place(bounding_box: tuple[float, float, float, float] | RegionXY)
RegionXY If the Resolution object is “unresolved” this is the function that resolves it to a set of points in xy space (Pxy). If there is no unresolved tag, this function just filters out points that do not fall in bounding box. Acts in place.
- classmethod separation(separation: float) Resolution
Separates the points along x and y by the separation.
- class opencsp.common.lib.geometry.TransformXYZ.TransformXYZ(matrix: ndarray)
Bases:
objectRepresentation of a 3D homogeneous spatial transform.
A TransformXYZ object encapsulates a 4x4 homogeneous transformation matrix, which includes both rotation and translation components. This class provides methods for creating transformations, applying them to vectors, and obtaining their inverse.
Properties
- matrixnp.ndarray
The 4x4 matrix representation of the transformation.
- RRotation
The rotation component of the transformation.
- R_matrixnp.ndarray
The 3x3 rotation matrix.
- VVxyz
The translation component of the transformation.
- V_matrixnp.ndarray
The translation vector as a length 3 array.
- __init__(matrix: ndarray)
Initializes a TransformXYZ object with the given transformation matrix.
- Parameters:
matrix (np.ndarray) – A 4x4 homogeneous transformation matrix.
- Raises:
ValueError – If the input matrix does not have shape (4, 4).
- apply(V: Vxyz) Vxyz
Applies 3D spatial transform to input vector by rotating then translating. Returns a rotated copy of the input vector.
- copy() TransformXYZ
Returns a copy of the transform
- classmethod from_R(R: Rotation)
TransformXYZ from a 3D rotation. Assumes zero translation.
- Parameters:
R (Rotation) – 3D rotation.
- Return type:
TransformXYZ.
- classmethod from_R_V(R: Rotation, V: Vxyz)
TransformXYZ from a 3D rotation and a 3D translation.
- Parameters:
R (Rotation) – 3D rotation.
V (Vxyz) – 3D translation.
- Return type:
TransformXYZ.
- classmethod from_V(V: Vxyz)
TransformXYZ from a 3D translation. Assumes zero rotation.
- Parameters:
V (Vxyz) – 3D translation.
- Return type:
TransformXYZ.
- classmethod from_zero_zero()
Returns zero translation and zero rotation TransformXYZ.
- Return type:
TransformXYZ.
- classmethod identity()
Returns the identity tranformation. Alias for TransformXYZ.from_zero_zero().
- Return type:
TransformXYZ.
- inv() TransformXYZ
Returns inverse transformation
- Returns:
Inverse transformation
- Return type:
- property R: Rotation
Rotation component of 3D transform.
- Return type:
Rotation.
- property R_matrix: ndarray
Rotation component of 3D transform.
- Returns:
3x3 rotation matrix.
- Return type:
np.ndarray
- property V: Vxyz
Translation component of 3D transform
- Returns:
3D translation vector.
- Return type:
- property V_matrix: ndarray
Translation component of 3D transform
- Returns:
3D translation vector as a length 3 array.
- Return type:
np.ndarray
- property matrix
4x4 matrix representation of transform.
- Returns:
4x4 transform data.
- Return type:
np.ndarray
- class opencsp.common.lib.geometry.Uxy.Uxy(data, dtype=<class 'float'>)
Bases:
VxyA class representing a 2D unit vector.
This class extends the Vxy class to ensure that the vector is normalized upon initialization, representing a direction in 2D space with a magnitude of 1.
- __init__(data, dtype=<class 'float'>)
Initializes the Uxy instance and normalizes the vector.
- Parameters:
data (array-like) – The initial data for the vector, which should be a 2D vector.
dtype (type, optional) – The data type of the vector elements. Defaults to float.
- Raises:
ValueError – If the provided data does not represent a valid 2D vector.
- class opencsp.common.lib.geometry.Uxyz.Uxyz(data, dtype=<class 'float'>)
Bases:
VxyzA class representing a 3D unit vector.
The Uxyz class extends the Vxyz class to specifically represent unit vectors in three-dimensional space. Upon initialization, the vector is normalized to ensure it has a magnitude of 1.
- _data
The underlying data representing the vector, normalized to unit length.
- Type:
np.ndarray
- __init__(data, dtype=<class 'float'>)
Instantiate class for representing a 3D unit vector.
- Parameters:
data (array-like) – The input data for the vector, which can be a list, tuple, or NumPy array of length 3.
dtype (data type, optional) – The data type of the vector elements. The default is float.
- Returns:
An instance of the Uxyz class representing a unit vector.
- Return type:
- class opencsp.common.lib.geometry.Vxy.Vxy(data_in: ~numpy.ndarray | tuple[float, float] | tuple[list, list] | ~opencsp.common.lib.geometry.Vxy.Vxy, dtype=<class 'float'>)
Bases:
objectA class to represent 2D points or vectors.
This class allows for the creation and manipulation of 2D vectors, including operations such as addition, subtraction, scaling, normalization, rotation, and dot/cross products.
The vectors can be initialized from various data formats, including NumPy arrays, tuples, lists, or other instances of the Vxy class.
- __init__(data_in: ~numpy.ndarray | tuple[float, float] | tuple[list, list] | ~opencsp.common.lib.geometry.Vxy.Vxy, dtype=<class 'float'>)
2D vector class to represent 2D points/vectors.
To represent a single vector:
x = 1 y = 2 vec = Vxy(np.array([[x], [y]]) # same as vec = Vxy([x, y]) print(vec.x) # [1.] print(vec.y) # [2.]
To represent a set of vectors:
vec1 = [1, 2] vec2 = [4, 5] vec3 = [7, 8] zipped = list(zip(vec1, vec2, vec3)) vecs = Vxy(np.array(zipped)) print(vec.x) # [1. 4. 7.] print(vec.y) # [2. 5. 8.] # or this equivalent method xs = [1, 4 ,7] ys = [2, 5, 8] vecs = Vxy((xs, ys))
- Parameters:
data_in (array-like) – The 2d point data: 2xN array, length 2 tuple, length 2 list
dtype (data type, optional) – Data type. The default is float.
- asindex(axis_order='xy') tuple[ndarray[Any, dtype[int64]], ndarray[Any, dtype[int64]]]
Returns the x and y values as integer arrays. This allows for indexing of a numpy array as follows:
arr_val[vxy_val.asindex()]
For example, to get an array of 1s at each of the vxy_val coordinates:
binary_image = np.zeros((np.max(vxy_val.y), np.max(vxy_val.x)), dtype=np.uint8) binary_image[vxy_val.asindex('yx')] = 1
In this type of usage, the ‘x’ values will be used for the first index, and the ‘y’ values will be used for the second index. For example:
arr_val = np.array([ [0, 1, 2], [3, 4, 5], [6, 7, 8] ]) vxy_val = Vxy(([0, 1, 2], [0, 1, 0])) print(arr_val[desired_indexes.asindex()]) # [0, 4, 6]
- astuple() tuple[Number, Number]
Get this instance as a tuple (x, y). Only works for single-value vectors.
Raises:
- RuntimeError:
This vector has more than one value.
- cross(V) ndarray
Calculates cross product. Operands 0 and 1 must have data sizes that can broadcast together.
- Parameters:
V (Vxy) – Input vector.
- Returns:
1D ndarray, cross product.
- Return type:
ndarray
- dot(V) ndarray
Calculated dot product. Size of input data must broadcast with size of data.
- Parameters:
V (Vxy) – Input vector.
- Returns:
Length n array of dot product values.
- Return type:
np.ndarray
- draw(ax=None)
Draws points on axis via plt.scatter.
- Parameters:
ax (matplotlib axis, optional) – Axis to draw on. The default is None.
- magnitude() ndarray[Any, dtype[float64]]
Returns magnitude of each vector.
- Returns:
Length n ndarray of vector magnitudes.
- Return type:
np.ndarray
- normalize_in_place() None
Normalizes vector. Replaces data in Vxy object with normalized data.
- rotate(R: ndarray)
Rotates vector about coordinate system origin. Returns a copy of the rotated vector.
- Parameters:
R (np.ndarray) – 2x2 rotation matrix.
- Returns:
Rotated vector.
- Return type:
- rotate_about(R: ndarray, V_pivot)
Rotates vector about a pivot point. Returns a copy of the rotated vector.
- rotate_about_in_place(R: ndarray, V_pivot) None
Rotates vector about given pivot point. Replaces data in Vxy object with rotated data.
- Parameters:
R (np.ndarray) – 2x2 rotation matrix.
V_pivot (Vxy) – Pivot point to rotate about
- rotate_in_place(R: ndarray) None
Rotates vector about coordinate system origin. Replaces data in Vxy object with rotated data.
- Parameters:
R (np.ndarray) – 2x2 rotation matrix.
- property data
An array with shape (2, N), where N is the number of 2D vectors in this instance.
- property dtype
- property x
The x-coordinates of the vectors.
- property y
The y-coordinates of the vectors.
Three dimensional vector representation
- class opencsp.common.lib.geometry.Vxyz.Vxyz(data_in: ~numpy.ndarray | tuple[float, float, float] | tuple[list, list, list] | ~opencsp.common.lib.geometry.Vxy.Vxy | ~opencsp.common.lib.geometry.Vxyz.Vxyz, dtype=<class 'float'>)
Bases:
object3D vector class to represent 3D points/vectors. Contains N 3D vectors where len == N.
The values for the contained vectors can be retrieved with
data(), or individual vectors can be retrieved with the indexing or x/y/z methods. For example, the following can both be used to get the first contained vector:.. code-block:: python
vec = v3.Vxyz([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) v0 = Vxyz([vec.x()[0], vec.y()[0], vec.z()[0]]) # v0 == Vxyz([0, 3, 6]) v0 = vec[0] # v0 == Vxyz([0, 3, 6])
- __init__(data_in: ~numpy.ndarray | tuple[float, float, float] | tuple[list, list, list] | ~opencsp.common.lib.geometry.Vxy.Vxy | ~opencsp.common.lib.geometry.Vxyz.Vxyz, dtype=<class 'float'>)
To represent a single vector:
x = 1 y = 2 z = 3 vec = Vxyz(np.array([[x], [y], [z]])) # same as vec = Vxyz([x, y, z]) print(vec.x) # [1.] print(vec.y) # [2.] print(vec.z) # [3.]
To represent a set of vectors:
vec1 = [1, 2, 3] vec2 = [4, 5, 6] vec3 = [7, 8, 9] zipped = list(zip(vec1, vec2, vec3)) vecs = Vxyz(np.array(zipped)) print(vec.x) # [1. 4. 7.] print(vec.y) # [2. 5. 8.] print(vec.z) # [3. 6. 9.] # or this equivalent method xs = [1, 4 ,7] ys = [2, 5, 8] zs = [3, 6, 9] vecs = Vxyz((xs, ys, zs))
- Parameters:
data_in (array-like) – The 3d point data: 3xN array, length 3 tuple, length 3 list. If a Vxy, then the data will be padded with 0s for ‘z’.
dtype (data type, optional) – Data type. The default is float.
- align_to(V: Vxyz) Rotation
Calculate shortest rotation that aligns current vector to input vector. Both vectors must have length 1. The returned rotation can be applied to the current vector so that it then aligns with the input vector. For example:
vec = Vxyz([1, 2, 3]) R = vec.align_to(Vxyz([1, 0, 0])) vec_r = vec.rotate(R) vec_r_n = vec_r.normalize() # vec.magnitude() == 3.74165739 # vec_r == [ 3.74165739, -4.44089210e-16, -2.22044605e-16 ] # vec_r_n == [ 1.00000000, -1.18687834e-16, -5.93439169e-17 ]
- Parameters:
V (Vxyz) – 3D vector to align current vector to. Must have length 1.
- Returns:
Rotation object to align current vector to given vector.
- Return type:
Rotation
- concatenate(V: Vxyz) Vxyz
Concatenates Vxyz to the end of current vector. Returns a copy as the new vector.
- cross(V: Vxyz) Vxyz
Calculates cross product. Operands 0 and 1 must have data sizes that can broadcast together.
- Parameters:
V (Vxyz) – Input vector to computer the cross product with. Must broadcast with the size of this instance (must have length 1 or N, where N is the length of this instance).
- Returns:
Cross product copy with shape (P), where O is the length of the input V and P is the greater of N and O.
- Return type:
- dot(V: Vxyz) ndarray
Calculated dot product. Size of input data must broadcast with size of data.
- Parameters:
V (Vxyz) – Input vector to compute the dot product with. Must broadcast with the size of this instance (must have length 1 or N, where N is the length of this instance).
- Returns:
Array of dot product values with shape (N).
- Return type:
np.ndarray
- draw_line(figure: RenderControlFigureRecord | View3d, close: bool | None = None, style: RenderControlPointSeq | None = None, label: str | None = None) None
Calls figure.draw_xyz_list(self.data.T) to draw all xyz points in a single series. Uses the default arguments for
View3d.draw_xyz_list()in place of any None arguments.- Parameters:
figure (rcfr.RenderControlFigureRecord or v3d.View3d) – The figure to draw to.
close (bool, optional) – True to add the first point again at the end of the plot, thereby drawing this set of points as a closed polygon. None or False to not add another point at the end (draw_xyz_list default)
style (rcps.RenderControlPointSeq, optional) – The style to use for the points and lines, or None for
RenderControlPointSequence.default().label (str, optional) – A string used to label this plot in the legend, or None for no label.
- draw_points(figure: RenderControlFigureRecord | View3d, style: RenderControlPointSeq | None = None, labels: list[str] | None = None) None
Calls figure.draw_xyz(p) to draw all xyz points in this instance individually. Uses the default arguments for
View3d.draw_xyz()in place of any None arguments.- Parameters:
figure (rcfr.RenderControlFigureRecord | v3d.View3d) – The figure to draw to.
close (bool, optional) – True to add the first point again at the end of the plot, thereby drawing this set of points as a closed polygon. None or False to not add another point at the end (draw_xyz_list default).
style (rcps.RenderControlPointSeq, optional) – The style to use for the points and lines, or None for
RenderControlPointSequence.default().label (str, optional) – A string used to label this plot in the legend, or None for no label.
- classmethod from_lifted_points(v: Vxy, func: Callable) Vxyz
Returns Vxyz from a Vxy and a function of form: z = func(x, y).
- classmethod from_list(vals: list[Vxyz])
Builds a single Vxyz instance from a list of Vxyz instances.
- hasnan()
Returns True if there is a single NaN in the current vector.
Note: this method exists because of the unintuitive behavior of isinstance in Python:
isinstance(np.nan, numbers.Number) # True
- magnitude() ndarray[Any, dtype[float64]]
Returns magnitude of each vector as a new array.
- Returns:
Vector magnitudes copy. Shape is (n).
- Return type:
np.ndarray
- normalize() Vxyz
Creates a copy of this instance and normalizes it.
- Returns:
Normalized vector copy with the same shape.
- Return type:
- normalize_in_place() None
Normalizes vector. Replaces data in Vxyz object with normalized data.
- classmethod origin()
- projXY() Vxy
Returns the x and y components of self as a Vxy.
The components are not a view via indexing but rather a copy.
- Returns:
Output XY points as a new vector. Shape is (2,N).
- Return type:
- rotate(R: Rotation) Vxyz
Returns a copy of the rotated vector rotated about the coordinate system origin. The rotation is applied to each of the contained 3d coordinates.
- Parameters:
R (Rotation) – Rotation object to apply to vector.
- Returns:
Rotated vector copy.
- Return type:
- rotate_about(R: Rotation, V_pivot: Vxyz) Vxyz
Returns a copy of the rotated vector rotated about the given pivot point. The rotation is applied to each of the contained 3d coordinates.
- rotate_about_in_place(R: Rotation, V_pivot: Vxyz) None
Rotates about the given pivot point. Replaces data in Vxyz object with rotated data. The rotation is applied to each of the contained 3d coordinates.
- Parameters:
R (Rotation) – Rotation object to apply to vector.
V_pivot (Vxyz) – Pivot point to rotate about. Must broadcast with the size of this instance (must have length 1 or N, where N is the length of this instance).
- Return type:
None
- rotate_in_place(R: Rotation) None
Rotates vector about the coordinate system origin. Replaces data in Vxyz object with rotated data. The rotation is applied to each of the contained 3d coordinates.
- Parameters:
R (Rotation) – Rotation object to apply to vector.
- Return type:
None
- property data: ndarray
An array with shape (3, N), where N is the number of 3D vectors in this instance.
- property dtype: dtype
- property x: ndarray
The x-coordinates of the vectors.
- property y: ndarray
The y-coordinates of the vectors.
- property z: ndarray
The z-coordinates of the vectors.
Angle Utility Classes
Angle Management
- opencsp.common.lib.geometry.angle.angle2_minus_angle_1(angle_1, angle_2)
Calculates the signed small angle between two input angles.
This function corrects for cases where the angles wrap around 2π.
- Parameters:
angle_1 (float) – The first angle in radians.
angle_2 (float) – The second angle in radians.
- Returns:
The signed angle difference between angle_2 and angle_1, adjusted for wrapping.
- Return type:
float
Examples
angle_1 = 5 degrees, angle_2 = 10 degrees ==> 5 degrees
angle_1 = 355 degrees, angle_2 = 10 degrees ==> 15 degrees
angle_1 = -5 degrees, angle_2 = -10 degrees ==> -5 degrees
angle_1 = 5 degrees, angle_2 = -10 degrees ==> -15 degrees
- opencsp.common.lib.geometry.angle.coord2deg(xy_or_xyz_or_xy_seq_or_xyz_seq, idx)
Converts the specified coordinate from radians to degrees for a single point or a sequence of points.
- Parameters:
xy_or_xyz_or_xy_seq_or_xyz_seq (np.ndarray or Iterable[np.ndarray]) – A single point (2D or 3D) or a sequence of points to convert.
idx (int) – The index of the coordinate to convert (0 for x, 1 for y, 2 for z).
- Returns:
A list of points with the specified coordinate converted to degrees. Returns an empty list if the input is empty.
- Return type:
list[np.ndarray]
- opencsp.common.lib.geometry.angle.coord2deg_aux(xy_or_xyz, idx)
Converts the specified coordinate (x, y, or z) from radians to degrees.
- Parameters:
xy_or_xyz (np.ndarray) – A 1D array representing a point in 2D or 3D space.
idx (int) – The index of the coordinate to convert (0 for x, 1 for y, 2 for z).
- Returns:
A copy of the input array with the specified coordinate converted to degrees.
- Return type:
np.ndarray
- opencsp.common.lib.geometry.angle.normalize(angle: float) float
- opencsp.common.lib.geometry.angle.normalize(angles: ndarray[Any, dtype[float64]] | Iterable) ndarray[Any, dtype[float64]]
Adjusts the given angle or angles to be in the range [0, 2π].
Note that because this function operates on floating point math, the result may not be exact (e.g., a value of -1e-16 could return 2π).
- Parameters:
angle_or_angles (float or
npt.NDArray[np.float_]()or Iterable) – A single angle or an array/iterable of angles to normalize.- Returns:
The normalized angle or array of normalized angles.
- Return type:
float or py:meth:npt.NDArray[np.float_]
- opencsp.common.lib.geometry.angle.p2deg(pq_or_pq_seq)
Converts the p-coordinates of a point or sequence of points from radians to degrees.
- Parameters:
pq_or_pq_seq (np.ndarray or Iterable[np.ndarray]) – A single point (2D) or a sequence of points.
- Returns:
A list of points with the p-coordinates converted to degrees.
- Return type:
list[np.ndarray]
- opencsp.common.lib.geometry.angle.q2deg(pq_or_pq_seq)
Converts the q-coordinates of a point or sequence of points from radians to degrees.
- Parameters:
pq_or_pq_seq (np.ndarray or Iterable[np.ndarray]) – A single point (2D) or a sequence of points.
- Returns:
A list of points with the q-coordinates converted to degrees.
- Return type:
list[np.ndarray]
- opencsp.common.lib.geometry.angle.x2deg(xy_or_xyz_or_xy_seq_or_xyz_seq)
Converts the x-coordinates of a point or sequence of points from radians to degrees.
- Parameters:
xy_or_xyz_or_xy_seq_or_xyz_seq (np.ndarray or Iterable[np.ndarray]) – A single point (2D or 3D) or a sequence of points.
- Returns:
A list of points with the x-coordinates converted to degrees.
- Return type:
list[np.ndarray]
- opencsp.common.lib.geometry.angle.y2deg(xy_or_xyz_or_xy_seq_or_xyz_seq)
Converts the y-coordinates of a point or sequence of points from radians to degrees.
- Parameters:
xy_or_xyz_or_xy_seq_or_xyz_seq (np.ndarray or Iterable[np.ndarray]) – A single point (2D or 3D) or a sequence of points.
- Returns:
A list of points with the y-coordinates converted to degrees.
- Return type:
list[np.ndarray]
- opencsp.common.lib.geometry.angle.z2deg(xyz_or_xyz_seq)
Converts the z-coordinates of a point or sequence of points from radians to degrees.
- Parameters:
xyz_or_xyz_seq (np.ndarray or Iterable[np.ndarray]) – A single point (3D) or a sequence of points.
- Returns:
A list of points with the z-coordinates converted to degrees.
- Return type:
list[np.ndarray]