Surface

Contents

Surface#

The Surface class is used for handling surface-related data and operations in the cratermaker project. It provides methods for setting elevation data, calculating distances and bearings, and other surface-related computations. The Surface class extends UxDataset for the cratermaker project.

Available Implementations#

Class

Argument name

Example Usage

IcosphereSurface

“icosphere”

surface = Surface.maker(“icosphere”,gridlevel=7)

ArbitraryResolutionSurface

“arbitrary_resolution”

surface = Surface.maker(“arbitrary_resolution”,pix=100)

HiResLocalSurface

“hireslocal”

surface = Surface.maker(“hireslocal”,pix=50,local_radius=1e3,local_location=(0,9))

DataSurface

“datasurface”

surface = Surface.maker(“datasurface”, local_location=(321.9913, 8.121), local_radius=50.0e3, pix=200.0)

class cratermaker.components.surface.Surface(target=None, simdir=None, **kwargs)[source]#

Bases: ComponentBase

classmethod maker(surface=None, target=None, reset=True, regrid=False, simdir=None, **kwargs)[source]#

Initialize a Surface model with the given name or instance.

Parameters:
  • surface (str or Surface, optional) – The name of the type of grid used for the surface. Default is “icosphere”.

  • target (Target, optional) – The target body or name of a known target body for the impact simulation.

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is True.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • simdir (str | Path) – The main project simulation directory. Default is the current working directory if None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

Surface – An initialized Surface object.

Available models:

  • arbitrary_resolution

  • hireslocal

  • datasurface

  • icosphere

saved_output_files(**kwargs)[source]#

Check if the component has any output files in its output directory.

Returns:

list[Path] – A list of Path objects representing the files that would be removed during a reset operation. Returns an empty list if no files found

reset(**kwargs)[source]#

Reset the surface to its initial state.

Parameters:

**kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

extract_region(location, region_radius, at_least_one_face=False, **kwargs)[source]#

Extract a regional grid based on a given location and radius.

Parameters:
  • location (tuple[float, float]) – tuple containing the longitude and latitude of the location in degrees.

  • region_radius (float) – The radius of the region to extract in meters.

  • at_least_one_face (bool, optional) – If True, ensure that at least one face is returned, even if the region radius is very small. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

LocalSurface – A LocalSurface object containing a view of the regional grid.

add_data(name, data, long_name=None, units=None, isfacedata=True, overwrite=False, fill_value=0.0, dtype=<class 'numpy.float64'>, positive_only=False, **kwargs)[source]#

Adds new data to the surface.

If the data variable already exists, it will be overwritten if overwrite is set to True.

Parameters:
  • name (str) – Name of the data variable. This will also be used as the data file name.

  • data (scalar or array-like) – Data file to be saved. If data is a scalar, then the data file will be filled with that value. If data is an array, then the data file will be filled with the array values. The data array must have the same size as the number of faces or nodes in the grid.

  • long_name (str, optional) – Long name of the data variable that will be saved as an attribute if this is new data. If the data already exists on the surface, this will be ignored.

  • units (str, optional) – Units of the data variable that will be saved as an attribute if this is new data. If the data already exists on the surface, this will be ignored.

  • isfacedata (bool, optional, default True) – Flag to indicate whether the data is face data or node data. This is only needed if data is a scalar, otherwise it is ignored

  • overwrite (bool, optional, default False) – By default, new data is added to the old data. This flag indicates that the data should be overwritten, replacing any old data with the new data.

  • fill_value (float, optional) – The fill value to use for new data variables. Default is 0.0.

  • dtype (data-type, optional) – The data type of the data variable. Default is np.float64.

  • positive_only (bool, optional) – If True, only allow positive values on the data (data will be clipped at 0.0). Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

None

update_elevation(new_elevation, overwrite=False, **kwargs)[source]#

Update the elevation data for the target’s surface mesh. This method will determine whether to update the node or face data (or both) depending on the size of the input data. If a scalar is passed, both node and face elevation will be updated to that value. By default, the elevation data will be added to the existing data. If overwrite is set to True, the existing data will be replaced with the new data.

Parameters:
  • new_elevation (ArrayLike | FloatLike) – Elevation to be added (or replaced, if overwrite is True). This can be a scalar, an array with the same size as the number of faces, an array with the same size as the number of nodes, or an array with the same size as the number of faces + nodes.

  • overwrite (bool, optional) – If True, the existing data will be replaced with the new data. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Notes

When passing combined data, the first part of the array will be used for face elevation and the second part for node elevation.

add_tag(name, tag=None, long_name=None, **kwargs)[source]#

Adds an integer tag to the surface.

Used primarily for tracking crater ids.

Parameters:
  • name (str) – The name of the tag variable to perform the add operation on.

  • tag (int | None) – The integer to value of the tag. If None is provided, the tag layers will be reset to zero

  • long_name (str | None) – The long name of the tag variable. This is only used if the tag variable doesn’t exist in the surface dataset. If None, no long name will be added.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

remove_tag(name, tag, **kwargs)[source]#

Removes an integer tag from the surface.

Parameters:
  • name (str) – The name of the tag variable to perform the remove operation on.

  • tag (int) – The integer tag to be removed.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

apply_diffusion(kdiff)[source]#

Apply diffusion to the surface.

Parameters:

kdiff (float or array-like) – The degradation state of the surface, which is the product of diffusivity and time. It can be a scalar or an array of the same size as the number of faces in the grid. If it is a scalar, the same value is applied to all faces. If it is an array, it must have the same size as the number of faces in the grid. The value of kdiff must be greater than 0.0.

slope_collapse(critical_slope_angle=35.0)[source]#

Collapse all slopes larger than the critical slope angle.

Parameters:

critical_slope_angle (float) – The critical slope angle (angle of repose) in degrees.

compute_slope()[source]#

Compute the slope of the surface.

Returns:

NDArray[np.float64] – The slope of all faces in degrees.

apply_noise(model='turbulence', noise_width=1000000.0, noise_height=1000.0, **kwargs)[source]#

Apply noise to the surface.

Parameters:
  • model (str) – The noise model to use. Options are “turbulence”

  • noise_width (float) – The width of the noise in meters.

  • noise_height (float) – The height of the noise in meters.

  • kwargs (Any) – Additional arguments to pass to the noise model.

calculate_face_and_node_distances(location, validate=True)[source]#

Computes the distances from a given location to all faces and nodes.

Parameters:
  • location (tuple[float, float]) – tuple containing the longitude and latitude of the location in degrees.

  • validate (bool, optional) – If the location should be validated and normalized. Only use if the validation is causing a performance bottleneck.

Returns:

  • NDArray – Array of distances for each face in meters.

  • NDArray – Array of distances for each node in meters.

calculate_face_and_node_bearings(location)[source]#

Computes the initial bearing (relative to North) from a given location to all faces and nodes.

Parameters:

location (tuple[float, float]) – tuple containing the longitude and latitude of the location in degrees.

Returns:

  • NDArray – Array of initial bearings for each face in degrees.

  • NDArray – Array of initial bearings for each node in degrees.

Notes

This is intended to be used as a helper to calculate_face_and_node_bearings.

find_nearest_node(location)[source]#

Find the index of the nearest node to a given point.

This method calculates the Haversine distance from the given point to each node in the grid, and returns the index of the node with the minimum distance.

Parameters:

location (tuple) – A tuple containing two elements: (longitude, latitude) in degrees.

Returns:

int – The index of the nearest node in the grid to the given point.

Notes

The method uses the ball tree query method that is included in the UxArray.Grid class.

find_nearest_face(location)[source]#

Find the index of the nearest face to a given point.

This method calculates the Haversine distance from the given point to each face in the grid, and returns the index of the face with the minimum distance.

Parameters:

location (tuple) – A tuple containing two elements: (longitude, latitude) in degrees.

Returns:

int – The index of the nearest face in the grid to the given point.

Notes

The method uses the ball tree query method that is included in the UxArray.Grid class. It is only approximate, as it looks for whichever face center is closest to the location. This means that it can return a neighboring face, rather than the face that contains the point.

interpolate_node_elevation_from_faces()[source]#

Update node elevations by area-weighted averaging of adjacent face elevations.

For each node, the elevation is computed as the area-weighted average of the elevations of the surrounding faces.

Returns:

None

get_random_location_on_face(face_index, **kwargs)[source]#

Generate a random coordinate within a given face of a the mesh.

Parameters:
  • grid (uxarray.Grid) – The grid object containing the mesh information.

  • face_index (int | NDArray[np.int64]) – The index or array of indices of the face within the grid to obtain the random sample.

  • size (int or tuple of ints, optional) – The number of samples to generate. If size is None (the default), a single tuple is returned. If size is greater than 1, then an array of tuples is returned. The default is 1.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

(lon,lat) or ndarray[(lon,lat)] of given size – A pair or array of pairs of longitude and latitude values in degrees.

Notes

This method is a wrapper for cratermaker.utils.montecarlo_utils.get_random_location_on_face().

elevation_to_cartesian(element='face')[source]#

Convert either the face or node elevations to Cartesian coordinates.

Parameters:

element (str, optional) – The type of element to convert. Can be “face” or “node”. Default is “face”.

Returns:

NDArray[np.float64, 3] – The Cartesian coordinates of the face elevations.

save(interval=0, time_variables=None, filename=None, **kwargs)[source]#

Save the surface data to the specified directory.

Each data variable is saved to a separate NetCDF file. If ‘time_variables’ is specified, then a one or more variables will be added to the dataset along the time dimension.

Parameters:
  • interval (int, optional) – Interval number to append to the data file name. Default is 0.

  • time_variables (dict, optional) – Dictionary containing one or more variable name and value pairs. These will be added to the dataset along the time dimension. Default is None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

export(driver='GPKG', interval=None, ask_overwrite=None, **kwargs)[source]#

Export the surface data to the specified format.

Parameters:
  • driver (str, optional) – The driver to use export the data to. Supported formats are ‘VTK’ or a driver supported by GeoPandas (‘GPKG’, ‘ESRI Shapefile’, etc.), and ‘GeoTIFF’.

  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • ask_overwrite (bool, optional) – If True, the user will be prompted to confirm before overwriting any existing files. If False, existing files will be overwritten without confirmation. If None, the default behavior of the class will be used. This will only persist for the duration of the export, and will be reset to its original value afterwards.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_vector_file(driver='GPKG', interval=None, **kwargs)[source]#

Export the face-associated data from the surface view data to a vector file using GeoPandas.

See geopandas.GeoDataFrame.to_file for more detailed information on the available parameters.

Parameters:
  • driver (str, optional) – The file format driver to use for exporting. Default is ‘GPKG’.

  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_raster(variable_name='face_elevation', **kwargs)[source]#

Rasterize a face-based variable into a 2D raster using rasterio.

Parameters:
  • variable_name (str, optional) – The name of the variable to rasterize. Default is “face_elevation”.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

  • raster (NDArray[np.float32]) – The rasterized variable as a 2D numpy array.

  • extent (tuple[float, float, float, float]) – The extent of the raster in the format (xmin, xmax, ymin, ymax).

  • transform (Affine) – The affine transform for the raster.

  • crs (CRS) – The coordinate reference system of the raster.

get_raster_dims()[source]#

Get the dimensions of the raster based on the target radius and pixel size.

Returns:

tuple[int, int] – The width and height of the raster in pixels.

to_geotiff_file(interval=None, variable_name='face_elevation', **kwargs)[source]#

Rasterize a face-based elevation variable into a GeoTIFF using rasterio.

Parameters:
  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • variable_name (str, optional) – The name of the variable to rasterize. Default is “face_elevation”.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_vtk_mesh(uxds=None, interval=None, **kwargs)[source]#

Exports the surface to a VTK PolyData object.

Parameters:
  • uxds (UxDataset, optional) – The dataset to export. If None, the method will use currently loaded data in the surface. Default is None.

  • interval (int, optional) – The interval number to export. If provided, the method will either extract the interval number from uxds (if it has intervals saved), or, if no uxds is passed, load a saved interval from file.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

vtkUnstructuredGrid – The VTK PolyData object representing the regional mesh.

to_vtk_file(interval=None, **kwargs)[source]#

Export the surface mesh to a VTK file and store it in the default export directory.

Parameters:
  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

plot(plot_style='map', variable_name=None, interval=None, cmap=None, label=None, scalebar=None, colorbar=True, show=True, save=False, ax=None, close_when_done=None, minimum_plot_width=800.0, **kwargs)[source]#

Plot an image of the surface.

Parameters:
  • plot_style (str, optional) – The style of the plot. Options are “map” and “hillshade”. In “map” mode, the variable is displayed as a colored map. In “hillshade” mode, a hillshade image is generated using “face_elevation” data. If a different variable is passed to variable, then the hillshade will be overlayed with that variable’s data. Default is “map”.

  • variable_name (str | None, optional) – The variable to plot. If None is provided then “face_elevation” is used in “map” mode.

  • interval (int | None, optional) – The interval number of the surface to plot. If None, the currently loaded surface data will be used.

  • cmap (str, optional) – The colormap to use for the plot. If None, a default colormap will be used (“cividis” by default and “grey” when plot_style==”hillshade” and variable==”face_elevation”).

  • label (str | None, optional) – A label for the plot. If None, no label will be added.

  • scalebar (bool, optional) – If True, a scalebar will be added to the plot. Default is False for global surfaces.

  • colorbar (bool, optional) – If True, a colorbar will be added to the plot when using “map” plot_style or “hillshade” with a variable overlay. Default is True.

  • show (bool, optional) – If True, the plot will be displayed. Default for local surfaces is True.

  • save (bool, optional) – If True, the plot will be saved to the default plot directory. Default is False.

  • ax (matplotlib.axes.Axes, optional) – An existing Axes object to plot on. If None, a new figure and axes will be created.

  • close_when_done (bool, optional) – If True, the figure will be closed after plotting. Default is True when save is True and show is False, and False otherwise.

  • minimum_plot_width (float, optional) – Because the width of the plot is determined by the number of faces, small regions will generate small plots with labels that are hard to read. This parameter sets a lower limit to the width of the image that is generated by the plot. By default it is 800. Set to None to turn it off.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

matplotlib.axes.Axes – A Matplotlib Axes object containing the plot.

pyvista_plotter(variable_name=None, variable=None, interval=None, theme=None, transparent_background=None, plotter=None, enable_interactive=True, **kwargs)[source]#

Show the surface region using an interactive 3D plot with PyVista.

Parameters:
  • variable_name (str, optional) – The name of the variable to plot. If the name of the variable is not already stored on the surface mesh, then the variable argument must also be passed. Default is None, which will plot a greyscale image of the surface.

  • variable ((n_face) array, optional) – An array face values that will be used to color the surface mesh. This is required if variable_name is not stored on the mesh.

  • interval (int | None, optional) – The interval number of the surface to show. If None, the currently loaded surface data will be displayed. Default is None.

  • theme (str, optional) – The PyVista theme to use for the plot. If None, the default PyVista theme will be used.

  • transparent_background (bool, optional) – If True, the background of the plot will be transparent. Default is False.

  • plotter (pv.Plotter, optional) – An existing PyVista Plotter object to use for the plot. If None, a new Plotter object will be created. Default is None.

  • enable_interactive (bool, optional) – If True, the key events for the plotter will be updated to include custom events for navigating between intervals. Default is True.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

pyvista.Plotter – The PyVista Plotter object for further customization.

compute_distances(locations, reference_location)[source]#

Calculate the great circle distance between one point and one or more other points in meters.

Parameters:
  • locations (FloatLike or ArrayLike) – Array of (lon, lat) locations of the second point or array of points in degrees.

  • reference_location (PairOfFloats) – (lon, lat) location of the reference point in degrees.

Returns:

NDArray – Great circle distance between the two points in meters.

Notes

This is a wrapper for a compiled Rust function and is intended to be used as a helper to calculate_face_and_node_distances.

compute_bearings(locations, reference_location)[source]#

Calculate the initial bearing relative to North from one point to one or more other points in degrees.

Parameters:
  • locations (ArrayLike) – Longitude and latitude of the second point or array of points in degrees.

  • reference_location (PairOfFloats) – Longitude and latitude of the first point in degrees.

Returns:

NDArray – Initial bearing from the first point to the second point or points in degrees.

compute_location_from_distance_bearing(distance, bearing, reference_location)[source]#

Calculate the longitude and latitude of one or more points given a reference point, initial bearings, and distances.

Parameters:
  • bearings (FloatLike or ArrayLike) – Initial bearing from the reference point to the target point or points in degrees.

  • distances (FloatLike or ArrayLike) – Great circle distance from the reference point to the target point or points in meters.

  • reference_location (PairOfFloats) – Longitude and latitude of the reference point in degrees.

Returns:

NDArray – Longitude and latitude of the target point or points in degrees.

read_saved_output(interval=None, reset=False, **kwargs)[source]#

Load the grid and data files into a UxDataset object.

Parameters:
  • interval (int, optional) – Interval number to read from the data files. Default is None (all saved intervals)

  • reset (bool, optional) – Flag to indicate whether to reset the surface. If True it reads in the grid but creates an empty dataset. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

UxDataset – An initialized UxDataset object containing the grid and data.

get_location_extents(location, radius)[source]#

Computes the longitude and latitude extents of a given region.

Parameters:
  • location (PairOfFloats) – The center of the region.

  • radius (FloatLike) – The radius of the region.

Returns:

  • lon_min (float) – Minimum longitude in degrees.

  • lon_max (float) – Maximum longitude in degrees.

  • lat_min (float) – Minimum latitude in degrees.

  • lat_max (float) – Maximum latitude in degrees.

property uxds#

The data associated with the surface as an instance of UxDataset.

property uxgrid#

The grid object as an instance of a UxArray Grid.

property gridtype#

The name of the grid type.

property grid_file#

Path to the grid file.

property target#

The Target object associated with this Surface object.

property pix#

The effective pixel size of the mesh in meters.

property pix_mean#

The mean pixel size of the mesh in meters.

property pix_std#

The standard deviation of the pixel size of the mesh in meters.

property pix_min#

The minimum pixel size of the mesh in meters.

property pix_max#

The maximum pixel size of the mesh in meters.

property radius#

Radius of the target body in meters.

property area#

Total surface area of the target body in m².

property face_area#

An array of areas of each individual face in m².

property face_size#

The effective size of each face in meters, which s simply the square root of the face area, but is useful for certain comparisons and is equivalent to the pix variable from CTEM.

property smallest_length#

The smallest length of the mesh in meters.

property face_lat#

Latitude of the center of each face in degrees.

property face_lon#

Longitude of the center of each face in degrees.

property face_x#

Cartesian x location of the center of each face in meters.

property face_y#

Cartesian y location of the center of each face in meters.

property face_z#

Cartesian z location of the center of each face in meters.

property node_lat#

Latitude of each node in degrees.

property node_lon#

Longitude of each node in degrees.

property node_x#

Cartesian x location of each node in meters.

property node_y#

Cartesian y location of each node in meters.

property node_z#

Cartesian z location of each node in meters.

property face_indices#

The indices of the faces of the surface.

property node_indices#

The indices of the nodes of the surface.

property edge_indices#

The indices of the edges of the surface.

property face_bin_indices#

Faces binned based on their area.

All faces within a factor of 2 in area are in the same bin. This property returns a list of face indices lists for each bin. The keys are the bin indices, and the values are lists of face indices of faces within that bin.

This is used when generating craters on surfaces with varying face sizes, so that the smallest crater is sized for the smallest face of a particular bin, rather than for the entire surface.

property face_bin_area#

The total area of all faces in each bin in m².

property face_bin_argmin#

The index of the smallest face in each bin.

property face_bin_argmax#

The index of the largest face in each bin.

property face_bin_min_areas#

The area of the smallest face in each bin in m².

property face_bin_max_areas#

The area of the largest face in each bin in m².

property face_bin_min_sizes#

The effective size of the smallest face in each bin in meters.

property face_bin_max_sizes#

The effective size of the largest face in each bin in meters.

property n_face#

Total number of faces.

property n_node#

Total number of nodes.

property n_edge#

Total number of edges.

property n_nodes_per_face#

The number of nodes that make up each face.

Dimensions: (n_node, )

property n_max_face_faces#

The maximum number of faces that surround a face.

property edge_face_distance#

Distances between the centers of the faces that saddle each edge in meters.

property edge_length#

Lengths of each edge in meters.

Notes

This is computed as the distance between the nodes that define the edge

property face_node_connectivity#

Indices of the nodes that make up each face.

Dimensions: (n_face, n_max_face_nodes)

Nodes are in counter-clockwise order.

property face_face_connectivity#

Indices of the faces that surround each face.

Dimensions: (n_face, n_max_face_faces)

property face_edge_connectivity#

Indices of the edges that surround each face.

Dimensions (n_face, n_max_face_edges)

property node_face_connectivity#

Indices of the faces that surround each node.

Dimensions: (n_node, n_max_node_faces)

property edge_face_connectivity#

Indices of the faces that saddle each edge.

Dimensions (n_edge, 2)

property edge_node_connectivity#

Indices of the nodes that define each edge.

Dimensions (n_edge, 2)

property face_tree#

The BallTree for the face centers, which can be used for efficient spatial queries.

property node_tree#

The BallTree for the nodes, which can be used for efficient spatial queries.

property edge_tree#

The BallTree for the edge centers, which can be used for efficient spatial queries.

static get_crs(radius, name, location=None)[source]#

Returns either a CRS for a global sphere or a local azimuthal equidistant projection centered at the given location if one is provided.

Parameters:
  • radius (float) – The radius of the sphere in meters.

  • name (str) – The name of the target body.

  • location (tuple[float, float] | None, optional) – The location of the center of the LAEA projection in degrees. If None, a global CRS is returned. Default is None.

property crs#

Return a geographic CRS (lon/lat in degrees) on a sphere using the target radius from the surface. Axis order is Lon/East, Lat/North.

property is_new#

Whether this surface is newly created or has been loaded from disk and not reset.

data_composer()[source]#

Creates a DataComposer tied to this Surface. This should usually be called in a with statement.

Returns:

DataComposer

property face_variables#

Returns a list of the data variables currently being stored on the faces.

property node_variables#

Returns a list of the data variables currently being stored on the nodes.

class cratermaker.components.surface.LocalSurface(surface, face_indices, node_indices=None, edge_indices=None, location=None, region_radius=None, **kwargs)[source]#

Bases: CratermakerBase

Generates a regional view of a subset of the surface mesh without making copies of any of the data.

Parameters:
  • surface (Surface) – The surface object that contains the mesh data.

  • face_indices (NDArray | slice) – The indices of the faces to include in the view.

  • node_indices (NDArray | slice | None, optional) – The indices of the nodes to include in the view. If None, all nodes connected to the faces will be extracted when required

  • edge_indices (NDArray | slice | None, optional) – The indices of the edges to include in the view. If None, all edges connected to the faces will be extracted when required.

  • location (tuple[float, float] | None, optional) – The location of the center of the view in degrees. This is intended to be passed via the extract_region method of Surface.

  • region_radius (FloatLike | None, optional) – The radius of the region to include in the view in meters. This is intended to be passed via the extract_region method of Surface.

  • reset (bool, optional) – Flag to indicate whether to remove any existing data files in the output directory. Default is True.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

add_data(name, data, long_name=None, units=None, isfacedata=True, overwrite=False, fill_value=0.0, dtype=<class 'numpy.float64'>, positive_only=False, **kwargs)[source]#

Adds new data to the surface.

Parameters:
  • name (str) – Name of the data variable. This will also be used as the data file name.

  • data (scalar or array-like) – Data file to be saved. If data is a scalar, then the data file will be filled with that value. If data is an array, then the data file will be filled with the array values. The data array must have the same size as the number of faces or nodes in the grid.

  • long_name (str, optional) – Long name of the data variable that will be saved as an attribute if this is new data. If the data already exists on the surface, this will be ignored.

  • units (str, optional) – Units of the data variable that will be saved as an attribute if this is new data. If the data already exists on the surface, this will be ignored.

  • isfacedata (bool, optional, default True) – Flag to indicate whether the data is face data or node data. This is only needed if data is a scalar, otherwise it is ignored

  • overwrite (bool, optional, default False) – By default, new data is added to the old data. This flag indicates that the data should be overwritten, replacing any old data with the new data.

  • fill_value (float, optional) – The fill value to use for new data variables. Default is 0.0.

  • dtype (data-type, optional) – The data type of the data variable. Default is np.float64.

  • positive_only (bool, optional) – If True, only allow positive values on the data (data will be clipped at 0.0). Default is False.

  • **kwargs – Additional keyword arguments that are either ignored or passed to internal functions as needed.

update_elevation(new_elevation, overwrite=False, **kwargs)[source]#

Update the elevation data for the target’s surface mesh. This method will determine whether to update the node or face data (or both) depending on the size of the input data. If a scalar is passed, both node and face elevation will be updated to that value. By default, the elevation data will be added to the existing data. If overwrite is set to True, the existing data will be replaced with the new data.

Parameters:
  • new_elevation (ArrayLike | FloatLike) – Elevation to be added (or replaced, if overwrite is True). This can be a scalar, an array with the same size as the number of faces, an array with the same size as the number of nodes, or an array with the same size as the number of faces + nodes.

  • overwrite (bool, optional) – If True, the existing data will be replaced with the new data. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Notes

When passing combined data, the first part of the array will be used for face elevation and the second part for node elevation.

add_tag(name, tag=None, long_name=None, **kwargs)[source]#

Adds an integer tag to the surface.

Used primarily for tracking crater ids.

Parameters:
  • name (str) – The name of the tag to be added.

  • tag (int | None) – The integer to apply the tag. If None is provided, the tag layers will be reset to zero

  • long_name (str | None) – The long name of the tag to be added. If None, no long name will be added.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

remove_tag(name, tag)[source]#

Removes an integer tag from the local surface.

Parameters:

tag (int) – The integer tag to be removed.

sort_tags(name)[source]#

Sort the tag layers in descending order based on the tag values. This is used to ensure that the most recently added tags are in the first available layer, which is important for the add_tag method to function properly.

Parameters:

name (str) – The name of the tag to be sorted.

apply_diffusion(kdiff)[source]#

Apply diffusion to the surface.

Parameters:

kdiff (float or array-like) – The degradation state of the surface, which is the product of diffusivity and time. It can be a scalar or an array of the same size as the number of faces in the grid. If it is a scalar, the same value is applied to all faces. If it is an array, it must have the same size as the number of faces in the grid. The value of kdiff must be greater than 0.0.

slope_collapse(critical_slope_angle=35.0)[source]#

Collapse all slopes larger than the critical slope angle.

Parameters:

critical_slope_angle (float) – The critical slope angle (angle of repose) in degrees.

compute_slope()[source]#

Compute the slope of the surface.

Returns:

NDArray[np.float64] – The slope of all faces in degrees.

apply_noise(model='turbulence', noise_width=1000000.0, noise_height=1000.0, **kwargs)[source]#

Apply noise to the node elevations of the surface view.

Parameters:
  • noise_width (float) – The spatial wavelength of the noise.

  • noise_height (float) – The amplitude of the noise.

calculate_face_and_node_distances(location=None, validate=True)[source]#

Computes the distances between nodes and faces and a given location.

Parameters:
  • location (tuple[float, float], option) – tuple containing the longitude and latitude of the location in degrees. If None, the location of the view center is used if it is set.

  • validate (bool, optional) – If the location should be validated and normalized. Only use if the validation is causing a performance bottleneck.

Returns:

  • NDArray – Array of face distances in meters.

  • NDArray – Array of node distances in meters.

calculate_face_and_node_bearings(location=None)[source]#

Computes the initial bearing between nodes and faces and a given location.

Parameters:

location (tuple[float, float]) – tuple containing the longitude and latitude of the location in degrees.

Returns:

  • NDArray – Array of initial bearings for each face in degrees.

  • NDArray – Array of initial bearings for each node in degrees.

interpolate_node_elevation_from_faces()[source]#

Update node elevations by area-weighted averaging of adjacent face elevations.

For each node, the elevation is computed as the area-weighted average of the elevations of the surrounding faces.

Returns:

None

get_reference_surface(reference_radius=None, only_faces=False, **kwargs)[source]#

Calculate the orientation of a hemispherical cap that represents the average surface within a given region.

Parameters:
  • reference_radius (float) – The radius of the reference region to compute the average over in meters. If None, the region_radius of the LocalSurface is used.

  • only_faces (bool) – If True, only return the face elevation data of the reference surface. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

NDArray[np.float64] – The face and node elevation points of the reference sphere, or the original elevation points is the reference region is too small

extract_subregion(subregion_radius, **kwargs)[source]#

Extract a subset of the LocalSurface region with a smaller radius than the original region.

Parameters:
  • subregion_radius (float) – The radius of the subregion to extract in meters.

  • **kwargs – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

LocalSurface – A LocalSurface object containing a view of the regional grid.

compute_volume(elevation)[source]#

Compute the volume of an array of elevation points.

Parameters:

elevation (NDArray) – The elevation values to compute. This should be the same size as the number of faces in the grid.

Returns:

float – The volume of the elevation points

elevation_to_cartesian(element='face')[source]#

Convert either the face or node elevations to Cartesian coordinates.

Parameters:

element (str, optional) – The type of element to convert. Can be “face” or “node”. Default is “face”.

Returns:

NDArray[np.float64, 3] – The Cartesian coordinates of the face elevations.

compute_radial_gradient(variable)[source]#

Compute the radial gradient of the local surface variable with respect to the local_location center.

Parameters:

variable (str or NDArray[np.float64]) – The variable to compute the radial gradient of. This can be a string (the name of a variable in the surface data) or an array of values the same size as the number of faces in the grid.

Returns:

NDArray[np.float64] – The radial gradient of all faces in meters per meter.

export(driver='GPKG', interval=None, ask_overwrite=None, **kwargs)[source]#

Export the surface view data to a specified file format and stores it in the default export directory.

If the format is “VTK,” the data will be exported using the Surface.to_vtk() method. Otherwise, it will use the Surface.to_vector_file() to export the data.

Parameters:
  • driver (str, optional) – The driver to use export the data to. Supported formats are ‘VTK’ or a driver supported by GeoPandas (‘GPKG’, ‘ESRI Shapefile’, etc.), and ‘GeoTIFF’.

  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • ask_overwrite (bool | None, optional) – If True, the user will be prompted to confirm before overwriting any existing files. If False, existing files will be overwritten without confirmation. If None, the default behavior of the class will be used. This will only persist for the duration of the export, and will be reset to its original value afterwards.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_vector_file(driver='GPKG', interval=None, to_file_kwargs=None, **kwargs)[source]#

Export the face-associated data from the surface view data to a vector file using GeoPandas.

See geopandas.GeoDataFrame.to_file for more detailed information on the available parameters.

Parameters:
  • driver (str, optional) – The file format driver to use for exporting. Default is ‘GPKG’.

  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • to_file_kwargs (dict | None, optional) – Additional keyword arguments to pass to the GeoDataFrame.to_file method.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_vtk_mesh(uxds=None, interval=None, **kwargs)[source]#

Exports the regional mesh to a VTK PolyData object.

Parameters:
  • uxds (UxDataset, optional) – The dataset to export. If None, the method will use currently loaded data in the surface. Default is None.

  • interval (int, optional) – The interval number to export. If provided, the method will either extract the interval number from uxds (if it has intervals saved), or, if no uxds is passed, load a saved interval from file.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

vtkUnstructuredGrid – The VTK PolyData object representing the regional mesh.

to_vtk_file(interval=None, **kwargs)[source]#

Export the regional mesh to a VTK file and store it in the default export directory.

Parameters:
  • interval (int, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_raster(uxda=None, **kwargs)[source]#

Rasterize a face-based variable into a 2D raster using rasterio.

Parameters:
  • uxda (UxDataArray | None) – The UxDataArray containing the face-based variable to rasterize. If None, the method will use currently loaded data in the surface with “face_elevation” as the default variable. Default is None.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

  • raster (NDArray[np.float32]) – The rasterized variable as a 2D numpy array.

  • extent (tuple[float, float, float, float]) – The extent of the raster in the format (xmin, xmax, ymin, ymax).

  • transform (Affine) – The affine transform for the raster.

  • crs (CRS) – The coordinate reference system of the raster.

get_raster_dims()[source]#

Get the dimensions of the raster based on the region radius (or target, if this is a global surface) and pixel size.

Returns:

tuple[int, int] – The width and height of the raster in pixels.

to_geotiff_file(interval=None, variable_name='face_elevation', **kwargs)[source]#

Rasterize a face-based elevation variable into a GeoTIFF using rasterio.

Parameters:
  • interval (int, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • variable_name (str, optional) – The name of the variable to rasterize. Default is “face_elevation”.

save(interval=0, time_variables=None, filename=None, **kwargs)[source]#

Save the region surface data to the specified directory.

Each data variable is saved to a separate NetCDF file. If ‘time_variables’ is specified, then a one or more variables will be added to the dataset along the time dimension.

Parameters:
  • interval (int, optional) – Interval number to append to the data file name. Default is 0.

  • time_variables (dict, optional) – Dictionary containing one or more variable name and value pairs. These will be added to the dataset along the time dimension. Default is None.

  • filename (Path | str, optional) – The path to the output file. If None, the file will be saved to the default

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

plot(filename=None, plot_style='map', variable_name=None, interval=None, cmap=None, label=None, scalebar=None, colorbar=True, show=True, save=False, ax=None, close_when_done=None, minimum_plot_width=800, **kwargs)[source]#

Plot an image of the local region.

Parameters:
  • filename (Path | str | None, optional) – The path to save the plot to. If None, and save is True, the plot will be saved to the default plot directory with a filename based on the interval number. Default is None.

  • plot_style (str, optional) – The style of the plot. Options are “map” and “hillshade”. In “map” mode, the variable is displayed as a colored map. In “hillshade” mode, a hillshade image is generated using “face_elevation” data. If a different variable is passed to variable, then the hillshade will be overlayed with that variable’s data. Default is “map”.

  • variable_name (str | None, optional) – The variable to plot. If None is provided then “face_elevation” is used in “map” mode.

  • interval (int | None, optional) – The interval number of the surface to plot. If None, the currently loaded surface data will be used.

  • cmap (str, optional) – The colormap to use for the plot. If None, a default colormap will be used (“cividis” by default and “grey” when plot_style==”hillshade” and variable==”face_elevation”).

  • label (str | None, optional) – A label for the plot. If None, no label will be added.

  • scalebar (bool, optional) – If True, a scalebar will be added to the plot. Default is True.

  • colorbar (bool, optional) – If True, a colorbar will be added to the plot when using “map” plot_style or “hillshade” with a variable overlay. Default is True.

  • show (bool, optional) – If True, the plot will be displayed. Default for local surfaces is True.

  • save (bool, optional) – If True, the plot will be saved to the default plot directory. Default is False unless filename is provided, in which case the default is True.

  • ax (matplotlib.axes.Axes, optional) – An existing Axes object to plot on. If None, a new figure and axes will be created.

  • close_when_done (bool, optional) – If True, the figure will be closed after plotting. Default is True when save is True and show is False, and False otherwise.

  • minimum_plot_width (float, optional) – Because the width of the plot is determined by the number of faces, small regions will generate small plots with labels that are hard to read. This parameter sets a lower limit to the width of the image that is generated by the plot. By default it is 800. Set to None to turn it off.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

matplotlib.axes.Axes – A Matplotlib Axes object containing the plot.

pyvista_plotter(variable_name=None, variable=None, interval=None, theme=None, transparent_background=None, plotter=None, enable_interactive=True, **kwargs)[source]#

Show the local surface region using an interactive 3D plot with PyVista.

Parameters:
  • variable_name (str | None, optional) – The name of the variable to plot. If the name of the variable is not already stored on the surface mesh, then the variable argument must also be passed. Default is None, which will plot a greyscale image of the surface.

  • variable ((n_face) array, optional) – An array face values that will be used to color the surface mesh. This is required if variable_name is not a face variable that is already saved in the the uxds dataset. Default is None.

  • interval (int | None, optional) – The interval number of the surface to plot. If None, the currently loaded surface data will be used. Default is None.

  • theme (str, optional) – The PyVista plot theme to use. If None, the default PyVista theme will be used. Default is None.

  • transparent_background (bool, optional) – If True, the background of the plot will be transparent. Default is None, which will use the default background setting for the chosen plot theme.

  • plotter (pyvista.Plotter, optional) – A pre-existing Plotter object to use. If None, then a new one will be created and returned. Default is None.

  • enable_interactive (bool, optional) – If True, the default PyVista key events will be updated to include custom events for toggling scalar visibility, changing the camera view, and showing a help message. Default is True.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

pyvista.Plotter – The PyVista Plotter object for further customization.

export_region_polygon(driver='GPKG', **kwargs)[source]#

Export the local surface region as a polygon to a vector file.

This will create a polygon that can be used for the OpenCraterTool plugin in QGIS.

Parameters:
  • driver (str, optional) – The OGR driver to use for exporting the polygon. Default is “GPKG”

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

compute_distances(locations, reference_location=None, validate=True)[source]#

Calculate the great circle distance between one point and one or more other points in meters.

Parameters:
  • locations (ArrayLike) – Longitude and latitude of the second point or array of points in degrees.

  • reference_location (PairOfFloats | None, optional) – Longitude and latitude of the first point in degrees. If None, then the center of the local region will be used. Default is None.

  • validate (bool, optional) – If the locations should be validated and normalized. Only use if the validation is causing a performance bottleneck.

Returns:

NDArray – Great circle distance between the two points in meters.

Notes

This is a wrapper for a compiled Rust function and is intended to be used as a helper to calculate_face_and_node_distances.

compute_bearings(locations, reference_location=None)[source]#

Calculate the initial bearing from one point to one or more other points in degrees.

Parameters:
  • locations (ArrayLike) – Longitude and latitude of the second point or array of points in degrees.

  • reference_location (PairOfFloats | None, optional) – Longitude and latitude of the first point in degrees. If None, then the center of the local region will be used. Default is None.

Returns:

NDArray – Initial bearing from the first point to the second point or points in degrees.

Notes

This is intended to be used as a helper to calculate_face_and_node_bearings.

compute_location_from_distance_bearing(distance, bearing, reference_location=None)[source]#

Calculate the longitude and latitude of one or more points given a reference point, initial bearings, and distances.

Parameters:
  • bearing (FloatLike | ArrayLike) – One or more initial bearing values from the reference point to the target point or points in degrees.

  • distance (FloatLike | ArrayLike) – One or more great circle distance from the reference point to the target point or points in meters.

  • reference_location (PairOfFloats | None, optional) – One pair of longitude and latitude of the reference point in degrees. If None, then the center of the local region will be used. Default is None.

Returns:

tuple or list of tuples the same length as bearing and distance. – longitude and latitude as a tuple of floats in degrees.

saved_output_files(**kwargs)[source]#

Check if the component has any output files in its output directory.

Returns:

list[Path] – A list of Path objects representing the files that would be removed during a reset operation. Returns an empty list if no files found

get_location_extents()[source]#

Computes the longitude and latitude extents of the local region.

Returns:

  • lon_min (float) – Minimum longitude in degrees.

  • lon_max (float) – Maximum longitude in degrees.

  • lat_min (float) – Minimum latitude in degrees.

  • lat_max (float) – Maximum latitude in degrees.

property surface#

The Surface object that contains the mesh data for the global surface.

property target#

The Target object associated with the LocalSurface.

property n_edge#

The number of edges in the view.

property n_face#

The number of faces in the view.

property n_node#

The number of nodes in the view.

property n_nodes_per_face#

The number of nodes per face in the view.

property face_size#

The effective pixel size of faces in the view in meters.

property location#

The (longitude, latitude) location of the center of the view in degrees.

property region_radius#

The radius of the region to include in the view in meters.

property face_bearing#

The initial bearing from the location to the faces measured clockwise relative to North in degrees.

property node_bearing#

The initial bearing from the location to the nodes measured clockwise relative to North in degrees.

property face_distance#

The distance from the location to the faces in meters.

property node_distance#

The distance from the location to the nodes in meters.

property face_area#

The areas of the faces in the view in m².

property face_lat#

Latitude of the center of the faces in the view in degrees.

property face_lon#

Longitude of the center of the faces in the viewin degrees.

property face_x#

Cartesian x location of the center of the faces in the view in meters.

property face_y#

Cartesian y location of the center of the faces in the view in meters.

property face_z#

Cartesian z location of the center of the faces in the view in meters.

property edge_face_distance#

Distances between the edges and the faces in the view in meters.

Dimensions: (n_edge)

property edge_length#

Lengths of the edges in the view in meters.

Dimensions: (n_edge)

property node_lat#

Latitude of the nodes in the view in degrees.

property node_lon#

Longitude of the nodes in the view in degrees.

property node_x#

Cartesian x location of the nodes in the view in meters.

property node_y#

Cartesian y location of the nodes in the view in meters.

property node_z#

Cartesian z location of the nodes in the view in meters.

property area#

The total area of the faces in the view in m².

property face_indices#

The indices of the faces in the view.

property node_indices#

The indices of the nodes in the view.

property edge_indices#

The indices of the edges in the view.

property edge_face_connectivity#

Local indices of the faces that make up the edges.

Dimensions: (n_edge, 2)

property face_edge_connectivity#

Local indices of the edges that make up the faces.

Dimensions: (n_face, n_max_face_edges)

property face_node_connectivity#

Local indices of the nodes that make up the faces.

Dimensions: (n_face, n_max_face_nodes)

Nodes are in counter-clockwise order.

property face_face_connectivity#

Indices of the faces that surround the faces.

Dimensions: (n_face, n_max_face_faces)

property node_face_connectivity#

Indices of the faces that surround the nodes.

Dimensions: (n_node, n_max_node_faces)

property edge_node_connectivity#

Local indices of the nodes that make up the edges.

Dimensions: (n_edge, 2)

property crs#

Return a local Azimuthal Equidistant (LAEA) CRS centered on self.location (in meters).

If self.location is not set, fall back to the parent Surface geographic CRS. The LAEA CRS uses the target body’s spherical radius.

read_saved_output(interval=None, reset=False, **kwargs)[source]#

Read the saved local surface data from disk for a given interval number and return it as a UxDataset.

Parameters:
  • interval (int | None, optional) – Interval number of data file to read. Default is None (all intervals are read).

  • reset (bool, optional) – Flag to indicate whether to reset the surface. If True it reads in the grid but creates an empty dataset and saves it to interval 0. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

  • UxDataset – An initialized UxDataset object containing the grid and data.

  • Dataset – The xarray Dataset containing only the local surface data.

property uxgrid#

The Uxarrray Grid representation of the local surface.

property uxds#

The UxDataset representation of the local surface.

property grid_file#

Path to the grid file.

property pix#

The effective pixel size of the base surface in meters.

property radius#

The radius of the local region in meters.

property plot_dir#

The directory to save plots to.

property from_surface#

A pyproj Transformer object to convert from the surface CRS to the local CRS.

property to_surface#

A pyproj Transformer object to convert from the local CRS to the surface CRS.

set_face_proj()[source]#

Set the projected x and y coordinates of the faces relative to the LocalSurface center.

set_node_proj()[source]#

Set the projected x and y coordinates of the nodes relative to the LocalSurface center.

property face_proj_x#

The projected x coordinates of the faces relative to the LocalSurface center in meters.

property face_proj_y#

The projected y coordinates of the faces relative to the LocalSurface center in meters.

property node_proj_x#

The projected x coordinates of the nodes relative to the LocalSurface center in meters.

property node_proj_y#

The projected y coordinates of the nodes relative to the LocalSurface center in meters.

property desloped_face_elevation#

The face elevations with the mean slope of the region removed in meters.

compute_desloped_face_elevation()[source]#

Compute the face elevations with the mean slope of the region removed.

property is_local#

Whether this surface is a local region or the full global surface.

property is_global#

Whether this surface is the full global surface.

data_composer()[source]#

Creates a DataComposer tied to this LocalSurface. This should usually be called in a with statement.

Returns:

DataComposer

property face_variables#

Returns a list of the data variables currently being stored on the faces.

property node_variables#

Returns a list of the data variables currently being stored on the nodes.

class cratermaker.components.surface.DataComposer(surface)[source]#

Bases: AbstractContextManager

Created using Surface.data_composer or LocalSurface.data_composer. Contains some static methods for loading LOLA data.

add_data(data)[source]#

Adds data to eventually be applied to the surface.

The data isn’t applied until finish is called or, if appplicable, self exits the with context.

Parameters:

dataset (DatasetReader | str | list[DatasetReader | str]) – A single dataset or a list of multiple datasets to be merged. Calls rasterio.open when necessary.

cancel()[source]#

Cancels the execution and closes all open datasets.

finish()[source]#

Apply all the datasets to the mesh and close them. This is implicitly called when exiting a with context.

static get_lola_cylindrical_files_from_pds(resolution, lat_range, lon_range)[source]#

Retrieve the appropriate cylindrically projected LOLA DEM file url or list of urls for a given location and resolution from the PDS.

This will determine which, if any, boundaries are crossed and will return a list of files to cover a region.

Parameters:
  • resolution (FloatLike) – Requested resolution in degrees per pixel. The closest available resolution will be used.

  • lat_range (tuple of float, optional) – The (min_lat, max_lat) in degrees of the local region.

  • lon_range (tuple of float, optional) – The (min_lon, max_lon) in degrees of the local region.

static get_lola_polar_files_from_pds(resolution, lat_range)[source]#

Retrieve the appropriate polar projected LOLA DEM file url for a given location and resolution from the PDS.

Parameters:
  • resolution (FloatLike) – Requested resolution in meters per pixel. The closest available resolution will be used.

  • lat_range (tuple of float) – The (min_lat, max_lat) in degrees of the local region.

static get_lola_dem_file_list(pix, lat_range, lon_range)[source]#

Determine the set of LOLA DEM files needed to cover the local region.

Parameters:
  • pix (FloatLike) – The approximate resolution in meters per pixel to use to select the DEM files.

  • lat_range (PairOfFloats, optional) – The (min_lat, max_lat) in degrees of the local region.

  • lon_range (PairOfFloats, optional) – The (min_lon, max_lon) in degrees of the local region.

populate_with_lola_data(pix=None)[source]#

Loads the DEM files from LOLA needed to cover the surface.

Parameters:

pix (FloatLike) – The approximate resolution in meters per pixel to use to select the DEM files. Defaults to the resolution of the surface used.

property localsurface#

The LocalSurface used to create the DataComposer.

property surface#

The Surface used to create the DataComposer.

property finished#

Whether finish() or cancel() has been called or not.

IcosphereSurface#

See Surface for inherited methods and attributes.

class cratermaker.components.surface.icosphere.IcosphereSurface(gridlevel=8, target=None, reset=True, regrid=False, simdir=None, **kwargs)[source]#

Bases: Surface

Create a uniform grid configuration using an icosphere. This is the most accurate and efficient way to create a uniform grid, but is limited to a few resolutions.

Parameters:
  • gridlevel (float, default 8) – The subdivision level of the icosphere.

  • target (Target, optional) – The target body or name of a known target body for the impact simulation.

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is True.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • simdir (str | Path) – The main project simulation directory. Default is the current working directory if None.

Returns:

IcosphereSurface – An instance of the IcosphereSurface class initialized with the given pixel size.

Notes

The number of faces of the icosphere is given by the formula:

\[n_{face} = 10 * 4^{gridlevel} + 2\]

The number of nodes is given by the formula:

\[n_{node} = 20 * 4^{gridlevel}\]
property gridlevel#

The subdivision level of the icosphere.

property pix#

The approximate face size for a cell of the mesh in meters.

Usage example#

1 from cratermaker import Surface
2 surface = Surface.maker("icosphere",gridlevel=7)

ArbitraryResolutionSurface#

See Surface for inherited methods and attributes.

class cratermaker.components.surface.arbitrary_resolution.ArbitraryResolutionSurface(pix=None, target=None, reset=True, regrid=False, simdir=None, **kwargs)[source]#

Bases: Surface

Create a uniform grid configuration with an arbitrary user-defined pixel size. This will not be as nice as the regular IcosphereSurface, but can be any resolution desired.

Parameters:
  • pix (float) – The approximate face size for the mesh in meters.

  • target (Target, optional) – The target body or name of a known target body for the impact simulation.

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is True.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • simdir (str | Path) – The main project simulation directory. Default is the current working directory if None.

Returns:

ArbitraryResolutionSurface – An instance of the ArbitraryResolutionSurface class initialized with the given pixel size.

property pix#

The approximate face size for a cell of the mesh.

Usage example#

1 from cratermaker import Surface
2 surface = Surface.maker("arbitrary_resolution",pix=100)

HiResLocalSurface#

See Surface for inherited methods and attributes.

class cratermaker.components.surface.hireslocal.HiResLocalSurface(pix, local_radius, local_location=None, superdomain_scale_factor=None, target=None, reset=True, regrid=False, simdir=None, **kwargs)[source]#

Bases: Surface

Create a uniform grid configuration with the given pixel size.

Parameters:
  • pix (FloatLike) – The approximate face size inside the local region in meters.

  • local_radius (FloatLike) – The radius of the local region in meters.

  • local_location (PairOfFloats | None) – The longitude and latitude of the location in degrees. If None, it will be set to (0.0, 0.0).

  • superdomain_scale_factor (FloatLike, optional) – A factor defining relative size of the face at the antipode of the local region to the face size inside the local region. If not provided, construction of the surface will be deferred until the set_superdomain method is called. If a negative number is provided, it will be computed based on a provided (or default) scaling and morphology model, and will be set so that smallest craters that can be resolved on faces outside the local region could potentially deposit ejecta at the boundary of the local region. Default is -1 (which triggers automatic computation based on scaling and morphology models).

  • target (Target, optional) – The target body or name of a known target body for the impact simulation. If none provide, it will be either set to the default, or extracted from the scaling model if it is provied

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is True.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • simdir (str | Path) – The main project simulation directory. Default is the current working directory if None.

Returns:

HiResLocalSurface – An instance of the HiResLocalSurface clas initialized with the given point distribution

reset(**kwargs)[source]#

Resets the surface by removing all saved output files (except for the grid).

This will also reset the local surface.

superdomain_function(r)[source]#

Defines the superdomain scale factor based on the distance from the local boundary.

This is set so that smallest craters that are modeled outside the local region are those whose ejecta could just reach the boundary. It is a piecewise function that returns the local pixel size inside the local region and a power law function outside. The slope and exponent of the power law is linear if superdomain_scale_factor is set explicitly, otherwise it is computed by the set_superdomain method.

Parameters:

r (FloatLike) – The distance from the local center in meters.

Returns:

FloatLike – The effective pixel size at the given distance from the local center.

extract_region(location, region_radius, at_least_one_face=False, **kwargs)[source]#

Extract a regional grid based on a given location and radius.

Parameters:
  • location (tuple[float, float]) – tuple containing the longitude and latitude of the location in degrees.

  • region_radius (float) – The radius of the region to extract in meters.

  • at_least_one_face (bool, optional) – If True, ensure that at least one face is returned, even if the region radius is very small. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

LocalSurface – A LocalSurface object containing a view of the regional grid.

save(interval=0, time_variables=None, **kwargs)[source]#

Save the surface data to the specified directory.

Each data variable is saved to a separate NetCDF file. If ‘time_variables’ is specified, then a one or more variables will be added to the dataset along the time dimension. If ‘interval’ is included as a key in time_variables, then this will be appended to the data file name.

Parameters:
  • interval (int, optional) – Interval number to append to the data file name. Default is 0.

  • time_variables (dict, optional) – Dictionary containing one or more variable name and value pairs. These will be added to the dataset along the time dimension. Default is None.

export(driver='GPKG', interval=None, superdomain=False, ask_overwrite=None, **kwargs)[source]#

Export the surface data to the specified format.

Parameters:
  • driver (str, optional) – The driver to use export the data to. Supported formats are ‘VTK’ or a driver supported by GeoPandas (‘GPKG’, ‘ESRI Shapefile’, etc.).

  • interval (int | None, optional) – The interval number to export. If None, all intervals currently saved will be exported. Default is None.

  • superdomain (bool, optional) – If True, export the full surface including the superdomain. If False, export only the local region. Default is False.

  • ask_overwrite (bool | None, optional) – If True, the user will be prompted to confirm before overwriting any existing files. If False, existing files will be overwritten without confirmation. If None, the default behavior of the class will be used. This will only persist for the duration of the export, and will be reset to its original value afterwards.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

plot(plot_style='map', variable_name=None, interval=None, cmap=None, label=None, scalebar=None, colorbar=True, show=True, save=False, ax=None, close_when_done=None, minimum_plot_width=800.0, superdomain=False, **kwargs)[source]#

Plot an image of the surface.

Parameters:
  • plot_style (str, optional) – The style of the plot. Options are “map” and “hillshade”. In “map” mode, the variable is displayed as a colored map. In “hillshade” mode, a hillshade image is generated using “face_elevation” data. If a different variable is passed to variable, then the hillshade will be overlayed with that variable’s data. Default is “map”.

  • variable_name (str | None, optional) – The variable to plot. If None is provided then “face_elevation” is used in “map” mode.

  • interval (int | None, optional) – The interval number of the surface to plot. If None, the currently loaded surface data will be used.

  • cmap (str, optional) – The colormap to use for the plot. If None, a default colormap will be used (“cividis” by default and “grey” when plot_style==”hillshade” and variable==”face_elevation”).

  • label (str | None, optional) – A label for the plot. If None, no label will be added.

  • scalebar (bool, optional) – If True, a scalebar will be added to the plot. Default is True.

  • colorbar (bool, optional) – If True, a colorbar will be added to the plot when using “map” plot_style or “hillshade” with a variable overlay. Default is True.

  • show (bool, optional) – If True, the plot will be displayed. Default for local surfaces is True.

  • save (bool, optional) – If True, the plot will be saved to the default plot directory. Default is False.

  • ax (matplotlib.axes.Axes, optional) – An existing Axes object to plot on. If None, a new figure and axes will be created.

  • close_when_done (bool, optional) – If True, the figure will be closed after plotting. Default is True when save is True and show is False, and False otherwise.

  • minimum_plot_width (float, optional) – Because the width of the plot is determined by the number of faces, small regions will generate small plots with labels that are hard to read. This parameter sets a lower limit to the width of the image that is generated by the plot. By default it is 800. Set to None to turn it off.

  • superdomain (bool, optional) – If True, plot the full surface including the superdomain. If False, plot only the local region. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

to_raster(variable_name='face_elevation', superdomain=False, **kwargs)[source]#

Rasterize a face-based variable into a 2D raster using rasterio.

Parameters:
  • variable_name (str, optional) – The name of the variable to rasterize. Default is “face_elevation”.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

  • raster (NDArray[np.float32]) – The rasterized variable as a 2D numpy array.

  • extent (tuple[float, float, float, float]) – The extent of the raster in the format (xmin, xmax, ymin, ymax).

  • transform (Affine) – The affine transform for the raster.

  • crs (CRS) – The coordinate reference system of the raster.

to_geotiff_file(interval=None, variable_name='face_elevation', superdomain=False, **kwargs)[source]#

Rasterize a face-based elevation variable into a GeoTIFF using rasterio.

Parameters:
  • interval (int | None, optional) – The interval number to export. Default is None, which will export all saved intervals.

  • variable_name (str, optional) – The name of the variable to rasterize. Default is “face_elevation”.

  • superdomain (bool, optional) – If True, export the full surface including the superdomain. If False, export only the local region. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

pyvista_plotter(variable_name=None, variable=None, superdomain=False, **kwargs)[source]#

Show the surface using an interactive 3D plot.

Parameters:
  • engine (str, optional) – The engine to use for plotting. Currently, only “pyvista” is supported. Default is “pyvista”.

  • variable_name (str | None, optional) – The name of the variable to plot. If the name of the variable is not already stored on the surface mesh, then the variable argument must also be passed. Default is None, which will plot a greyscale image of the surface.

  • variable ((n_face) array, optional) – An array face values that will be used to color the surface mesh. This is required if variable_name is not stored on the mesh.

  • superdomain (bool, optional) – If True, show the full surface including the superdomain. If False, show only the local region. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

Returns:

pyvista.Plotter – The PyVista Plotter object for further customization.

set_superdomain(morphology=None, reset=False, regrid=False, **kwargs)[source]#

Set the superdomain scale factor based on the scaling and morphology models.

This sets the cell size at the antipode such that ejecta from a crater of that size just reaches the local region.

Parameters:
  • morphology (Morphology | str | None, optional) – The morphology model to use. If None, the default morphology model will be used.

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is False.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

set_face_proj()[source]#

Set the face projection for the local surface.

set_node_proj()[source]#

Set the node projection for the local surface.

compute_location_from_distance_bearing(distance, bearing, reference_location=None)[source]#

Calculate the longitude and latitude of one or more points given a reference point, initial bearings, and distances.

Parameters:
  • bearings (FloatLike or ArrayLike) – Initial bearing from the reference point to the target point or points in degrees.

  • distances (FloatLike or ArrayLike) – Great circle distance from the reference point to the target point or points in meters.

  • reference_location (PairOfFloats, optional) – Longitude and latitude of the reference point in degrees. Default is the value of local_location

Returns:

NDArray – Longitude and latitude of the target point or points in degrees.

property local#

Returns the local view of the surface.

property pix#

The approximate face size for a cell of the mesh.

property local_radius#

The radius of the local region in meters.

property local_location#

The longitude and latitude of the location in degrees.

property local_grid_indices_file#

The path to the local grid indices file.

property superdomain_function_slope#
property superdomain_function_exponent#
property superdomain_scale_factor#

A factor defining the ratio of cell size to the distance from the local boundary.

This is set so that smallest craters that are modeled outside the local region are those whose ejecta could just reach the boundary.

class cratermaker.components.surface.hireslocal.LocalHiResLocalSurface(surface, face_indices=None, node_indices=None, edge_indices=None, location=None, region_radius=None, **kwargs)[source]#

Bases: LocalSurface

Generates a regional view of a subset of the surface mesh without making copies of any of the data.

Parameters:
  • surface (Surface) – The surface object that contains the mesh data.

  • face_indices (NDArray | slice) – The indices of the faces to include in the view.

  • node_indices (NDArray | slice | None, optional) – The indices of the nodes to include in the view. If None, all nodes connected to the faces will be extracted when required

  • edge_indices (NDArray | slice | None, optional) – The indices of the edges to include in the view. If None, all edges connected to the faces will be extracted when required.

  • location (tuple[float, float] | None, optional) – The location of the center of the view in degrees. This is intended to be passed via the extract_region method of Surface.

  • region_radius (FloatLike | None, optional) – The radius of the region to include in the view in meters. This is intended to be passed via the extract_region method of Surface.

add_tag(name, tag=None, long_name=None, tag_superdomain=False, **kwargs)[source]#

Adds an integer tag to the surface with an option to tag faces in the superdomain.

Parameters:
  • name (str) – The name of the tag to be added.

  • tag (int | None) – The integer to apply the tag. If None is provided, the tag layers will be reset to zero

  • long_name (str | None) – The long name of the tag to be added. If None, no long name will be added.

  • tag_superdomain (bool = False,) – If True, apply the tag to surface including the superdomain. If False, apply only to the local region. Default is False.

  • **kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

apply_diffusion(kdiff)[source]#

Apply diffusion to the surface.

Parameters:

kdiff (float or array-like) – The degradation state of the surface, which is the product of diffusivity and time. It can be a scalar or an array of the same size as the number of faces in the grid. If it is a scalar, the same value is applied to all faces. If it is an array, it must have the same size as the number of faces in the grid. The value of kdiff must be greater than 0.0.

Notes

This method only operates on the faces that overlap with the local region of the surface.

slope_collapse(critical_slope_angle=35.0)[source]#

Collapse all slopes larger than the critical slope angle.

Parameters:

critical_slope_angle (float) – The critical slope angle (angle of repose) in degrees.

Notes

This method only operates on the faces that overlap with the local region of the surface.

apply_noise(model='turbulence', noise_width=1000000.0, noise_height=1000.0, **kwargs)[source]#

Apply noise to the node elevations of the surface view.

Parameters:
  • noise_width (float) – The spatial wavelength of the noise.

  • noise_height (float) – The amplitude of the noise.

Notes

This method only operates on the faces that overlap with the local region of the surface.

extract_subregion(subregion_radius)[source]#

Extract a subset of the LocalHiResLocalSurface region with a smaller radius than the original region.

Parameters:

subregion_radius (float) – The radius of the subregion to extract in meters.

Returns:

LocalHiResLocalSurface – A LocalHiResSurface object containing a view of the regional grid.

property local_grid_indices_file#

The path to the local grid file.

property local_overlap#

A LocalSurface object that contains the overlap between this object and the high resolution local region of the surface, or None if there is no overlap.

property edge_mask#

A boolean indicating which edge indices overlap with the local region.

property face_mask#

A boolean indicating which face indices overlap with the local region.

property node_mask#

A boolean indicating which node indices overlap with the local region.

Usage example#

1 from cratermaker import Surface
2 surface = Surface.maker("hireslocal", pix=50, local_radius=1e3, local_location=(0,9))

DataSurface#

See api-HiResLocalSurface for inherited methods and attributes.

class cratermaker.components.surface.datasurface.DataSurface(local_radius, local_location, superdomain_scale_factor=-1, target=None, reset=True, regrid=False, simdir=None, pix=None, dem_file_list=None, superdomain_dem_file=None, **kwargs)[source]#

Bases: HiResLocalSurface

A Surface subclass that generates a local region using DEM data.

Currently implements only lunar LOLA data from the PDS. Other data sources may be added in the future.

Parameters:
  • local_radius (FloatLike) – The radius of the local region in meters.

  • local_location (PairOfFloats) – The longitude and latitude of the location in degrees.

  • superdomain_scale_factor (FloatLike, optional) – A factor defining relative size of the face at the antipode of the local region to the face size inside the local region. If not provided, construction of the surface will be deferred until the set_superdomain method is called. If a negative number is provided, it will be computed based on a provided (or default) scaling and morphology model, and will be set so that smallest craters that can be resolved on faces outside the local region could potentially deposit ejecta at the boundary of the local region. Default is -1 (which triggers automatic computation based on scaling and morphology models).

  • target (Target, optional) – The target body or name of a known target body for the impact simulation. If none provide, it will be either set to the default, or extracted from the scaling model if it is provied

  • reset (bool, optional) – Flag to indicate whether to reset the surface. Default is True.

  • regrid (bool, optional) – Flag to indicate whether to regrid the surface. Default is False.

  • simdir (str | Path) – The main project simulation directory. Default is the current working directory if None.

  • pix (FloatLike | None, optional) – The approximate face size inside the local region in meters. This will be used to determine the target resolution of the DEM data to be used. The actual resolution may be different based on the available DEM data. Note that if you provide a list of DEM files using the dem_file_list parameter, this value will be ignored. If None, is set, and no file(s) are provided, a default resolution that creates approximately 1e6 faces in the local region will be used.

  • local_radius (FloatLike)

  • dem_file_list (list of str | Path, optional) – A list of one or more DEM files or urls links to files to be used for the local region. If not provided, a set of files will be determined based on the location and radius of the region. It will chose a set of files that fully covers the local region with approximately approximately 1e6 faces.

  • superdomain_dem_file (str | Path, optional) – A global DEM files or urs link to a file to be used for the superdomain region. If not provided, a default global DEM file will be used based on the target body.

  • **kwargs (Any)

Returns:

DataSurface – An instance of the DataSurface class initialized with faces and elevations drawn from DEM data

Notes

Currently this only uses LOLA DEM data for the Moon.

reset(**kwargs)[source]#

Reset the surface to its initial state.

Parameters:

**kwargs (Any) – Additional keyword arguments that are either ignored or passed to internal functions as needed.

property dem_file_list#

The list of files to use for the DEM data in the high resolution local region.

property superdomain_dem_file#

The list of files to use for the DEM data in the superdomain.

Usage example#

This creates a DataSurface with a local region containing Kepler crater. The resolution of the local surface will be approxiamtely half of what it would be if pix was not set.

1 from cratermaker import Surface
2 surface = Surface.maker("datasurface", pix=200.0, local_location=(321.9913, 8.121), local_radius=50.0e3)