diff --git a/LoopStructural/export/exporters.py b/LoopStructural/export/exporters.py index b54a8f32b..9cd29c48a 100644 --- a/LoopStructural/export/exporters.py +++ b/LoopStructural/export/exporters.py @@ -2,15 +2,11 @@ Routines to export geological model data to file in a variety of formats """ -import os - import numpy as np from pyevtk.hl import pointsToVTK, unstructuredGridToVTK from pyevtk.vtk import VtkTriangle -from skimage.measure import marching_cubes from LoopStructural.export.file_formats import FileFormat -from LoopStructural.geometry import Surface from LoopStructural.utils.helper import create_box from ..utils import getLogger @@ -18,266 +14,6 @@ logger = getLogger(__name__) -def write_feat_surfs( - model, featurename, file_format=FileFormat.NUMPY, file_name=None, isovalue=0.0 -): - """ - Writes out features from a model as 3d surfaces - - Parameters - ---------- - model: GeologicalModel object - Geological model to export - file_name: string - Name of file that model is exported to, including path, but without the file extension - file_format: export.fileformats.FileFormat object - OPTIONAL desired format of exported file. Supports GOCAD, VTK & NUMPY. Default is NUMPY - target_feats: list - OPTIONAL list of feature names to export, if omitted all faults are exported - isovalue: float - OPTIONAL isovalue point at which surface is generated, default is 0.0 - - Returns - ------- - Tuple of (boolean, [ SimpleNamespace() ... ]) - If successful, boolean is True and SimpleNamespace() objects have the following attributes: - verts: vertices, numpy ndarray with dtype = float64 & shape = (N,3) - faces: faces, numpy ndarray with dtype = int32 & shape = (M,3) - values: values, numpy ndarray with dtype = float32 & shape = (N,) - normals: normals, numpy ndarray with dtype = float32 & shape = (N,3) - name: name of feature e.g. fault or supergroup, string - If not successful, it returns (False, []) - """ - # Set up the type of file writer function - if file_format == FileFormat.GOCAD: - write_fn = _write_feat_surfs_gocad - elif file_format == FileFormat.VTK: - write_fn = _write_feat_surfs_evtk - elif file_format == FileFormat.NUMPY: - write_fn = None - else: - logger.warning(f"Cannot export to surface file - format {file_format} not supported yet") - return False, [] - # Skip if not a requested feature - if featurename not in model: - logger.warning("{featurename} is not in the model, skipping") - return False, [] - has_feats = True - - x = np.linspace(model.bounding_box.bb[0, 0], model.bounding_box.bb[1, 0], model.nsteps[0]) - y = np.linspace(model.bounding_box.bb[0, 1], model.bounding_box.bb[1, 1], model.nsteps[1]) - z = np.linspace(model.bounding_box.bb[1, 2], model.bounding_box.bb[0, 2], model.nsteps[2]) - xx, yy, zz = np.meshgrid(x, y, z, indexing="ij") - points = np.array([xx.flatten(), yy.flatten(), zz.flatten()]).T - val = model[featurename].evaluate_value(points) - step_vector = np.array([x[1] - x[0], y[1] - y[0], z[1] - z[0]]) - logger.info(f"Creating isosurface of {featurename} at {isovalue}") - - if isovalue > np.nanmax(val) or isovalue < np.nanmin(val): - logger.warning( - f"For {featurename} isovalue {isovalue} doesn't exist inside bounding box, skipping" - ) - return False, [] - try: - verts, faces, normals, values = marching_cubes( - val.reshape(model.nsteps, order="C"), isovalue, spacing=step_vector - ) - verts += np.array( - [ - model.bounding_box.bb[0, 0], - model.bounding_box.bb[0, 1], - model.bounding_box.bb[1, 2], - ] - ) - surf = Surface( - vertices=verts, - triangles=faces, - normals=normals, - values=values, - name=featurename.replace(" ", "-"), - ) - - except (ValueError, RuntimeError) as e: - logger.debug(f"Exception creating feature surface {featurename}: {e}") - logger.warning(f"Cannot isosurface {featurename} at {isovalue}, skipping") - return False, [] - - if not has_feats: - logger.warning("Cannot locate features in model") - return False, [] - - # Call the file writer function - result = True - if write_fn is not None: - result = write_fn(surf, file_name) - return result - - -def _write_feat_surfs_evtk(surf, file_name): - """ - Writes out an unstructured VTK file containing a 2d fault surface - - Parameters - ---------- - surf_list: [ SimpleNamespace() ... ] - Details of the surfaces, as a list of SimpleNamespace() objects. Fields are: - verts: vertices, numpy ndarray with dtype = float64 & shape = (N,3) - faces: faces, numpy ndarray with dtype = int32 & shape = (M,3) - values: values, numpy ndarray with dtype = float32 & shape = (N,) - normals: normals, numpy ndarray with dtype = float32 & shape = (N,3) - name: name of feature e.g. fault or supergroup, string - - file_name: string - file name to be written out without extension - - Returns - ------- - True if successful - - """ - connectivity = np.zeros(0) - offsets = np.zeros(0) - cell_types = np.zeros(0) - x = np.zeros(0) - y = np.zeros(0) - z = np.zeros(0) - conn_idx = 0 - offset_idx = 0 - pointData = np.zeros(0) - - # Concatenate the geometry of all features into x, y, z, connectivity, offsets & cell_types - - # Accumulate x,y,z values in 1-d array - x = np.append(x, np.ascontiguousarray(surf.verts[:, 0])) - y = np.append(y, np.ascontiguousarray(surf.verts[:, 1])) - z = np.append(z, np.ascontiguousarray(surf.verts[:, 2])) - - # Convert faces to int64 - conn = np.array(surf.faces, dtype=np.int64) - - # Reshape connections to 1d - conn = conn.reshape(conn.size) - conn += conn_idx - - # Make offsets into connection array - offs = np.array(list(range(3 + offset_idx, len(conn) + offset_idx, 3)), dtype=np.int64) - - # Set VTK datatype as triangles - ctype = np.zeros(offs.size) - ctype.fill(VtkTriangle.tid) - - # Accumulate values in arrays - connectivity = np.append(connectivity, conn) - - offsets = np.append(offsets, offs) - cell_types = np.append(cell_types, ctype) - - pointData = np.append(pointData, surf.values.reshape(surf.values.size)) - - # Enable connections to point to next set of vertices - conn_idx = x.size - - # Enable offsets to point to next set of connections - offset_idx = connectivity.size - - # Write out file - try: - logger.info(f"Writing file {file_name}.vtu") - unstructuredGridToVTK( - f"{file_name}", - x, - y, - z, - connectivity=connectivity, - offsets=offsets, - cell_types=cell_types, - pointData={"values": pointData}, - ) - except (OSError, ValueError) as e: - logger.warning(f"Cannot export fault surface to VTK file {file_name}: {e}") - return False - - return True - - -def _write_feat_surfs_gocad(surf, file_name): - """ - Writes out a GOCAD TSURF file for each surface in list - - Parameters - ---------- - surf_list: [ SimpleNamespace() ... ] - Details of the surfaces, as a list of SimpleNamespace() objects. Fields are: - verts: vertices, numpy ndarray with dtype = float64 & shape = (N,3) - faces: faces, numpy ndarray with dtype = int32 & shape = (M,3) - values: values, numpy ndarray with dtype = float32 & shape = (N,) - normals: normals, numpy ndarray with dtype = float32 & shape = (N,3) - name: name of feature e.g. fault or supergroup, string - - file_name: string - Desired filename - - Returns - ------- - True if successful - - """ - from pathlib import Path - - file_name = Path(file_name).with_suffix(".ts") - with open(f"{file_name}", "w") as fd: - fd.write( - f"""GOCAD TSurf 1 -HEADER {{ -*solid*color: #ffa500 -ivolmap: false -imap: false -name: {surf.name} -}} -GOCAD_ORIGINAL_COORDINATE_SYSTEM -NAME Default -PROJECTION Unknown -DATUM Unknown -AXIS_NAME X Y Z -AXIS_UNIT m m m -ZPOSITIVE Elevation -END_ORIGINAL_COORDINATE_SYSTEM -GEOLOGICAL_FEATURE {surf.name} -GEOLOGICAL_TYPE fault -PROPERTY_CLASS_HEADER X {{ -kind: X -unit: m -}} -PROPERTY_CLASS_HEADER Y {{ -kind: Y -unit: m -}} -PROPERTY_CLASS_HEADER Z {{ -kind: Z -unit: m -is_z: on -}} -PROPERTY_CLASS_HEADER vector3d {{ -kind: Length -unit: m -}} -TFACE -""" - ) - v_idx = 1 - v_map = {} - for idx, vert in enumerate(surf.vertices): - if not np.isnan(vert[0]) and not np.isnan(vert[1]) and not np.isnan(vert[2]): - fd.write(f"VRTX {v_idx:} {vert[0]} {vert[1]} {vert[2]} \n") - v_map[idx] = v_idx - v_idx += 1 - for face in surf.triangles: - if face[0] in v_map and face[1] in v_map and face[2] in v_map: - fd.write(f"TRGL {v_map[face[0]]} {v_map[face[1]]} {v_map[face[2]]} \n") - fd.write("END\n") - return True - - def write_cubeface(model, file_name, data_label, nsteps, file_format): """ Writes out the model as a cuboid with six rectangular surfaces @@ -322,7 +58,7 @@ def write_vol(model, file_name, data_label, nsteps, file_format): nsteps : np.array([num-x-steps, num-y-steps, num-z-steps]) 3d array dimensions file_format: export.fileformats.FileFormat object - Desired format of exported file. Supports VTK and GOCAD + Desired format of exported file. Supports VTK Returns ------- @@ -331,8 +67,6 @@ def write_vol(model, file_name, data_label, nsteps, file_format): """ if file_format == FileFormat.VTK: return _write_vol_evtk(model, file_name, data_label, nsteps) - if file_format == FileFormat.GOCAD: - return _write_vol_gocad(model, file_name, data_label, nsteps) logger.warning(f"Cannot export to file - format {file_format} not supported yet") return False @@ -439,110 +173,3 @@ def _write_vol_evtk(model, file_name, data_label, nsteps, real_coords=True): logger.warning(f"Cannot export volume to VTK file {file_name}: {e}") return False return True - - -def _write_vol_gocad(model, file_name, data_label, nsteps, real_coords=True): - """ - Writes out the model as a 3d volume grid in GOCAD VOXET object format - - Parameters - ---------- - model : GeologicalModel object - Geological model to export - file_name : string - Name of file that model is exported to, including path, but without the file extension - data_label : string - A data label to insert into export file - nsteps : np.array([num-x-steps, num-y-steps, num-z-steps]) - 3d array dimensions - - Returns - ------- - True if successful - - """ - # Define grid spacing (world coordinates -- evaluate_model/features now - # project world -> local internally) - xyz = model.bounding_box.regular_grid(nsteps=nsteps, local=False) - - vals = model.evaluate_model(xyz, scale=False) - # Use FORTRAN style indexing for GOCAD VOXET - vol_vals = np.reshape(vals, nsteps, order="F") - bbox = model.bounding_box[:] - - # If integer values - if type(vals[0]) is np.int64: - d_type = np.int8 - no_data_val = None - prop_esize = 1 - prop_storage_type = "Octet" - - # If float values - elif type(vals[0]) is np.float32: - d_type = np.dtype(">f4") - no_data_val = -999999.0 - prop_esize = 4 - prop_storage_type = "Float" - else: - logger.warning( - f"Cannot export volume to GOCAD VOXET file: Unsupported type {type(vals[0])}" - ) - return False - - # Write out VOXET file - vo_filename = file_name + ".vo" - data_filename = file_name + "@@" - try: - with open(vo_filename, "w") as fp: - fp.write( - f"""GOCAD Voxet 1 -HEADER {{ -name: {os.path.basename(file_name)} -}} -GOCAD_ORIGINAL_COORDINATE_SYSTEM -NAME Default -AXIS_NAME "X" "Y" "Z" -AXIS_UNIT "m" "m" "m" -ZPOSITIVE Elevation -END_ORIGINAL_COORDINATE_SYSTEM -AXIS_O 0.000000 0.000000 0.000000 -AXIS_U 1.000000 0.000000 0.000000 -AXIS_V 0.000000 1.000000 0.000000 -AXIS_W 0.000000 0.000000 1.000000 -AXIS_MIN {bbox[0, 0]} {bbox[0, 1]} {bbox[0, 2]} -AXIS_MAX {bbox[1, 0]} {bbox[1, 1]} {bbox[1, 2]} -AXIS_N {nsteps[0]} {nsteps[1]} {nsteps[2]} -AXIS_NAME "X" "Y" "Z" -AXIS_UNIT "m" "m" "m" -AXIS_TYPE even even even -PROPERTY 1 {data_label} -PROPERTY_CLASS 1 {data_label} -PROP_UNIT 1 {data_label} -PROPERTY_CLASS_HEADER 1 {data_label} {{ -}} -PROPERTY_SUBCLASS 1 QUANTITY {prop_storage_type} -""" - ) - if no_data_val is not None: - fp.write(f"PROP_NO_DATA_VALUE 1 {no_data_val}\n") - fp.write( - f"""PROP_ETYPE 1 IEEE -PROP_FORMAT 1 RAW -PROP_ESIZE 1 {prop_esize} -PROP_OFFSET 1 0 -PROP_FILE 1 {data_filename} -END\n""" - ) - except OSError as exc: - logger.warning(f"Cannot export volume to GOCAD VOXET file {vo_filename}: {exc}") - return False - - # Write out accompanying binary data file - export_vals = np.array(vol_vals, dtype=d_type) - try: - with open(data_filename, "wb") as fp: - export_vals.tofile(fp) - except OSError as exc: - logger.warning(f"Cannot export volume to GOCAD VOXET data file {data_filename}: {exc}") - return False - return True diff --git a/LoopStructural/export/gocad.py b/LoopStructural/export/gocad.py index e7dfba3a0..5987456ec 100644 --- a/LoopStructural/export/gocad.py +++ b/LoopStructural/export/gocad.py @@ -235,35 +235,3 @@ def _write_feat_surfs_gocad(surf, file_name): fd.write(f"TRGL {v_map[face[0]]} {v_map[face[1]]} {v_map[face[2]]} \n") fd.write("END\n") return True - - -# def _write_pointset(points, file_name): -# """ -# Write out a GOCAD VS file for a pointset - -# Parameters -# ---------- -# points: SimpleNamespace() -# Details of the points, as a SimpleNamespace() object. Fields are: -# locations: locations, numpy ndarray with dtype = float64 & shape = (N,3) -# vectors: vectors, numpy ndarray with dtype = float64 & shape = (N,3) -# name: name of feature e.g. fault or supergroup, string - -# file_name: string -# Desired filename - -# Returns -# ------- -# True if successful - -# """ -# file_name = Path(file_name).with_suffix(".vs") -# with open(f"{file_name}", "w") as fd: -# fd.write( -# f"""GOCAD VSet 1 -# HEADER {{ -# name: {points.name} -# }} -# GOCAD_ORIGINAL_COORDINATE_SYSTEM -# NAME Default -# PROJECTION Unknown \ No newline at end of file diff --git a/LoopStructural/interpolators/_builders.py b/LoopStructural/interpolators/_builders.py deleted file mode 100644 index 8bf9734da..000000000 --- a/LoopStructural/interpolators/_builders.py +++ /dev/null @@ -1,149 +0,0 @@ -# from LoopStructural.utils.exceptions import LoopException -# import numpy as np -# from typing import Optional -# from LoopStructural.interpolators import ( -# P1Interpolator, -# P2Interpolator, -# FiniteDifferenceInterpolator, -# GeologicalInterpolator, -# DiscreteFoldInterpolator, -# StructuredGrid, -# TetMesh, -# ) -# from LoopStructural.geometry import BoundingBox -# from LoopStructural.utils.logging import getLogger - -# logger = getLogger(__name__) - - -# def get_interpolator( -# bounding_box: BoundingBox, -# interpolatortype: str, -# nelements: int, -# element_volume: Optional[float] = None, -# buffer: float = 0.2, -# dimensions: int = 3, -# support=None, -# ) -> GeologicalInterpolator: -# # add a buffer to the interpolation domain, this is necessary for -# # faults but also generally a good -# # idea to avoid boundary problems -# # buffer = bb[1, :] -# origin = bounding_box.with_buffer(buffer).origin -# maximum = bounding_box.with_buffer(buffer).maximum -# box_vol = np.prod(maximum - origin) -# if interpolatortype == "PLI": -# if support is None: -# if element_volume is None: -# # nelements /= 5 -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # step_vector /= np.array([1,1,2]) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# if np.any(np.less(nsteps, 3)): -# axis_labels = ["x", "y", "z"] -# for i in range(3): -# if nsteps[i] < 3: -# nsteps[i] = 3 -# logger.error( -# f"Number of steps in direction {axis_labels[i]} is too small, try increasing nelements" -# ) -# logger.error("Cannot create interpolator: number of steps is too small") -# raise ValueError("Number of steps too small cannot create interpolator") - -# support = TetMesh(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# "Creating regular tetrahedron mesh with %i elements \n" -# "for modelling using PLI" % (support.ntetra) -# ) - -# return P1Interpolator(support) -# if interpolatortype == "P2": -# if support is not None: -# logger.info( -# "Creating regular tetrahedron mesh with %i elements \n" -# "for modelling using P2" % (support.ntetra) -# ) -# return P2Interpolator(support) -# else: -# raise ValueError("Cannot create P2 interpolator without support, try using PLI") - -# if interpolatortype == "FDI": -# # find the volume of one element -# if element_volume is None: -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# if np.any(np.less(nsteps, 3)): -# logger.error("Cannot create interpolator: number of steps is too small") -# axis_labels = ["x", "y", "z"] -# for i in range(3): -# if nsteps[i] < 3: -# nsteps[i] = 3 -# # logger.error( -# # f"Number of steps in direction {axis_labels[i]} is too small, try increasing nelements" -# # ) -# # raise ValueError("Number of steps too small cannot create interpolator") -# # create a structured grid using the origin and number of steps - -# grid = StructuredGrid(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# f"Creating regular grid with {grid.n_elements} elements \n" "for modelling using FDI" -# ) -# return FiniteDifferenceInterpolator(grid) -# if interpolatortype == "DFI": -# if element_volume is None: -# nelements /= 5 -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# # create a structured grid using the origin and number of steps - -# mesh = TetMesh(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# f"Creating regular tetrahedron mesh with {mesh.ntetra} elements \n" -# "for modelling using DFI" -# ) -# return DiscreteFoldInterpolator(mesh, None) -# raise LoopException("No interpolator") -# # fi interpolatortype == "DFI" and dfi is True: -# # if element_volume is None: -# # nelements /= 5 -# # element_volume = box_vol / nelements -# # # calculate the step vector of a regular cube -# # step_vector = np.zeros(3) -# # step_vector[:] = element_volume ** (1.0 / 3.0) -# # # number of steps is the length of the box / step vector -# # nsteps = np.ceil((bb[1, :] - bb[0, :]) / step_vector).astype(int) -# # # create a structured grid using the origin and number of steps -# # if "meshbuilder" in kwargs: -# # mesh = kwargs["meshbuilder"].build(bb, nelements) -# # else: -# # mesh = kwargs.get( -# # "mesh", -# # TetMesh(origin=bb[0, :], nsteps=nsteps, step_vector=step_vector), -# # ) -# # logger.info( -# # f"Creating regular tetrahedron mesh with {mesh.ntetra} elements \n" -# # "for modelling using DFI" -# # ) -# # return DFI(mesh, kwargs["fold"]) -# # if interpolatortype == "Surfe" or interpolatortype == "surfe": -# # # move import of surfe to where we actually try and use it -# # if not surfe: -# # logger.warning("Cannot import Surfe, try another interpolator") -# # raise ImportError("Cannot import surfepy, try pip install surfe") -# # method = kwargs.get("method", "single_surface") -# # logger.info("Using surfe interpolator") -# # return SurfeRBFInterpolator(method) -# # logger.warning("No interpolator") -# # raise InterpolatorError("Could not create interpolator") diff --git a/LoopStructural/interpolators/_constant_norm.py b/LoopStructural/interpolators/_constant_norm.py deleted file mode 100644 index f1bbcd2bf..000000000 --- a/LoopStructural/interpolators/_constant_norm.py +++ /dev/null @@ -1,241 +0,0 @@ -from __future__ import annotations - -from typing import Callable - -import numpy as np -from loop_interpolation import DiscreteInterpolator, FiniteDifferenceInterpolator, P1Interpolator -from scipy import sparse - -from LoopStructural.utils import getLogger, rng - -logger = getLogger(__name__) - - -class ConstantNormInterpolator: - """Adds a non linear constraint to an interpolator to constrain - the norm of the gradient to be a set value. - - Returns - ------- - ConstantNormInterpolator - an interpolator mixin that iteratively re-weights a unit gradient norm constraint - into the least squares system of the wrapped discrete interpolator - """ - - def __init__(self, interpolator: DiscreteInterpolator, basetype): - """Initialise the constant norm inteprolator - with a discrete interpolator. - - Parameters - ---------- - interpolator : DiscreteInterpolator - The discrete interpolator to add constant norm to. - """ - self.basetype = basetype - self.interpolator = interpolator - self.support = interpolator.support - self.random_subset = False - self.norm_length = 1.0 - self.n_iterations = 20 - self.store_solution_history = False - self.solution_history = [] # np.zeros((self.n_iterations, self.support.n_nodes)) - self.gradient_constraint_store = [] - - def add_constant_norm(self, w: float): - """Add a constraint to the interpolator to constrain the norm of the gradient - to be a set value - - Parameters - ---------- - w : float - weighting of the constraint - """ - if "constant norm" in self.interpolator.constraints: - _ = self.interpolator.constraints.pop("constant norm") - - element_indices = np.arange(self.support.elements.shape[0]) - if self.random_subset: - rng.shuffle(element_indices) - element_indices = element_indices[: int(0.1 * self.support.elements.shape[0])] - _vertices, gradient, elements, _inside = self.support.get_element_gradient_for_location( - self.support.barycentre[element_indices] - ) - - t_g = gradient[:, :, :] - # t_n = gradient[self.support.shared_element_relationships[:, 1], :, :] - v_t = np.einsum( - "ijk,ik->ij", - t_g, - self.interpolator.c[self.support.elements[elements]], - ) - - norm = np.linalg.norm(v_t, axis=1) - valid = norm > 0 - if not np.all(valid): - logger.warning( - f"Skipping {np.sum(~valid)} elements with zero gradient norm " - "when adding constant norm constraint" - ) - t_g = t_g[valid] - v_t = v_t[valid] / norm[valid, np.newaxis] - elements = elements[valid] - element_indices = element_indices[valid] - self.gradient_constraint_store.append( - np.hstack([self.support.barycentre[element_indices], v_t]) - ) - A1 = np.einsum("ij,ijk->ik", v_t, t_g) - volume = self.support.element_size[element_indices] - A1 = A1 / volume[:, np.newaxis] # normalise by element size - - b = np.zeros(A1.shape[0]) + self.norm_length - b = b / volume # normalise by element size - idc = np.hstack( - [ - self.support.elements[elements], - ] - ) - self.interpolator.add_constraints_to_least_squares(A1, b, idc, w=w, name="constant norm") - - def solve_system( - self, - solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None = None, - tol: float | None = None, - solver_kwargs: dict | None = None, - ) -> bool: - """Solve the system of equations iteratively for the constant norm interpolator. - - Parameters - ---------- - solver : Optional[Union[Callable[[sparse.csr_matrix, np.ndarray], np.ndarray], str]], optional - Solver function or name, by default None - tol : Optional[float], optional - Tolerance for the solver, by default None - solver_kwargs : dict, optional - Additional arguments for the solver, by default {} - - Returns - ------- - bool - Success status of the solver - """ - if solver_kwargs is None: - solver_kwargs = {} - success = True - for i in range(self.n_iterations): - if i > 0: - self.add_constant_norm(w=(0.1 * i) ** 2 + 0.01) - # Ensure the interpolator is cast to P1Interpolator before calling solve_system - if isinstance(self.interpolator, self.basetype): - success = self.basetype.solve_system( - self.interpolator, solver=solver, tol=tol, solver_kwargs=solver_kwargs - ) - if self.store_solution_history: - - self.solution_history.append(self.interpolator.c) - else: - raise TypeError("self.interpolator is not an instance of P1Interpolator") - if not success: - break - return success - - -class ConstantNormP1Interpolator(P1Interpolator, ConstantNormInterpolator): - """Constant norm interpolator using P1 base interpolator - - Parameters - ---------- - P1Interpolator : class - The P1Interpolator class. - ConstantNormInterpolator : class - The ConstantNormInterpolator class. - """ - - def __init__(self, support): - """Initialise the constant norm P1 interpolator. - - Parameters - ---------- - support : support object - the mesh/support object that the base interpolator is built on - """ - P1Interpolator.__init__(self, support) - ConstantNormInterpolator.__init__(self, self, P1Interpolator) - - def solve_system( - self, - solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None = None, - tol: float | None = None, - solver_kwargs: dict | None = None, - ) -> bool: - """Solve the system of equations for the constant norm P1 interpolator. - - Parameters - ---------- - solver : Optional[Union[Callable[[sparse.csr_matrix, np.ndarray], np.ndarray], str]], optional - Solver function or name, by default None - tol : Optional[float], optional - Tolerance for the solver, by default None - solver_kwargs : dict, optional - Additional arguments for the solver, by default {} - - Returns - ------- - bool - Success status of the solver - """ - if solver_kwargs is None: - solver_kwargs = {} - return ConstantNormInterpolator.solve_system( - self, solver=solver, tol=tol, solver_kwargs=solver_kwargs - ) - - -class ConstantNormFDIInterpolator(FiniteDifferenceInterpolator, ConstantNormInterpolator): - """Constant norm interpolator using finite difference base interpolator - - Parameters - ---------- - FiniteDifferenceInterpolator : class - The FiniteDifferenceInterpolator class. - ConstantNormInterpolator : class - The ConstantNormInterpolator class. - """ - - def __init__(self, support): - """Initialise the constant norm finite difference interpolator. - - Parameters - ---------- - support : support object - the mesh/support object that the base interpolator is built on - """ - FiniteDifferenceInterpolator.__init__(self, support) - ConstantNormInterpolator.__init__(self, self, FiniteDifferenceInterpolator) - - def solve_system( - self, - solver: Callable[[sparse.csr_matrix, np.ndarray], np.ndarray] | str | None = None, - tol: float | None = None, - solver_kwargs: dict | None = None, - ) -> bool: - """Solve the system of equations for the constant norm finite difference interpolator. - - Parameters - ---------- - solver : Optional[Union[Callable[[sparse.csr_matrix, np.ndarray], np.ndarray], str]], optional - Solver function or name, by default None - tol : Optional[float], optional - Tolerance for the solver, by default None - solver_kwargs : dict, optional - Additional arguments for the solver, by default {} - - Returns - ------- - bool - Success status of the solver - """ - if solver_kwargs is None: - solver_kwargs = {} - return ConstantNormInterpolator.solve_system( - self, solver=solver, tol=tol, solver_kwargs=solver_kwargs - ) diff --git a/LoopStructural/interpolators/_discrete_fold_interpolator.py b/LoopStructural/interpolators/_discrete_fold_interpolator.py deleted file mode 100644 index cf7a4ca2b..000000000 --- a/LoopStructural/interpolators/_discrete_fold_interpolator.py +++ /dev/null @@ -1,192 +0,0 @@ -""" -Piecewise linear interpolator using folds -""" -from __future__ import annotations - -from typing import Callable - -import numpy as np - -from ..interpolators import InterpolatorType, PiecewiseLinearInterpolator -from ..modelling.features.fold import FoldEvent -from ..utils import getLogger, rng - -logger = getLogger(__name__) - - -class DiscreteFoldInterpolator(PiecewiseLinearInterpolator): - """ """ - - def __init__(self, support, fold: FoldEvent | None = None): - """ - A piecewise linear interpolator that can also use fold constraints defined in Laurent et al., 2016 - - Parameters - ---------- - support - discrete support with nodes and elements etc - fold FoldEvent - a fold event with a valid geometry - """ - - PiecewiseLinearInterpolator.__init__(self, support) - self.type = InterpolatorType.DISCRETE_FOLD - self.fold = fold - - def update_fold(self, fold): - """ - - Parameters - ---------- - fold : FoldEvent - a fold that contrains the geometry we are trying to add - - Returns - ------- - - """ - logger.error("updating fold, this should be done by accessing the fold attribute") - self.fold = fold - - def setup_interpolator(self, **kwargs): - if self.fold is None: - raise ValueError("No fold event specified") - fold_weights = kwargs.get("fold_weights", {}) - super().setup_interpolator(**kwargs) - self.add_fold_constraints(**fold_weights) - - - def add_fold_constraints( - self, - fold_orientation=10.0, - fold_axis_w=10.0, - fold_regularisation=None, - fold_normalisation=1.0, - fold_norm=1.0, - step=2, - mask_fn: Callable | None = None, - ): - """ - - Parameters - ---------- - fold_orientation : double - weight for the fold direction/orientation in the least squares system - fold_axis_w : double - weight for the fold axis in the least squares system - fold_regularisation : list - weight for the fold regularisation in the least squares system - fold_normalisation : double - weight for the fold norm constraint in the least squares system - fold_norm - length of the interpolation norm in the least squares system - step: int - array step for adding constraints - - - Returns - ------- - - Notes - ----- - For more information about the fold weights see EPSL paper by Gautier Laurent 2016 - - """ - if fold_regularisation is None: - fold_regularisation = [0.1, 0.01, 0.01] - # get the gradient of all of the elements of the mesh - eg = self.support.get_element_gradients(np.arange(self.support.n_elements)) - # get array of all nodes for all elements N,4,3 - nodes = self.support.nodes[self.support.get_elements()[np.arange(self.support.n_elements)]] - # calculate the fold geometry for the elements barycentre - deformed_orientation, fold_axis, dgz = self.fold.get_deformed_orientation( - self.support.barycentre - ) - element_idx = np.arange(self.support.n_elements) - rng.shuffle(element_idx) - # calculate element volume for weighting - vecs = nodes[:, 1:, :] - nodes[:, 0, None, :] - vol = np.abs(np.linalg.det(vecs)) / 6 - weight = np.ones(self.support.n_elements, dtype=float) - if mask_fn is not None: - weight[mask_fn(self.support.barycentre)] = 0 - weight = weight[::step] - if fold_orientation is not None: - """ - dot product between vector in deformed ori plane = 0 - """ - rng.shuffle(element_idx) - - logger.info(f"Adding fold orientation constraint to w = {fold_orientation}") - A = np.einsum( - "ij,ijk->ik", - deformed_orientation[element_idx[::step], :], - eg[element_idx[::step], :, :], - ) - A *= vol[element_idx[::step], None] - B = np.zeros(A.shape[0]) - idc = self.support.get_elements()[element_idx[::step], :] - self.add_constraints_to_least_squares( - A, B, idc, w=weight * fold_orientation, name="fold orientation" - ) - - if fold_axis_w is not None: - """ - dot product between axis and gradient should be 0 - """ - rng.shuffle(element_idx) - - logger.info(f"Adding fold axis constraint to w = {fold_axis_w}") - A = np.einsum( - "ij,ijk->ik", - fold_axis[element_idx[::step], :], - eg[element_idx[::step], :, :], - ) - A *= vol[element_idx[::step], None] - B = np.zeros(A.shape[0]).tolist() - idc = self.support.get_elements()[element_idx[::step], :] - - self.add_constraints_to_least_squares( - A, B, idc, w=weight * fold_axis_w, name="fold axis" - ) - - if fold_normalisation is not None: - """ - specify scalar norm in X direction - """ - rng.shuffle(element_idx) - - logger.info(f"Adding fold normalisation constraint to w = {fold_normalisation}") - A = np.einsum("ij,ijk->ik", dgz[element_idx[::step], :], eg[element_idx[::step], :, :]) - A *= vol[element_idx[::step], None] - - B = np.ones(A.shape[0]) - - if fold_norm is not None: - B[:] = fold_norm - B *= fold_normalisation - B *= vol[element_idx[::step]] - idc = self.support.get_elements()[element_idx[::step], :] - - self.add_constraints_to_least_squares( - A, B, idc, w=weight * fold_normalisation, name="fold normalisation" - ) - - if fold_regularisation is not None: - """ - fold constant gradient - """ - logger.info( - f"Adding fold regularisation constraint to w = {fold_regularisation[0]} {fold_regularisation[1]} {fold_regularisation[2]}" - ) - self.minimise_edge_jumps( - w=fold_regularisation[0], vector=dgz, name="fold regularisation 1" - ) - self.minimise_edge_jumps( - w=fold_regularisation[1], - vector=deformed_orientation, - name="fold regularisation 2", - ) - self.minimise_edge_jumps( - w=fold_regularisation[2], vector=fold_axis, name="fold regularisation 3" - ) diff --git a/LoopStructural/interpolators/_interpolatortype.py b/LoopStructural/interpolators/_interpolatortype.py deleted file mode 100644 index eaf995ba5..000000000 --- a/LoopStructural/interpolators/_interpolatortype.py +++ /dev/null @@ -1,23 +0,0 @@ -from enum import Enum - - -class InterpolatorType(Enum): - """ - Enum for the different interpolator types - - Each value is a unique identifier. - """ - - BASE = "BASE" - BASE_DISCRETE = "BASE_DISCRETE" - FINITE_DIFFERENCE = "FINITE_DIFFERENCE" - DISCRETE_FOLD = "DISCRETE_FOLD" - PIECEWISE_LINEAR = "PIECEWISE_LINEAR" - PIECEWISE_QUADRATIC = "PIECEWISE_QUADRATIC" - BASE_DATA_SUPPORTED = "BASE_DATA_SUPPORTED" - SURFE = "SURFE" - PIECEWISE_LINEAR_CONSTANT_NORM = "PIECEWISE_LINEAR_CONSTANT_NORM" - FINITE_DIFFERENCE_CONSTANT_NORM = "FINITE_DIFFERENCE_CONSTANT_NORM" - - - diff --git a/LoopStructural/modelling/core/geological_model.py b/LoopStructural/modelling/core/geological_model.py index c67b5bdb0..bda466ddf 100644 --- a/LoopStructural/modelling/core/geological_model.py +++ b/LoopStructural/modelling/core/geological_model.py @@ -1442,11 +1442,7 @@ def evaluate_feature_gradient(self, feature_name, xyz, scale=True): """ # `scale` is retained for API-signature compatibility only -- see # evaluate_model. - feature = self.get_feature_by_name(feature_name) - if feature: - return feature.evaluate_gradient(xyz) - else: - return np.zeros(xyz.shape[0]) + return self.get_feature_by_name(feature_name).evaluate_gradient(xyz) @public_api(tier="provisional") def evaluate_feature_block_value( diff --git a/LoopStructural/modelling/features/_lambda_geological_feature.py b/LoopStructural/modelling/features/_lambda_geological_feature.py index cc76fd789..70932db3b 100644 --- a/LoopStructural/modelling/features/_lambda_geological_feature.py +++ b/LoopStructural/modelling/features/_lambda_geological_feature.py @@ -80,28 +80,9 @@ def evaluate_value(self, pos: np.ndarray, ignore_regions=False) -> np.ndarray: np.ndarray value of the feature at each location, nan where outside of the regions """ - v = np.zeros(pos.shape[0]) - v[:] = np.nan - - # Precompute each fault's scalar value (gx = fault.__getitem__(0).evaluate_value) - # once and reuse for both the region mask check and fault application. - # FaultSegment.evaluate_value(pos) == self.__getitem__(0).evaluate_value(pos) == gx. - # apply_to_points also needs gx to determine the displacement mask — passing it - # avoids the duplicate evaluation on the np.copy of pos. - precomputed_gx = {id(f): f.evaluate_value(pos) for f in self.faults} - - # Region mask: pass precomputed gx so PositiveRegion/NegativeRegion skip re-evaluation - mask = np.ones(pos.shape[0], dtype=bool) - if not ignore_regions: - for r in self.regions: - pre = precomputed_gx.get(id(getattr(r, 'feature', None))) - mask = np.logical_and(mask, r(pos, precomputed_val=pre)) - - # Apply faults: pass precomputed gx so apply_to_points skips one evaluate_value call - if self.faults_enabled: - for f in self.faults: - pos = f.apply_to_points(pos, precomputed_gx=precomputed_gx.get(id(f))) - + v = np.full(pos.shape[0], np.nan) + mask = self._calculate_mask(pos, ignore_regions=ignore_regions) + pos = self._apply_faults(pos) if self.function is not None: v[mask] = self.function(pos[mask, :]) return v @@ -141,7 +122,6 @@ def evaluate_gradient( except ValueError: logger.error("element_scale_parameter must be a float") element_scale_parameter = 1 - v = np.zeros((pos.shape[0], 3)) v = np.zeros(pos.shape) v[:] = np.nan mask = self._calculate_mask(pos, ignore_regions=ignore_regions) @@ -151,26 +131,8 @@ def evaluate_gradient( # generate a regular tetrahedron for each point # we will then move these points by the fault and then recalculate the gradient. # this should work... - resolved = False tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter) - while resolved: - for f in self.faults: - v = ( - f[0] - .evaluate_value(tetrahedron.reshape(-1, 3), fillnan='nearest') - .reshape(tetrahedron.shape[0], 4) - ) - flag = np.logical_or(np.all(v > 0, axis=1), np.all(v < 0, axis=1)) - if np.any(~flag): - logger.warning( - f"Points are too close to fault {f[0].name}. Refining the tetrahedron" - ) - element_scale_parameter *= 0.5 - tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter) - - resolved = True - tetrahedron_faulted = self._apply_faults(np.array(tetrahedron.reshape(-1, 3))).reshape( tetrahedron.shape ) diff --git a/LoopStructural/modelling/features/builders/__init__.py b/LoopStructural/modelling/features/builders/__init__.py index b218b08ea..d524ccdd8 100644 --- a/LoopStructural/modelling/features/builders/__init__.py +++ b/LoopStructural/modelling/features/builders/__init__.py @@ -1,4 +1,3 @@ -from ._analytical_fold_builder import AnalyticalFoldBuilder from ._base_builder import BaseBuilder from ._fault_builder import FaultBuilder from ._folded_feature_builder import FoldedFeatureBuilder diff --git a/LoopStructural/modelling/features/builders/_analytical_fold_builder.py b/LoopStructural/modelling/features/builders/_analytical_fold_builder.py deleted file mode 100644 index e6f2647c0..000000000 --- a/LoopStructural/modelling/features/builders/_analytical_fold_builder.py +++ /dev/null @@ -1,41 +0,0 @@ -import numpy as np - -from .._lambda_geological_feature import LambdaGeologicalFeature -from ._base_builder import BaseBuilder - - -class AnalyticalFoldBuilder(BaseBuilder): - def __init__(self, model, name: str = 'Feature'): - super().__init__(model=model, name=name) - self._wavelength = np.max(model.bounding_box.length) - self._amplitude = np.min(model.bounding_box.length) - self._centre = model.bounding_box - self._feature = LambdaGeologicalFeature( - function=self._function, model=self.model, name=self.name, builder=self - ) - - @property - def amplitude(self): - return self._amplitude - - @property - def wavelength(self): - return self._wavelength - - def _function(self, xyz): - return xyz[:, 2] + np.sin(xyz[:, 0] / self.wavelength) * self.amplitude - - def build(self, **kwargs): - # the feature object identity is kept stable across rebuilds -- - # only its underlying function needs refreshing here. - self._feature.function = self._function - self._up_to_date = True - - def up_to_date(self, callback=None): - if not self._up_to_date: - self.update() - if callable(callback): - callback(1) - return - if callable(callback): - callback(1) diff --git a/LoopStructural/modelling/features/fault/_fault_function.py b/LoopStructural/modelling/features/fault/_fault_function.py index 41895bb6e..e1595b959 100644 --- a/LoopStructural/modelling/features/fault/_fault_function.py +++ b/LoopStructural/modelling/features/fault/_fault_function.py @@ -24,10 +24,6 @@ class FaultProfileFunction(metaclass=ABCMeta): def __init__(self): self.lim = [-1, 1] - @abstractmethod - def to_dict(self) -> dict: - pass - @abstractmethod def __call__(self, v: np.ndarray) -> np.ndarray: pass @@ -174,51 +170,6 @@ def __call__(self, v): return eva - def to_dict(self) -> dict: - """Export the function to a dictionary - - - Returns - ------- - dict - Keys A, B, max_v, min_v, w, up_to_date used to create a new CubicFunction - """ - return { - "A": self.A, - "B": self.B, - "max_v": self.max_v, - "min_v": self.min_v, - "w": self.w.tolist(), - "value_points": self.value_points, - "gradient_points": self.gradient_points, - "up_to_date": self.up_to_date, - } - - @classmethod - def from_dict(cls, data: dict) -> CubicFunction: - """Create a fault profile function from a json dictionary - - Parameters - ---------- - data : dict - Dictionary containing A, B, max_v, min_v, w, up_to_date - - Returns - ------- - CubicFunction - An initialised function given the dictionary parameters - """ - instance = cls() - instance.A = data.get("A", []) - instance.B = data.get("B", []) - instance.max_v = data.get("max_v", 999999) - instance.min_v = data.get("min_v", 999999) - instance.w = np.array(data.get("w", [0, 0, 0, 0])) - instance.value_points = data.get("value_points", []) - instance.gradient_points = data.get("gradient_points", []) - instance.up_to_date = data.get("up_to_date", False) - return instance - class Composite(FaultProfileFunction): """ @@ -251,31 +202,6 @@ def __call__(self, v: np.ndarray) -> np.ndarray: r[v < 0] = self.negative(v[v < 0]) return r - def to_dict(self) -> dict: - return { - "positive": self.positive.to_dict(), - "negative": self.negative.to_dict(), - } - - @classmethod - def from_dict(cls, data: dict) -> Composite: - """Create a fault profile function from a json dictionary - - Parameters - ---------- - data : dict - Dictionary containing "positive" and "negative" keys, each a dictionary - of CubicFunction parameters - - Returns - ------- - Composite - An initialised composite function given the dictionary parameters - """ - positive = CubicFunction.from_dict(data["positive"]) - negative = CubicFunction.from_dict(data["negative"]) - return cls(positive, negative) - class Ones(FaultProfileFunction): """ @@ -300,13 +226,6 @@ def __call__(self, v: np.ndarray) -> np.ndarray: tip_ends = () - def to_dict(self) -> dict: - return {} - - @classmethod - def from_dict(cls, data: dict) -> Ones: - return cls() - class Zeros(FaultProfileFunction): """ @@ -331,13 +250,6 @@ def __call__(self, v: np.ndarray) -> np.ndarray: tip_ends = () - def to_dict(self) -> dict: - return {} - - @classmethod - def from_dict(cls, data: dict) -> Zeros: - return cls() - class FaultDisplacement: def __init__( @@ -411,20 +323,6 @@ def tip_ends(self) -> dict: """ return {1: _profile_tip_ends(self.gy), 2: _profile_tip_ends(self.gz)} - def to_dict(self) -> dict: - return { - "gx": self.gx.to_dict(), - "gy": self.gy.to_dict(), - "gz": self.gz.to_dict(), - } - - @classmethod - def from_dict(cls, data: dict) -> FaultDisplacement: - gx = CubicFunction.from_dict(data["gx"]) - gy = CubicFunction.from_dict(data["gy"]) - gz = CubicFunction.from_dict(data["gz"]) - return cls(gx=gx, gy=gy, gz=gz) - def plot(self, range=(-1, 1), axs: list | None = None): try: import matplotlib.pyplot as plt @@ -473,9 +371,9 @@ def _taylor(function, x: np.ndarray, side: int) -> np.ndarray: x0 = side * _fault_block.BLOCK_SIDE_EPSILON f0, f1, f2, f3, f4, f5 = (function(x0 + side * k * h) for k in range(6)) slope = side * (-25.0 * f0 + 48.0 * f1 - 36.0 * f2 + 16.0 * f3 - 3.0 * f4) / (12.0 * h) - curvature = ( - 45.0 * f0 - 154.0 * f1 + 214.0 * f2 - 156.0 * f3 + 61.0 * f4 - 10.0 * f5 - ) / (12.0 * h**2) + curvature = (45.0 * f0 - 154.0 * f1 + 214.0 * f2 - 156.0 * f3 + 61.0 * f4 - 10.0 * f5) / ( + 12.0 * h**2 + ) return f0 + slope * (x - x0) + 0.5 * curvature * (x - x0) ** 2 diff --git a/LoopStructural/modelling/features/fault/_fault_function_feature.py b/LoopStructural/modelling/features/fault/_fault_function_feature.py index 0cc41b4c6..547f1aa7c 100644 --- a/LoopStructural/modelling/features/fault/_fault_function_feature.py +++ b/LoopStructural/modelling/features/fault/_fault_function_feature.py @@ -108,29 +108,6 @@ def evaluate_gradient(self, location): d = self.displacement(fault_suface, fault_displacement, fault_strike) return d - def evaluate_on_surface(self, location): - """Evaluate displacement specifically on the fault surface. - - Parameters - ---------- - location : np.ndarray - Array of xyz coordinates on the fault surface - - Returns - ------- - np.ndarray - Fault displacement values on the surface - - Notes - ----- - This method evaluates displacement only considering the fault displacement - and strike components, not the fault surface component. - """ - fault_displacement = self.fault_frame.features[1].evaluate_value(location) - fault_strike = self.fault_frame.features[2].evaluate_value(location) - d = self.displacement.evaluate(fault_displacement, fault_strike) - return d - def get_data(self, value_map: dict | None = None): """Get data associated with this fault displacement feature. diff --git a/LoopStructural/modelling/features/fault/_fault_segment.py b/LoopStructural/modelling/features/fault/_fault_segment.py index e3b1453ca..0e67c7554 100644 --- a/LoopStructural/modelling/features/fault/_fault_segment.py +++ b/LoopStructural/modelling/features/fault/_fault_segment.py @@ -250,9 +250,6 @@ def evaluate_value(self, locations, ignore_regions=False, *, block=None): ) return force_side(v, block_side(block, self.name)) - def ellipsoid(self): - pass - def mean(self): return self.__getitem__(0).mean() @@ -363,15 +360,10 @@ def _displacement_fraction(self, gx, gy, gz, block=None, offset=0.0): d = np.zeros(gx.shape) mask = np.logical_and(~np.isnan(forced), ~np.isnan(gy)) mask = np.logical_and(mask, ~np.isnan(gz)) - d[~mask] = 0 - gx_mask = np.zeros_like(mask, dtype=bool) - gx_mask[mask] = forced[mask] > 0 - d[gx_mask] = 1.0 - if self.faultfunction is not None: - d[mask] = block_displacement( - self.faultfunction, gx[mask] + offset, forced[mask] + offset, gy[mask], gz[mask], - side, - ) + d[mask] = block_displacement( + self.faultfunction, gx[mask] + offset, forced[mask] + offset, gy[mask], gz[mask], + side, + ) return d def evaluate_displacement(self, points, *, block=None): diff --git a/LoopStructural/utils/config.py b/LoopStructural/utils/config.py deleted file mode 100644 index d496927e9..000000000 --- a/LoopStructural/utils/config.py +++ /dev/null @@ -1,18 +0,0 @@ -class LoopStructuralConfig: - """ - Class to store configuration settings. - """ - - __splay_fault_threshold = 30 - __experimental = False - __default_interpolator = "FDI" - __default_nelements = 1e4 - __default_solver = "cg" - - # @property - # def experimental(): - # return __experimental - - # @experimental.setter - # def experimental(self, value): - # __experimental = value diff --git a/LoopStructural/utils/features.py b/LoopStructural/utils/features.py deleted file mode 100644 index 0513b945a..000000000 --- a/LoopStructural/utils/features.py +++ /dev/null @@ -1,5 +0,0 @@ -from ..modelling.features import LambdaGeologicalFeature - -X = LambdaGeologicalFeature(lambda pos: pos[:, 0], name="x") -Y = LambdaGeologicalFeature(lambda pos: pos[:, 1], name="y") -Z = LambdaGeologicalFeature(lambda pos: pos[:, 2], name="z") diff --git a/LoopStructural/utils/helper.py b/LoopStructural/utils/helper.py index 39e251f23..32a338dac 100644 --- a/LoopStructural/utils/helper.py +++ b/LoopStructural/utils/helper.py @@ -1,6 +1,5 @@ import numpy as np import pandas as pd -from sklearn.decomposition import PCA from .logging import getLogger @@ -19,11 +18,6 @@ def get_data_bounding_box_map(xyz, buffer): ------- """ - # find the aligned coordinates box using pca - modelpca = PCA(n_components=3) - modelpca.fit(xyz) - # transform the data to this new coordinate then find extents - # transformed_xyz = modelpca.transform(xyz) minx = np.min(xyz[:, 0]) maxx = np.max(xyz[:, 0]) miny = np.min(xyz[:, 1]) @@ -67,11 +61,6 @@ def get_data_bounding_box(xyz, buffer): ------- """ - # find the aligned coordinates box using pca - modelpca = PCA(n_components=3) - modelpca.fit(xyz) - # transform the data to this new coordinate then find extents - # transformed_xyz = modelpca.transform(xyz) minx = np.min(xyz[:, 0]) maxx = np.max(xyz[:, 0]) miny = np.min(xyz[:, 1]) diff --git a/LoopStructural/utils/linalg.py b/LoopStructural/utils/linalg.py deleted file mode 100644 index 751bb4df5..000000000 --- a/LoopStructural/utils/linalg.py +++ /dev/null @@ -1,8 +0,0 @@ -import numpy as np - - -def normalise(v): - v = np.array(v) - - np.linalg.norm(v, axis=1) - return v / np.linalg.norm(v) diff --git a/LoopStructural/utils/maths.py b/LoopStructural/utils/maths.py index afc36e678..bb219b395 100644 --- a/LoopStructural/utils/maths.py +++ b/LoopStructural/utils/maths.py @@ -1,434 +1,33 @@ -import numbers - -import numpy as np - -from LoopStructural.utils.typing import NumericInput - - -def strikedip2vector(strike: NumericInput, dip: NumericInput) -> np.ndarray: - """Convert strike and dip to a vector - - Parameters - ---------- - strike : NumericInput - strike angle(s) in degrees, measured clockwise from North - dip : NumericInput - dip angle(s) in degrees, measured from the horizontal plane - - Returns - ------- - np.ndarray - nx3 array of unit vectors normal to the plane defined by strike and dip - """ - if isinstance(strike, numbers.Number): - strike = np.array([strike]) - else: - strike = np.array(strike) - if isinstance(dip, numbers.Number): - dip = np.array([dip]) - else: - dip = np.array(dip) - - vec = np.zeros((len(strike), 3)) - s_r = np.deg2rad(strike) - d_r = np.deg2rad(dip) - vec[:, 0] = np.sin(d_r) * np.cos(s_r) - vec[:, 1] = -np.sin(d_r) * np.sin(s_r) - vec[:, 2] = np.cos(d_r) - vec /= np.linalg.norm(vec, axis=1)[:, None] - return vec -def dipdipdirection2vector(dip_direction: NumericInput, dip: NumericInput, degrees: bool = True) -> np.ndarray: - """Convert dip direction and dip to a vector - - Parameters - ---------- - dip_direction : NumericInput - dip direction angle(s) in degrees, measured clockwise from North - dip : NumericInput - dip angle(s) in degrees, measured from the horizontal plane - degrees : bool, optional - whether the input angles are in degrees, by default True - - Returns - ------- - np.ndarray - nx3 array of unit vectors normal to the plane defined by dip direction and dip - """ - if isinstance(dip_direction, numbers.Number): - dip_direction = np.array([dip_direction]) - else: - dip_direction = np.array(dip_direction) - if isinstance(dip, numbers.Number): - dip = np.array([dip]) - else: - dip = np.array(dip) - if degrees: - dip_direction = np.deg2rad(dip_direction) - dip = np.deg2rad(dip) - vec = np.zeros((len(dip_direction), 3)) - vec[:, 0] = np.sin(dip) * np.sin(dip_direction) - vec[:, 1] = np.sin(dip) * np.cos(dip_direction) - vec[:, 2] = np.cos(dip) - vec /= np.linalg.norm(vec, axis=1)[:, None] - return vec - -def azimuthplunge2vector( - plunge: NumericInput, - azimuth: NumericInput, - degrees: bool = True, -) -> np.ndarray: - raise DeprecationWarning( - "azimuthplunge2vector is deprecated, use plungeazimuth2vector instead" - ) - -def plungeazimuth2vector( - plunge: NumericInput, - azimuth: NumericInput, - degrees: bool = True, -) -> np.ndarray: - """Convert plunge and plunge direction to a vector - - Parameters - ---------- - azimuth : Union[np.ndarray, list] - array or array like of plunge direction values - plunge : Union[np.ndarray, list] - array or array like of plunge values - - Returns - ------- - np.array - nx3 vector - """ - if isinstance(plunge, numbers.Number): - plunge = np.array([plunge], dtype=float) - else: - plunge = np.array(plunge, dtype=float) - if isinstance(azimuth, numbers.Number): - azimuth = np.array([azimuth], dtype=float) - else: - azimuth = np.array(azimuth, dtype=float) - if degrees: - plunge = np.deg2rad(plunge) - azimuth = np.deg2rad(azimuth) - vec = np.zeros((len(plunge), 3)) - vec[:, 0] = np.sin(azimuth) * np.cos(plunge) - vec[:, 1] = np.cos(azimuth) * np.cos(plunge) - vec[:, 2] = -np.sin(plunge) - return vec - - -def normal_vector_to_strike_and_dip( - normal_vector: NumericInput, degrees: bool = True -) -> np.ndarray: - """Convert from a normal vector to strike and dip - - Parameters - ---------- - normal_vector : np.ndarray, list - array of normal vectors - degrees : bool, optional - whether to return in degrees or radians, by default True - Returns - ------- - np.ndarray - 2xn array of strike and dip values - - Notes - ------ - - if a 1d array is passed in it is assumed to be a single normal vector - and cast into a 1x3 array - - """ - normal_vector = np.array(normal_vector) - if len(normal_vector.shape) == 1: - normal_vector = normal_vector[None, :] - # normalise the normal vector - normal_vector /= np.linalg.norm(normal_vector, axis=1)[:, None] - dip = np.arccos(normal_vector[:, 2]) - strike = -np.arctan2(normal_vector[:, 1], normal_vector[:, 0]) - if degrees: - dip = np.rad2deg(dip) - strike = np.rad2deg(strike) - - return np.array([strike, dip]).T - -def normal_vector_to_dip_and_dip_direction( - normal_vector: NumericInput, degrees: bool = True -) -> np.ndarray: - """Convert from a normal vector to dip and dip direction - - Parameters - ---------- - normal_vector : np.ndarray, list - array of normal vectors - degrees : bool, optional - whether to return in degrees or radians, by default True - Returns - ------- - np.ndarray - 2xn array of dip direction and dip values - - Notes - ------ - - if a 1d array is passed in it is assumed to be a single normal vector - and cast into a 1x3 array - - """ - normal_vector = np.array(normal_vector) - if len(normal_vector.shape) == 1: - normal_vector = normal_vector[None, :] - # normalise the normal vector - normal_vector /= np.linalg.norm(normal_vector, axis=1)[:, None] - dip = np.arccos(normal_vector[:, 2]) - dip_direction = np.arctan2(normal_vector[:, 0], normal_vector[:, 1]) - if degrees: - dip = np.rad2deg(dip) - dip_direction = np.rad2deg(dip_direction) - dip_direction = (dip_direction + 360) % 360 - - return np.array([dip_direction, dip]).T - -def rotation(axis: NumericInput, angle: NumericInput) -> np.ndarray: - """Create a rotation matrix for an axis and angle - - Parameters - ---------- - axis : Union[np.ndarray, list] - vector defining the axis of rotation - angle : Union[np.ndarray, list] - angle to rotate in degrees - - Returns - ------- - np.ndarray - 3x3 rotation matrix - """ - c = np.cos(np.deg2rad(angle)) - s = np.sin(np.deg2rad(angle)) - C = 1.0 - c - x = axis[:, 0] - y = axis[:, 1] - z = axis[:, 2] - xs = x * s - ys = y * s - zs = z * s - xC = x * C - yC = y * C - zC = z * C - xyC = x * yC - yzC = y * zC - zxC = z * xC - rotation_mat = np.zeros((axis.shape[0], 3, 3)) - rotation_mat[:, 0, 0] = x * xC + c - rotation_mat[:, 0, 1] = xyC - zs - rotation_mat[:, 0, 2] = zxC + ys - - rotation_mat[:, 1, 0] = xyC + zs - rotation_mat[:, 1, 1] = y * yC + c - rotation_mat[:, 1, 2] = yzC - xs - - rotation_mat[:, 2, 0] = zxC - ys - rotation_mat[:, 2, 1] = yzC + xs - rotation_mat[:, 2, 2] = z * zC + c - return rotation_mat - - -def rotate(vector: NumericInput, axis: NumericInput, angle: NumericInput) -> np.ndarray: - """Rotate a vector about an axis - - Parameters - ---------- - vector : Union[np.ndarray, list] - vector to rotate - alpha : Union[np.ndarray, list] - axis to rotate about - beta : Union[np.ndarray, list] - angle to rotate in degrees - - Returns - ------- - np.ndarray - rotated vector - """ - return np.einsum("ijk,ik->ij", rotation(axis, angle), vector) - # rotation_mat = rotation( - # np.tile(np.array([0, 0, 1])[None, :], (yaw.shape[0], 1)), yaw - # ) - # vector = np.einsum("ijk,ik->ij", rotation_mat, vector) - # rotation_mat = rotation( - # np.tile(np.array([0, 1, 0])[None, :], (pitch.shape[0], 1)), pitch - # ) - # vector = np.einsum("ijk,ik->ij", rotation_mat, vector) - - # return vector - - -def get_vectors(normal: NumericInput) -> tuple[np.ndarray, np.ndarray]: - """Find strike and dip vectors for a normal vector. - Makes assumption the strike vector is horizontal component and the dip is vertical. - Found by calculating strike and and dip angle and then finding the appropriate vectors - - Parameters - ---------- - normal : Union[np.ndarray, list] - input - - Returns - ------- - np.ndarray, np.ndarray - strike vector, dip vector - """ - length = np.linalg.norm(normal, axis=1)[:, None] - normal /= length # np.linalg.norm(normal,axis=1)[:,None] - strikedip = normal_vector_to_strike_and_dip(normal) - strike_vec = get_strike_vector(strikedip[:, 0]) - strike_vec /= np.linalg.norm(strike_vec, axis=0)[None, :] - dip_vec = np.cross(strike_vec, normal, axisa=0, axisb=1).T # (strikedip[:, 0], strikedip[:, 1]) - dip_vec /= np.linalg.norm(dip_vec, axis=0)[None, :] - return strike_vec * length.T, dip_vec * length.T - - -def get_strike_vector(strike: NumericInput, degrees: bool = True) -> np.ndarray: - """Return strike direction vector(s) from strike angle(s). - - Parameters - ---------- - strike : NumericInput - Single strike angle or array-like of strike angles, measured clockwise from North. - degrees : bool, optional - Whether the input angles are in degrees. If False, angles are assumed to be in radians. - Default is True. - - Returns - ------- - np.ndarray - Array of shape (3, n) where each column is a 3D unit vector (x, y, z) representing - the horizontal strike direction. The z-component is always 0. - - """ - if isinstance(strike, numbers.Number): - strike = np.array([strike]) - strike = np.array(strike) - if degrees: - strike = np.deg2rad(strike) - v = np.array( - [ - np.sin(-strike), - -np.cos(-strike), - np.zeros(strike.shape[0]), - ] - ) - - return v - - -def get_dip_vector(strike, dip): - """Return the dip vector based on strike and dip angles. - - Parameters - ---------- - strike : float - Strike angle in degrees, measured clockwise from North. - dip : float - Dip angle in degrees, measured from the horizontal plane. - - Returns - ------- - np.ndarray - Unit vector (length 3) representing the dip direction in 3D space. - - """ - v = np.array( - [ - -np.cos(np.deg2rad(-strike)) * np.cos(-np.deg2rad(dip)), - np.sin(np.deg2rad(-strike)) * np.cos(-np.deg2rad(dip)), - np.sin(-np.deg2rad(dip)), - ] - ) - return v - - -def regular_tetraherdron_for_points(xyz, scale_parameter): - """Generate regular tetrahedrons centered at given 3D points. - - Parameters - ---------- - xyz : np.ndarray - Array of shape (n, 3) representing the coordinates of n points in 3D space, - which will serve as the centers of the generated tetrahedrons. - scale_parameter : float - Scaling factor controlling the size of the regular tetrahedrons. - - Returns - ------- - np.ndarray - Array of shape (n, 4, 3) representing n regular tetrahedrons, where each - tetrahedron has 4 vertices in 3D space, positioned relative to the corresponding center point. - - """ - regular_tetrahedron = np.array( - [ - [np.sqrt(8 / 9), 0, -1 / 3], - [-np.sqrt(2 / 9), np.sqrt(2 / 3), -1 / 3], - [-np.sqrt(2 / 9), -np.sqrt(2 / 3), -1 / 3], - [0, 0, 1], - ] - ) - regular_tetrahedron *= scale_parameter - tetrahedron = np.zeros((xyz.shape[0], 4, 3)) - tetrahedron[:] = xyz[:, None, :] - tetrahedron[:, :, :] += regular_tetrahedron[None, :, :] - - return tetrahedron - - -def gradient_from_tetrahedron(tetrahedron, value): - """Compute the gradient of values within tetrahedral elements - - Parameters - ---------- - tetrahedron : np.ndarray - Array of shape (n, 4, 3) representing the coordinates of tetrahedral elements, - where each tetrahedron is defined by 4 vertices in 3D space. - value : np.ndarray - Array of shape (n, 4) representing the scalar values at the 4 vertices - of each tetrahedron. - - Returns - ------- - np.ndarray - Array of shape (n, 3) representing the gradient vector of the scalar field - inside each tetrahedral element. - - """ - tetrahedron = tetrahedron.reshape(-1, 4, 3) - m = np.array( - [ - [ - (tetrahedron[:, 1, 0] - tetrahedron[:, 0, 0]), - (tetrahedron[:, 1, 1] - tetrahedron[:, 0, 1]), - (tetrahedron[:, 1, 2] - tetrahedron[:, 0, 2]), - ], - [ - (tetrahedron[:, 2, 0] - tetrahedron[:, 0, 0]), - (tetrahedron[:, 2, 1] - tetrahedron[:, 0, 1]), - (tetrahedron[:, 2, 2] - tetrahedron[:, 0, 2]), - ], - [ - (tetrahedron[:, 3, 0] - tetrahedron[:, 0, 0]), - (tetrahedron[:, 3, 1] - tetrahedron[:, 0, 1]), - (tetrahedron[:, 3, 2] - tetrahedron[:, 0, 2]), - ], - ] - ) - I = np.array([[-1.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 1.0, 0.0], [-1.0, 0.0, 0.0, 1.0]]) - m = np.swapaxes(m, 0, 2) - element_gradients = np.linalg.inv(m) - - element_gradients = element_gradients.swapaxes(1, 2) - element_gradients = element_gradients @ I - v = np.sum(element_gradients * value[:, None, :], axis=2) - return v +"""Compatibility re-export: the vector maths helpers now live in loop_common.""" + +from loop_common.math._maths import ( + azimuthplunge2vector, + dipdipdirection2vector, + get_dip_vector, + get_strike_vector, + get_vectors, + gradient_from_tetrahedron, + normal_vector_to_dip_and_dip_direction, + normal_vector_to_strike_and_dip, + plungeazimuth2vector, + regular_tetraherdron_for_points, + rotate, + rotation, + strikedip2vector, +) + +__all__ = [ + "azimuthplunge2vector", + "dipdipdirection2vector", + "get_dip_vector", + "get_strike_vector", + "get_vectors", + "gradient_from_tetrahedron", + "normal_vector_to_dip_and_dip_direction", + "normal_vector_to_strike_and_dip", + "plungeazimuth2vector", + "regular_tetraherdron_for_points", + "rotate", + "rotation", + "strikedip2vector", +] diff --git a/packages/loop_common/src/loop_common/geometry/_point.py b/packages/loop_common/src/loop_common/geometry/_point.py index 0fd00f8ab..b7c9778bf 100644 --- a/packages/loop_common/src/loop_common/geometry/_point.py +++ b/packages/loop_common/src/loop_common/geometry/_point.py @@ -78,10 +78,6 @@ def save(self, filename: str | io.StringIO, *, group="Loop", ext=None): with open(filename, "wb") as f: pickle.dump(self, f) - elif ext == "vs": - from LoopStructural.export.gocad import _write_pointset - - _write_pointset(self, filename) elif ext == "csv": import pandas as pd @@ -215,10 +211,6 @@ def save(self, filename, *, group="Loop"): with open(filename, "wb") as f: pickle.dump(self, f) - elif ext == "vs": - from LoopStructural.export.gocad import _write_pointset - - _write_pointset(self, filename) elif ext == "csv": import pandas as pd diff --git a/packages/loop_common/src/loop_common/geometry/_surface.py b/packages/loop_common/src/loop_common/geometry/_surface.py index c6d8ec578..c89540037 100644 --- a/packages/loop_common/src/loop_common/geometry/_surface.py +++ b/packages/loop_common/src/loop_common/geometry/_surface.py @@ -259,7 +259,7 @@ def save(self, filename, *, group="Loop", replace_spaces=True, ext=None): point_data={"normals": self.normals}, ) elif ext == "ts" or ext == "gocad": - from LoopStructural.export.exporters import _write_feat_surfs_gocad + from LoopStructural.export.gocad import _write_feat_surfs_gocad _write_feat_surfs_gocad(self, filename) elif ext == "geoh5": diff --git a/packages/loop_common/src/loop_common/math/_maths.py b/packages/loop_common/src/loop_common/math/_maths.py index fd9d8b52a..6c59c267f 100644 --- a/packages/loop_common/src/loop_common/math/_maths.py +++ b/packages/loop_common/src/loop_common/math/_maths.py @@ -11,15 +11,15 @@ def strikedip2vector(strike: NumericInput, dip: NumericInput) -> np.ndarray: Parameters ---------- - strike : _type_ - _description_ - dip : _type_ - _description_ + strike : NumericInput + strike angle(s) in degrees, measured clockwise from North + dip : NumericInput + dip angle(s) in degrees, measured from the horizontal plane Returns ------- - _type_ - _description_ + np.ndarray + nx3 array of unit vectors normal to the plane defined by strike and dip """ if isinstance(strike, numbers.Number): strike = np.array([strike]) @@ -47,17 +47,17 @@ def dipdipdirection2vector( Parameters ---------- - dip_direction : _type_ - _description_ - dip : _type_ - _description_ + dip_direction : NumericInput + dip direction angle(s) in degrees, measured clockwise from North + dip : NumericInput + dip angle(s) in degrees, measured from the horizontal plane degrees : bool, optional - _description_, by default True + whether the input angles are in degrees, by default True Returns ------- - _type_ - _description_ + np.ndarray + nx3 array of unit vectors normal to the plane defined by dip direction and dip """ if isinstance(dip_direction, numbers.Number): dip_direction = np.array([dip_direction]) diff --git a/packages/loop_interpolation/src/loop_interpolation/_builders.py b/packages/loop_interpolation/src/loop_interpolation/_builders.py deleted file mode 100644 index a224c3f4f..000000000 --- a/packages/loop_interpolation/src/loop_interpolation/_builders.py +++ /dev/null @@ -1,149 +0,0 @@ -# from LoopStructural.utils.exceptions import LoopException -# import numpy as np -# from typing import Optional -# from LoopStructural.interpolators import ( -# P1Interpolator, -# P2Interpolator, -# FiniteDifferenceInterpolator, -# GeologicalInterpolator, -# DiscreteFoldInterpolator, -# StructuredGrid, -# TetMesh, -# ) -# from LoopStructural.datatypes import BoundingBox -# from LoopStructural.utils.logging import getLogger - -# logger = getLogger(__name__) - - -# def get_interpolator( -# bounding_box: BoundingBox, -# interpolatortype: str, -# nelements: int, -# element_volume: Optional[float] = None, -# buffer: float = 0.2, -# dimensions: int = 3, -# support=None, -# ) -> GeologicalInterpolator: -# # add a buffer to the interpolation domain, this is necessary for -# # faults but also generally a good -# # idea to avoid boundary problems -# # buffer = bb[1, :] -# origin = bounding_box.with_buffer(buffer).origin -# maximum = bounding_box.with_buffer(buffer).maximum -# box_vol = np.prod(maximum - origin) -# if interpolatortype == "PLI": -# if support is None: -# if element_volume is None: -# # nelements /= 5 -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # step_vector /= np.array([1,1,2]) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# if np.any(np.less(nsteps, 3)): -# axis_labels = ["x", "y", "z"] -# for i in range(3): -# if nsteps[i] < 3: -# nsteps[i] = 3 -# logger.error( -# f"Number of steps in direction {axis_labels[i]} is too small, try increasing nelements" -# ) -# logger.error("Cannot create interpolator: number of steps is too small") -# raise ValueError("Number of steps too small cannot create interpolator") - -# support = TetMesh(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# "Creating regular tetrahedron mesh with %i elements \n" -# "for modelling using PLI" % (support.ntetra) -# ) - -# return P1Interpolator(support) -# if interpolatortype == "P2": -# if support is not None: -# logger.info( -# "Creating regular tetrahedron mesh with %i elements \n" -# "for modelling using P2" % (support.ntetra) -# ) -# return P2Interpolator(support) -# else: -# raise ValueError("Cannot create P2 interpolator without support, try using PLI") - -# if interpolatortype == "FDI": -# # find the volume of one element -# if element_volume is None: -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# if np.any(np.less(nsteps, 3)): -# logger.error("Cannot create interpolator: number of steps is too small") -# axis_labels = ["x", "y", "z"] -# for i in range(3): -# if nsteps[i] < 3: -# nsteps[i] = 3 -# # logger.error( -# # f"Number of steps in direction {axis_labels[i]} is too small, try increasing nelements" -# # ) -# # raise ValueError("Number of steps too small cannot create interpolator") -# # create a structured grid using the origin and number of steps - -# grid = StructuredGrid(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# f"Creating regular grid with {grid.n_elements} elements \n" "for modelling using FDI" -# ) -# return FiniteDifferenceInterpolator(grid) -# if interpolatortype == "DFI": -# if element_volume is None: -# nelements /= 5 -# element_volume = box_vol / nelements -# # calculate the step vector of a regular cube -# step_vector = np.zeros(3) -# step_vector[:] = element_volume ** (1.0 / 3.0) -# # number of steps is the length of the box / step vector -# nsteps = np.ceil((maximum - origin) / step_vector).astype(int) -# # create a structured grid using the origin and number of steps - -# mesh = TetMesh(origin=origin, nsteps=nsteps, step_vector=step_vector) -# logger.info( -# f"Creating regular tetrahedron mesh with {mesh.ntetra} elements \n" -# "for modelling using DFI" -# ) -# return DiscreteFoldInterpolator(mesh, None) -# raise LoopException("No interpolator") -# # fi interpolatortype == "DFI" and dfi is True: -# # if element_volume is None: -# # nelements /= 5 -# # element_volume = box_vol / nelements -# # # calculate the step vector of a regular cube -# # step_vector = np.zeros(3) -# # step_vector[:] = element_volume ** (1.0 / 3.0) -# # # number of steps is the length of the box / step vector -# # nsteps = np.ceil((bb[1, :] - bb[0, :]) / step_vector).astype(int) -# # # create a structured grid using the origin and number of steps -# # if "meshbuilder" in kwargs: -# # mesh = kwargs["meshbuilder"].build(bb, nelements) -# # else: -# # mesh = kwargs.get( -# # "mesh", -# # TetMesh(origin=bb[0, :], nsteps=nsteps, step_vector=step_vector), -# # ) -# # logger.info( -# # f"Creating regular tetrahedron mesh with {mesh.ntetra} elements \n" -# # "for modelling using DFI" -# # ) -# # return DFI(mesh, kwargs["fold"]) -# # if interpolatortype == "Surfe" or interpolatortype == "surfe": -# # # move import of surfe to where we actually try and use it -# # if not surfe: -# # logger.warning("Cannot import Surfe, try another interpolator") -# # raise ImportError("Cannot import surfepy, try pip install surfe") -# # method = kwargs.get("method", "single_surface") -# # logger.info("Using surfe interpolator") -# # return SurfeRBFInterpolator(method) -# # logger.warning("No interpolator") -# # raise InterpolatorError("Could not create interpolator") diff --git a/packages/loop_interpolation/src/loop_interpolation/_validation.py b/packages/loop_interpolation/src/loop_interpolation/_validation.py index 7601606bb..3c7e62b1d 100644 --- a/packages/loop_interpolation/src/loop_interpolation/_validation.py +++ b/packages/loop_interpolation/src/loop_interpolation/_validation.py @@ -13,6 +13,7 @@ warning. This preserves backward-compatible behaviour where constraints that fall outside the model or contain missing values are ignored. """ + from __future__ import annotations import logging @@ -22,40 +23,11 @@ _logger = logging.getLogger(__name__) -def _fill_nan_weights(points: np.ndarray, weight_col: int) -> np.ndarray: - """Replace NaN values in the weight column with 1.0 (default weight). - - Parameters - ---------- - points : np.ndarray - Constraint array, already converted to float64. - weight_col : int - Column index of the weight column. - - Returns - ------- - np.ndarray - Array with NaN weights replaced; a copy is returned only if any - replacements were made. - """ - nan_mask = ~np.isfinite(points[:, weight_col]) - if np.any(nan_mask): - n_replaced = int(np.sum(nan_mask)) - _logger.warning( - "%d NaN weight value(s) replaced with 1.0 (default weight). " - "Provide explicit finite weights to suppress this warning.", - n_replaced, - ) - points = points.copy() - points[nan_mask, weight_col] = 1.0 - return points - - def _drop_nan_data_rows(points: np.ndarray, data_cols: slice, name: str) -> np.ndarray: """Drop rows that contain NaN or inf in the position / data columns. Weight columns are intentionally excluded from this check because NaN - weights are handled separately by :func:`_fill_nan_weights`. + weights are handled separately. Parameters ---------- @@ -89,37 +61,30 @@ class ValidationError(ValueError): """Base exception for constraint validation errors.""" - class ShapeError(ValidationError): """Exception for shape mismatches in constraint arrays.""" - class DtypeError(ValidationError): """Exception for data type mismatches in constraint arrays.""" - class FiniteValueError(ValidationError): """Exception for non-finite values in constraint arrays.""" - class VectorError(ValidationError): """Exception for invalid vector/direction constraints.""" - class WeightError(ValidationError): """Exception for invalid weight values.""" - class UnsupportedCombinationError(ValidationError): """Exception for unsupported constraint combinations.""" - def _ensure_float_array(arr: np.ndarray, name: str = "array") -> np.ndarray: """Convert array to float type with error handling. @@ -149,41 +114,6 @@ def _ensure_float_array(arr: np.ndarray, name: str = "array") -> np.ndarray: ) -def _check_shape( - arr: np.ndarray, - expected_shape: tuple[int | None, ...], - name: str = "array", -) -> None: - """Validate array shape matches expectations. - - Parameters - ---------- - arr : np.ndarray - Array to validate - expected_shape : tuple - Expected shape. Use None for variable dimensions. - name : str - Name of array for error messages - - Raises - ------ - ShapeError - If shape doesn't match expected shape - """ - if arr.ndim != len(expected_shape): - raise ShapeError( - f"{name} has {arr.ndim} dimensions, but {len(expected_shape)} expected. " - f"Expected shape: {expected_shape}, got {arr.shape}" - ) - - for i, (actual, expected) in enumerate(zip(arr.shape, expected_shape)): - if expected is not None and actual != expected: - raise ShapeError( - f"{name} dimension {i}: expected {expected}, got {actual}. " - f"Expected shape: {expected_shape}, got {arr.shape}" - ) - - def _check_finite(arr: np.ndarray, name: str = "array") -> None: """Validate all values in array are finite (not NaN or inf). @@ -210,359 +140,6 @@ def _check_finite(arr: np.ndarray, name: str = "array") -> None: ) -def _strip_injected_weight_column( - arr: np.ndarray, points: np.ndarray, no_weight_ncols: int -) -> np.ndarray: - """Undo the weight column that ``BaseConstraint.to_array()`` always - appends, when the caller's original input didn't include one. - - The constraint classes always carry an explicit weight column - internally (defaulting to 1.0) so downstream interpolator code has a - uniform layout. The standalone ``validate_*`` helpers instead promise a - round-trip of the caller's own column layout, so the injected column is - dropped again here when it wasn't present on input. - """ - pts = np.asarray(points) - if pts.ndim == 2 and pts.shape[1] == no_weight_ncols: - return arr[:, :no_weight_ncols] - return arr - - -def validate_value_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate value constraint input array. - - Value constraints specify scalar field values at points. - Expected format: [X, Y, Z, value] or [X, Y, Z, value, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype). Rows with NaN/inf in position or - value columns are silently dropped; NaN weights are replaced with 1.0. - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates or values are non-finite after NaN rows are dropped - """ - from .constraints import ValueConstraint - - arr = ValueConstraint.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions + 1) - - -def validate_gradient_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate gradient constraint input array. - - Gradient constraints specify field gradients at points. - Expected format: [X, Y, Z, gx, gy, gz] or [X, Y, Z, gx, gy, gz, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype). Rows with NaN/inf in position or - gradient columns are silently dropped; NaN weights are replaced with 1.0. - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates or gradient values are non-finite after NaN rows are dropped - VectorError - If gradient vectors have zero magnitude (degenerate case) - """ - from .constraints import GradientConstraint - - arr = GradientConstraint.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions * 2) - - -def validate_normal_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate normal constraint input array. - - Normal constraints specify surface normals at points. - Expected format: [X, Y, Z, nx, ny, nz] or [X, Y, Z, nx, ny, nz, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype). Rows with NaN/inf in position or - normal columns are silently dropped; NaN weights are replaced with 1.0. - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates or normals are non-finite after NaN rows are dropped - VectorError - If normal vectors have zero magnitude - """ - from .constraints import GradientConstraint - - arr = GradientConstraint.from_array(points, dimensions=dimensions, is_normal=True).to_array() - return _strip_injected_weight_column(arr, points, dimensions * 2) - - -def validate_tangent_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate tangent constraint input array. - - Tangent constraints specify tangent directions at points. - Expected format: [X, Y, Z, tx, ty, tz] or [X, Y, Z, tx, ty, tz, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype). Rows with NaN/inf in position or - tangent columns are silently dropped; NaN weights are replaced with 1.0. - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates or tangents are non-finite after NaN rows are dropped - VectorError - If tangent vectors have zero magnitude - """ - from .constraints import GradientConstraint - - arr = GradientConstraint.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions * 2) - - -def validate_interface_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate interface constraint input array. - - Interface constraints mark surface boundaries. - Expected format: [X, Y, Z, id] or [X, Y, Z, id, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype). Rows with NaN/inf in position or - id columns are silently dropped; NaN weights are replaced with 1.0. - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates are non-finite after NaN rows are dropped - """ - from .constraints import InterfaceConstraint - - arr = InterfaceConstraint.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions + 1) - - -def validate_inequality_value_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate inequality value constraint input array. - - Inequality constraints specify bounds on scalar field values. - Expected format: [X, Y, Z, lower_bound, upper_bound] or [X, Y, Z, lower_bound, upper_bound, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype) - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates or bounds are non-finite - ValueError - If lower bound >= upper bound for any constraint - """ - from .constraints import InequalityConstraint - - arr = InequalityConstraint.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions + 2) - - -def validate_inequality_pairs_constraint( - points: np.ndarray, - dimensions: int = 3, -) -> np.ndarray: - """Validate inequality pairs constraint input array. - - Inequality pairs enforce ordering between pairs of points. - Expected format: [X, Y, Z, rock_id] or [X, Y, Z, rock_id, weight] - - Parameters - ---------- - points : np.ndarray - Input point array to validate - dimensions : int - Number of spatial dimensions (default 3) - - Returns - ------- - np.ndarray - Validated array (float64 dtype) - - Raises - ------ - ShapeError - If points has wrong number of dimensions or columns - DtypeError - If points cannot be converted to float - FiniteValueError - If any coordinates are non-finite - """ - from .constraints import InequalityPair - - arr = InequalityPair.from_array(points, dimensions=dimensions).to_array() - return _strip_injected_weight_column(arr, points, dimensions + 1) - - -def validate_weights( - weights: float | np.ndarray, - n_constraints: int, - constraint_name: str = "constraint", -) -> float | np.ndarray: - """Validate weight values for constraints. - - Weights must be positive scalars or arrays. - - Parameters - ---------- - weights : float or np.ndarray - Weight value(s) to validate - n_constraints : int - Number of constraints (for array validation) - constraint_name : str - Name of constraint type for error messages - - Returns - ------- - float or np.ndarray - Validated weights - - Raises - ------ - DtypeError - If weights cannot be converted to float - FiniteValueError - If weights contain non-finite values - WeightError - If weights are non-positive or wrong shape - """ - if isinstance(weights, (int, float)): - if not np.isfinite(weights): - raise FiniteValueError( - f"{constraint_name} weight is non-finite. " - f"Weight must be a finite positive number. Got: {weights}" - ) - if weights <= 0: - raise WeightError(f"{constraint_name} weight must be positive. Got: {weights}") - return float(weights) - - weights_arr = _ensure_float_array(weights, f"{constraint_name} weights array") - - if weights_arr.ndim == 1: - if weights_arr.shape[0] != n_constraints: - raise ShapeError( - f"{constraint_name} weights array has {weights_arr.shape[0]} elements, " - f"but {n_constraints} constraints provided. " - f"Weight array length must match number of constraints." - ) - else: - raise ShapeError( - f"{constraint_name} weights array must be 1D. Got shape: {weights_arr.shape}" - ) - - _check_finite(weights_arr, f"{constraint_name} weights") - - if np.any(weights_arr <= 0): - n_invalid = int(np.sum(weights_arr <= 0)) - invalid_indices = np.where(weights_arr <= 0)[0] - raise WeightError( - f"Found {n_invalid} non-positive weights in {constraint_name} array. " - f"All weights must be positive. " - f"Non-positive weights at indices: {invalid_indices}" - ) - - return weights_arr - - def check_unsupported_combinations( data: dict, constraint_type: str, diff --git a/packages/loop_interpolation/tests/test_input_validation.py b/packages/loop_interpolation/tests/test_input_validation.py deleted file mode 100644 index 8aed9a806..000000000 --- a/packages/loop_interpolation/tests/test_input_validation.py +++ /dev/null @@ -1,83 +0,0 @@ -import numpy as np -import pytest -from loop_interpolation import _validation - -ValidationError = _validation.ValidationError -ShapeError = _validation.ShapeError -DtypeError = _validation.DtypeError -WeightError = _validation.WeightError - - -def test_value_constraint_valid_and_additional_weight_column_supported(): - pts = np.array([[0, 0, 0, 1.0], [1, 1, 1, 2.0]]) - out = _validation.validate_value_constraint(pts) - assert out.shape == (2, 4) - assert out.dtype == np.float64 - - -def test_value_constraint_non_finite_rejected(): - pts = np.array([[0.0, 0.0, 0.0, np.nan]]) - out = _validation.validate_value_constraint(pts) - assert out.shape == (0, 4) - - -def test_value_constraint_non_numeric_rejected(): - pts = np.array([["x", "y", "z", "v"]]) - with pytest.raises(DtypeError): - _validation.validate_value_constraint(pts) - - -def test_gradient_constraint_zero_vector_skipped_by_default(): - pts = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) - out = _validation.validate_gradient_constraint(pts) - assert out.shape == (0, 6) - - -def test_gradient_constraint_non_finite_rejected(): - pts = np.array([[0.0, 0.0, 0.0, 1.0, np.inf, 0.0]]) - out = _validation.validate_gradient_constraint(pts) - assert out.shape == (0, 6) - - -def test_normal_constraint_zero_vector_skipped_by_default(): - pts = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) - out = _validation.validate_normal_constraint(pts) - assert out.shape == (0, 6) - - -def test_tangent_constraint_zero_vector_skipped_by_default(): - pts = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) - out = _validation.validate_tangent_constraint(pts) - assert out.shape == (0, 6) - - -def test_interface_constraint_bad_shape_rejected(): - pts = np.array([[0.0, 0.0, 0.0]]) - with pytest.raises(ShapeError): - _validation.validate_interface_constraint(pts) - - -def test_inequality_value_constraint_invalid_bounds_rejected(): - pts = np.array([[0.0, 0.0, 0.0, 2.0, 1.0]]) - with pytest.raises(ValidationError): - _validation.validate_inequality_value_constraint(pts) - - -def test_inequality_pairs_constraint_bad_shape_rejected(): - pts = np.array([[0.0, 0.0, 0.0]]) - with pytest.raises(ShapeError): - _validation.validate_inequality_pairs_constraint(pts) - - -def test_validate_weights_scalar_and_array(): - assert _validation.validate_weights(1.5, n_constraints=3) == 1.5 - arr = np.array([1.0, 2.0, 3.0]) - out = _validation.validate_weights(arr, n_constraints=3) - assert np.array_equal(out, arr) - - -def test_validate_weights_non_positive_rejected(): - with pytest.raises(WeightError): - _validation.validate_weights(0.0, n_constraints=1) - with pytest.raises(WeightError): - _validation.validate_weights(np.array([1.0, -1.0]), n_constraints=2) diff --git a/pyproject.toml b/pyproject.toml index 5e8505d66..363b9a02e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -234,16 +234,12 @@ allow-dict-calls-with-keyword-arguments = true "LoopStructural/geometry/_structured_grid.py" = ["D", "ANN"] "LoopStructural/interpolators/__init__.py" = ["D", "ANN"] "LoopStructural/interpolators/_api.py" = ["D", "ANN"] -"LoopStructural/interpolators/_builders.py" = ["D", "ANN"] -"LoopStructural/interpolators/_constant_norm.py" = ["D", "ANN"] "LoopStructural/interpolators/_cython/__init__.py" = ["D", "ANN"] -"LoopStructural/interpolators/_discrete_fold_interpolator.py" = ["D", "ANN"] "LoopStructural/interpolators/_discrete_interpolator.py" = ["D", "ANN"] "LoopStructural/interpolators/_finite_difference_interpolator.py" = ["D", "ANN"] "LoopStructural/interpolators/_geological_interpolator.py" = ["D", "ANN"] "LoopStructural/interpolators/_interpolator_builder.py" = ["D", "ANN"] "LoopStructural/interpolators/_interpolator_factory.py" = ["D", "ANN"] -"LoopStructural/interpolators/_interpolatortype.py" = ["D", "ANN"] "LoopStructural/interpolators/_operator.py" = ["D", "ANN"] "LoopStructural/interpolators/_p1interpolator.py" = ["D", "ANN"] "LoopStructural/interpolators/_p2interpolator.py" = ["D", "ANN"] @@ -266,7 +262,6 @@ allow-dict-calls-with-keyword-arguments = true "LoopStructural/modelling/features/_structural_frame.py" = ["D", "ANN"] "LoopStructural/modelling/features/_unconformity_feature.py" = ["D", "ANN"] "LoopStructural/modelling/features/builders/__init__.py" = ["D", "ANN"] -"LoopStructural/modelling/features/builders/_analytical_fold_builder.py" = ["D", "ANN"] "LoopStructural/modelling/features/builders/_base_builder.py" = ["D", "ANN"] "LoopStructural/modelling/features/builders/_fault_builder.py" = ["D", "ANN"] "LoopStructural/modelling/features/builders/_folded_feature_builder.py" = ["D", "ANN"] @@ -305,15 +300,11 @@ allow-dict-calls-with-keyword-arguments = true "LoopStructural/utils/_surface.py" = ["D", "ANN"] "LoopStructural/utils/_transformation.py" = ["D", "ANN"] "LoopStructural/utils/colours.py" = ["D", "ANN"] -"LoopStructural/utils/config.py" = ["D", "ANN"] "LoopStructural/utils/dtm_creator.py" = ["D", "ANN"] "LoopStructural/utils/exceptions.py" = ["D", "ANN"] -"LoopStructural/utils/features.py" = ["D", "ANN"] "LoopStructural/utils/helper.py" = ["D", "ANN"] "LoopStructural/utils/json_encoder.py" = ["D", "ANN"] -"LoopStructural/utils/linalg.py" = ["D", "ANN"] "LoopStructural/utils/logging.py" = ["D", "ANN"] -"LoopStructural/utils/maths.py" = ["D", "ANN"] "LoopStructural/utils/observer.py" = ["D", "ANN"] "LoopStructural/utils/regions.py" = ["D", "ANN"] "LoopStructural/utils/typing.py" = ["D", "ANN"] diff --git a/tests/unit/io/test_exporters.py b/tests/unit/io/test_exporters.py index c47a2395b..b73985d14 100644 --- a/tests/unit/io/test_exporters.py +++ b/tests/unit/io/test_exporters.py @@ -5,8 +5,7 @@ from LoopStructural.export import exporters from LoopStructural.export.file_formats import FileFormat -from LoopStructural.geometry import BoundingBox, Surface -from LoopStructural.utils.exceptions import LoopValueError +from LoopStructural.geometry import BoundingBox # --------------------------------------------------------------------------- # Lightweight fakes standing in for a GeologicalModel/BoundingBox, so these @@ -15,46 +14,6 @@ # --------------------------------------------------------------------------- -class _SphericalFeature: - """A fake geological feature whose scalar field is a signed distance to a - sphere centred in the unit cube - guarantees a clean isosurface at 0.""" - - def evaluate_value(self, points): - centre = np.array([0.5, 0.5, 0.5]) - return np.linalg.norm(points - centre, axis=1) - 0.3 - - -class _FakeBoundingBoxArrayLike: - """Stands in for the parts of `model.bounding_box` that `write_feat_surfs` - accesses directly through numpy-style indexing (`.bb[...]`).""" - - def __init__(self, bb): - self._bb = np.asarray(bb, dtype=float) - - @property - def bb(self): - return self._bb - - -class _FakeModelForSurfaces: - """Fake model exposing only what `write_feat_surfs` touches.""" - - def __init__(self, feature_name="strati"): - self.bounding_box = _FakeBoundingBoxArrayLike([[0, 0, 0], [1, 1, 1]]) - self.nsteps = np.array([12, 12, 12]) - self._features = {feature_name: _SphericalFeature()} - - def __contains__(self, name): - return name in self._features - - def __getitem__(self, name): - return self._features[name] - - def rescale(self, points): - # identity rescale, in-place like the real implementation would allow - return points - - class _FakeModelForVolume: """Fake model exposing what `write_cubeface`/`write_vol` touch. Uses a real `BoundingBox` since that is what `GeologicalModel.bounding_box` @@ -73,110 +32,6 @@ def evaluate_model(self, points, scale=True): return (distance > 0).astype(np.int64) -# --------------------------------------------------------------------------- -# write_feat_surfs -# --------------------------------------------------------------------------- - - -def test_write_feat_surfs_feature_not_in_model_returns_false_empty(): - model = _FakeModelForSurfaces() - result = exporters.write_feat_surfs(model, "not_a_feature", file_format=FileFormat.NUMPY) - assert result == (False, []) - - -def test_write_feat_surfs_isovalue_outside_range_returns_false_empty(): - model = _FakeModelForSurfaces() - result = exporters.write_feat_surfs( - model, "strati", file_format=FileFormat.NUMPY, isovalue=999.0 - ) - assert result == (False, []) - - -def test_write_feat_surfs_unsupported_format_returns_false_empty(): - model = _FakeModelForSurfaces() - result = exporters.write_feat_surfs(model, "strati", file_format=FileFormat.OBJ) - assert result == (False, []) - - -def test_write_feat_surfs_numpy_format_success(): - # NOTE: this documents a real bug - the docstring for write_feat_surfs - # promises a `(bool, [Surface, ...])` tuple return, and every early-exit - # path in the function does return such a tuple, but the final - # success-path `return result` (LoopStructural/export/exporters.py) only - # returns the bare boolean, breaking the documented contract. Calling code - # written against the docstring (`ok, surfaces = write_feat_surfs(...)`) - # would raise `TypeError: cannot unpack non-iterable bool object`. - model = _FakeModelForSurfaces() - result = exporters.write_feat_surfs(model, "strati", file_format=FileFormat.NUMPY) - assert result is True - - -def test_write_feat_surfs_vtk_format_is_broken_for_real_surface(tmp_path): - # NOTE: this documents a second bug - `_write_feat_surfs_evtk` reads - # `surf.verts` / `surf.faces` but the `Surface` dataclass that - # `write_feat_surfs` builds via marching_cubes only exposes `.vertices` - # and `.triangles`. Any call to write_feat_surfs with FileFormat.VTK - # therefore always raises AttributeError. - model = _FakeModelForSurfaces() - file_name = tmp_path / "iso" - with pytest.raises(AttributeError, match="verts"): - exporters.write_feat_surfs( - model, "strati", file_format=FileFormat.VTK, file_name=str(file_name) - ) - - -def test_write_feat_surfs_gocad_format_writes_ts_file(tmp_path): - model = _FakeModelForSurfaces() - file_name = tmp_path / "iso_gocad" - result = exporters.write_feat_surfs( - model, "strati", file_format=FileFormat.GOCAD, file_name=str(file_name) - ) - assert result is True - ts_file = tmp_path / "iso_gocad.ts" - assert ts_file.exists() - content = ts_file.read_text() - assert "GOCAD TSurf 1" in content - assert "name: strati" in content - - -# --------------------------------------------------------------------------- -# _write_feat_surfs_evtk / _write_feat_surfs_gocad (called with correctly -# shaped objects, to isolate the writer logic from the attribute-name bug -# above) -# --------------------------------------------------------------------------- - - -class _EvtkCompatibleSurf: - def __init__(self): - self.verts = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) - self.faces = np.array([[0, 1, 2]]) - self.values = np.array([1.0, 2.0, 3.0], dtype=np.float32) - self.normals = np.array([[0.0, 0.0, 1.0]] * 3) - self.name = "evtk_surf" - - -def test_write_feat_surfs_evtk_writes_file_when_attribute_names_match(tmp_path): - surf = _EvtkCompatibleSurf() - file_name = tmp_path / "compatible" - result = exporters._write_feat_surfs_evtk(surf, str(file_name)) - assert result is True - assert (tmp_path / "compatible.vtu").exists() - - -def test_write_feat_surfs_gocad_direct_call(tmp_path): - surf = Surface( - vertices=np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), - triangles=np.array([[0, 1, 2]]), - name="direct_surf", - ) - file_name = tmp_path / "direct" - result = exporters._write_feat_surfs_gocad(surf, str(file_name)) - assert result is True - content = (tmp_path / "direct.ts").read_text() - assert "name: direct_surf" in content - assert "TRGL 1 2 3" in content - - # --------------------------------------------------------------------------- # write_cubeface # --------------------------------------------------------------------------- @@ -223,22 +78,3 @@ def test_write_vol_unsupported_format_returns_false(tmp_path): model, str(file_name), "label", np.array([5, 5, 5]), FileFormat.OBJ ) assert result is False - - -def test_write_vol_gocad_is_broken_for_real_bounding_box(tmp_path): - # NOTE: this documents a third bug - `_write_vol_gocad` does - # `bbox = model.bounding_box[:]`, treating `model.bounding_box` as a raw - # numpy array. In practice (both here and in GeologicalModel) it is a - # `BoundingBox` object whose `__getitem__` only supports string names (or - # falls through to raising `LoopValueError` for anything else, including - # a bare slice). So `write_vol(..., file_format=FileFormat.GOCAD)` always - # raises instead of writing a VOXET file. - model = _FakeModelForVolume() - file_name = tmp_path / "vol_gocad" - # `BoundingBox.__getitem__` raises its own `LoopValueError` (defined in - # `loop_common.geometry._bounding_box`, a `ValueError`). It is not the class - # of `LoopStructural.utils.exceptions`, so match both. - with pytest.raises((LoopValueError, ValueError)): - exporters.write_vol( - model, str(file_name), "label", np.array([5, 5, 5]), FileFormat.GOCAD - ) diff --git a/tests/unit/io/test_gocad.py b/tests/unit/io/test_gocad.py index a2041e686..1c325dfb7 100644 --- a/tests/unit/io/test_gocad.py +++ b/tests/unit/io/test_gocad.py @@ -8,7 +8,7 @@ _write_feat_surfs_gocad, _write_structured_grid_gocad, ) -from LoopStructural.geometry import StructuredGrid, Surface +from LoopStructural.geometry import StructuredGrid, Surface, ValuePoints def _read(path): @@ -240,3 +240,15 @@ def test_write_feat_surfs_gocad_skips_nan_vertices_and_touching_triangles(tmp_pa # remains assert content.count("TRGL") == 1 assert "TRGL 1 2 3" in content + + +def test_surface_save_ts_and_points_save_vs(tmp_path): + surf = Surface( + vertices=np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), + triangles=np.array([[0, 1, 2]]), + name="saved", + ) + surf.save(str(tmp_path / "saved.ts")) + assert "TRGL 1 2 3" in _read(tmp_path / "saved.ts") + with pytest.raises(ValueError, match="vs"): + ValuePoints().save(str(tmp_path / "points.vs")) diff --git a/tests/unit/modelling/test_lambda_feature_regions.py b/tests/unit/modelling/test_lambda_feature_regions.py new file mode 100644 index 000000000..902764d2e --- /dev/null +++ b/tests/unit/modelling/test_lambda_feature_regions.py @@ -0,0 +1,16 @@ +import numpy as np + +from LoopStructural.modelling.features import GeologicalFeature, LambdaGeologicalFeature +from LoopStructural.modelling.features._unconformity_feature import UnconformityFeature + + +def test_lambda_feature_with_unconformity_and_function_regions(): + parent = GeologicalFeature("parent", builder=None) + unconformity = UnconformityFeature(parent, 0.5) + unconformity.evaluate_value = lambda pos, **kwargs: pos[:, 2] + feature = LambdaGeologicalFeature( + lambda pos: pos[:, 0], regions=[unconformity, lambda pos: pos[:, 1] < 0.5] + ) + pos = np.array([[1.0, 0.0, 0.0], [2.0, 0.0, 1.0], [3.0, 1.0, 0.0]]) + v = feature.evaluate_value(pos) + np.testing.assert_array_equal(v, [1.0, np.nan, np.nan]) diff --git a/tests/unit/modelling/test_world_location_consumers.py b/tests/unit/modelling/test_world_location_consumers.py index 231c09cca..9d7580a9c 100644 --- a/tests/unit/modelling/test_world_location_consumers.py +++ b/tests/unit/modelling/test_world_location_consumers.py @@ -238,15 +238,10 @@ def test_internal_callers_do_not_warn(tmp_path): from LoopStructural.export.file_formats import FileFormat from tests.unit.io import test_exporters as fakes - class _Surfaces(fakes._FakeModelForSurfaces): - def rescale(self, points, *, inplace=False): - return model.rescale(points, inplace=inplace) - class _Volume(fakes._FakeModelForVolume): def rescale(self, points, *, inplace=False): return model.rescale(points, inplace=inplace) - exporters.write_feat_surfs(_Surfaces(), "strati", file_format=FileFormat.NUMPY) exporters.write_cubeface( _Volume(), str(tmp_path / "cube"), "label", np.array([5, 5, 5]), FileFormat.VTK )