diff --git a/docs/proto/KeyValueStore.proto b/docs/proto/KeyValueStore.proto index 5f7a6ee08..d579be5eb 100644 --- a/docs/proto/KeyValueStore.proto +++ b/docs/proto/KeyValueStore.proto @@ -19,16 +19,42 @@ message KeyValueStoreInputChunk { } } +// Element type of the values stored for a key +enum KeyValueElementType { + KEY_VALUE_ELEMENT_TYPE_FLOAT32 = 0; + KEY_VALUE_ELEMENT_TYPE_FLOAT64 = 1; + KEY_VALUE_ELEMENT_TYPE_INT32 = 2; + KEY_VALUE_ELEMENT_TYPE_INT64 = 3; + KEY_VALUE_ELEMENT_TYPE_UINT32 = 4; + KEY_VALUE_ELEMENT_TYPE_UINT64 = 5; +} + message KeyValueInputParameters { // Name needs to be sent in the first message string name = 1; int64 num_elements = 2; + KeyValueElementType element_type = 3; } -message KeyValueStoreChunk { repeated float values = 1; } +// FLOAT32 values travel in values, FLOAT64 in double_values, INT32 and INT64 +// in int_values, UINT32 and UINT64 in uint_values +message KeyValueStoreChunk { + repeated float values = 1; + repeated double double_values = 2; + repeated sint64 int_values = 3; + repeated uint64 uint_values = 4; +} -message KeyValueStoreOutputRequest { string name = 1; } +message KeyValueStoreOutputRequest { + string name = 1; + KeyValueElementType element_type = 2; +} -message KeyValueStoreOutputChunk { repeated float values = 1; } +message KeyValueStoreOutputChunk { + repeated float values = 1; + repeated double double_values = 2; + repeated sint64 int_values = 3; + repeated uint64 uint_values = 4; +} message KeyValueStoreRemoveRequest { string name = 1; } diff --git a/docs/rips/PythonExamples/surfaces_and_visualization/import_polygon_file.py b/docs/rips/PythonExamples/surfaces_and_visualization/import_polygon_file.py new file mode 100644 index 000000000..30d91aed7 --- /dev/null +++ b/docs/rips/PythonExamples/surfaces_and_visualization/import_polygon_file.py @@ -0,0 +1,32 @@ +###################################################################### +# This example imports a polygon from a .pol file +###################################################################### +import os +import tempfile + +import rips + +resinsight = rips.Instance.find() + +polygon_collection = resinsight.project.descendants(rips.PolygonCollection)[0] + +with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname: + # A .pol file has one "x y depth" point per line. "999.0 999.0 999.0" ends a polygon. + file_name = os.path.join(tmpdirname, "example_polygon.pol") + with open(file_name, "w") as f: + f.write("0.0 0.0 1000.0\n") + f.write("1000.0 0.0 1000.0\n") + f.write("1000.0 1000.0 1000.0\n") + f.write("0.0 1000.0 1000.0\n") + f.write("999.0 999.0 999.0\n") + + # The polygons are imported into a new folder named after the file. + # The first polygon in the file is returned. + polygon = polygon_collection.import_polygon_file( + file_name=file_name, + on_name_conflict=rips.NameConflictPolicy.AUTO_RENAME, + ) + + print(f"Imported polygon: {polygon.name}") + for coordinate in polygon.coordinates: + print(coordinate) diff --git a/docs/rips/generated/KeyValueStore_pb2.py b/docs/rips/generated/KeyValueStore_pb2.py index 68fa84eb9..0610616ef 100644 --- a/docs/rips/generated/KeyValueStore_pb2.py +++ b/docs/rips/generated/KeyValueStore_pb2.py @@ -25,25 +25,27 @@ import Definitions_pb2 as Definitions__pb2 -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13KeyValueStore.proto\x12\x04rips\x1a\x11\x44\x65\x66initions.proto\"\x94\x01\n\x17KeyValueStoreInputChunk\x12\x33\n\nparameters\x18\x01 \x01(\x0b\x32\x1d.rips.KeyValueInputParametersH\x00\x12*\n\x06values\x18\x02 \x01(\x0b\x32\x18.rips.KeyValueStoreChunkH\x00\x42\x18\n\x16KeyValueStoreChunkType\"=\n\x17KeyValueInputParameters\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cnum_elements\x18\x02 \x01(\x03\"$\n\x12KeyValueStoreChunk\x12\x0e\n\x06values\x18\x01 \x03(\x02\"*\n\x1aKeyValueStoreOutputRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"*\n\x18KeyValueStoreOutputChunk\x12\x0e\n\x06values\x18\x01 \x03(\x02\"*\n\x1aKeyValueStoreRemoveRequest\x12\x0c\n\x04name\x18\x01 \x01(\t2\xf1\x01\n\rKeyValueStore\x12N\n\x08SetValue\x12\x1d.rips.KeyValueStoreInputChunk\x1a\x1f.rips.ClientToServerStreamReply\"\x00(\x01\x12P\n\x08GetValue\x12 .rips.KeyValueStoreOutputRequest\x1a\x1e.rips.KeyValueStoreOutputChunk\"\x00\x30\x01\x12>\n\x0bRemoveValue\x12 .rips.KeyValueStoreRemoveRequest\x1a\x0b.rips.Empty\"\x00\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x13KeyValueStore.proto\x12\x04rips\x1a\x11\x44\x65\x66initions.proto\"\x94\x01\n\x17KeyValueStoreInputChunk\x12\x33\n\nparameters\x18\x01 \x01(\x0b\x32\x1d.rips.KeyValueInputParametersH\x00\x12*\n\x06values\x18\x02 \x01(\x0b\x32\x18.rips.KeyValueStoreChunkH\x00\x42\x18\n\x16KeyValueStoreChunkType\"n\n\x17KeyValueInputParameters\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cnum_elements\x18\x02 \x01(\x03\x12/\n\x0c\x65lement_type\x18\x03 \x01(\x0e\x32\x19.rips.KeyValueElementType\"d\n\x12KeyValueStoreChunk\x12\x0e\n\x06values\x18\x01 \x03(\x02\x12\x15\n\rdouble_values\x18\x02 \x03(\x01\x12\x12\n\nint_values\x18\x03 \x03(\x12\x12\x13\n\x0buint_values\x18\x04 \x03(\x04\"[\n\x1aKeyValueStoreOutputRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12/\n\x0c\x65lement_type\x18\x02 \x01(\x0e\x32\x19.rips.KeyValueElementType\"j\n\x18KeyValueStoreOutputChunk\x12\x0e\n\x06values\x18\x01 \x03(\x02\x12\x15\n\rdouble_values\x18\x02 \x03(\x01\x12\x12\n\nint_values\x18\x03 \x03(\x12\x12\x13\n\x0buint_values\x18\x04 \x03(\x04\"*\n\x1aKeyValueStoreRemoveRequest\x12\x0c\n\x04name\x18\x01 \x01(\t*\xe7\x01\n\x13KeyValueElementType\x12\"\n\x1eKEY_VALUE_ELEMENT_TYPE_FLOAT32\x10\x00\x12\"\n\x1eKEY_VALUE_ELEMENT_TYPE_FLOAT64\x10\x01\x12 \n\x1cKEY_VALUE_ELEMENT_TYPE_INT32\x10\x02\x12 \n\x1cKEY_VALUE_ELEMENT_TYPE_INT64\x10\x03\x12!\n\x1dKEY_VALUE_ELEMENT_TYPE_UINT32\x10\x04\x12!\n\x1dKEY_VALUE_ELEMENT_TYPE_UINT64\x10\x05\x32\xf1\x01\n\rKeyValueStore\x12N\n\x08SetValue\x12\x1d.rips.KeyValueStoreInputChunk\x1a\x1f.rips.ClientToServerStreamReply\"\x00(\x01\x12P\n\x08GetValue\x12 .rips.KeyValueStoreOutputRequest\x1a\x1e.rips.KeyValueStoreOutputChunk\"\x00\x30\x01\x12>\n\x0bRemoveValue\x12 .rips.KeyValueStoreRemoveRequest\x1a\x0b.rips.Empty\"\x00\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'KeyValueStore_pb2', _globals) if not _descriptor._USE_C_DESCRIPTORS: DESCRIPTOR._loaded_options = None + _globals['_KEYVALUEELEMENTTYPE']._serialized_start=659 + _globals['_KEYVALUEELEMENTTYPE']._serialized_end=890 _globals['_KEYVALUESTOREINPUTCHUNK']._serialized_start=49 _globals['_KEYVALUESTOREINPUTCHUNK']._serialized_end=197 _globals['_KEYVALUEINPUTPARAMETERS']._serialized_start=199 - _globals['_KEYVALUEINPUTPARAMETERS']._serialized_end=260 - _globals['_KEYVALUESTORECHUNK']._serialized_start=262 - _globals['_KEYVALUESTORECHUNK']._serialized_end=298 - _globals['_KEYVALUESTOREOUTPUTREQUEST']._serialized_start=300 - _globals['_KEYVALUESTOREOUTPUTREQUEST']._serialized_end=342 - _globals['_KEYVALUESTOREOUTPUTCHUNK']._serialized_start=344 - _globals['_KEYVALUESTOREOUTPUTCHUNK']._serialized_end=386 - _globals['_KEYVALUESTOREREMOVEREQUEST']._serialized_start=388 - _globals['_KEYVALUESTOREREMOVEREQUEST']._serialized_end=430 - _globals['_KEYVALUESTORE']._serialized_start=433 - _globals['_KEYVALUESTORE']._serialized_end=674 + _globals['_KEYVALUEINPUTPARAMETERS']._serialized_end=309 + _globals['_KEYVALUESTORECHUNK']._serialized_start=311 + _globals['_KEYVALUESTORECHUNK']._serialized_end=411 + _globals['_KEYVALUESTOREOUTPUTREQUEST']._serialized_start=413 + _globals['_KEYVALUESTOREOUTPUTREQUEST']._serialized_end=504 + _globals['_KEYVALUESTOREOUTPUTCHUNK']._serialized_start=506 + _globals['_KEYVALUESTOREOUTPUTCHUNK']._serialized_end=612 + _globals['_KEYVALUESTOREREMOVEREQUEST']._serialized_start=614 + _globals['_KEYVALUESTOREREMOVEREQUEST']._serialized_end=656 + _globals['_KEYVALUESTORE']._serialized_start=893 + _globals['_KEYVALUESTORE']._serialized_end=1134 # @@protoc_insertion_point(module_scope) diff --git a/docs/rips/generated/generated_classes.py b/docs/rips/generated/generated_classes.py index 5af829073..cdeab50ae 100644 --- a/docs/rips/generated/generated_classes.py +++ b/docs/rips/generated/generated_classes.py @@ -2772,6 +2772,20 @@ def create_polygon(self, name: str="", coordinates: List[List[float]]=[], on_nam return self._call_pdm_method_return_value("CreatePolygon", Polygon, name=name, coordinates=coordinates, on_name_conflict=on_name_conflict) + def import_polygon_file(self, file_name: str="", name: str="", on_name_conflict: NameConflictPolicy=NameConflictPolicy.FAIL) -> Polygon: + """ + Import polygons from file into a new folder. The folder is named after the file unless a name is given. Returns the first polygon in the file + + Arguments: + file_name (str): Polygon file (*.pol, *.dat, *.txt, *.csv) + name (str): Name of the new folder. A file with a single polygon also gives the polygon this name. Defaults to the file name + on_name_conflict (NameConflictPolicy): One of [FAIL, AUTO_RENAME, OVERWRITE] + Returns: + Polygon + """ + return self._call_pdm_method_return_value("ImportPolygonFile", Polygon, file_name=file_name, name=name, on_name_conflict=on_name_conflict) + + def polygons(self) -> List[Polygon]: """Polygons @@ -4622,8 +4636,8 @@ def set_geometry_from_keys(self, vertices_key: str="", triangles_key: str="") -> Set geometry from keys. Arguments: - vertices_key (str): Key for x, y and depth of each vertex - triangles_key (str): Key for three vertex indices per triangle + vertices_key (str): Key for x, y and depth of each vertex (float64) + triangles_key (str): Key for three vertex indices per triangle (uint32) Returns: """ diff --git a/docs/rips/project.py b/docs/rips/project.py index a11ac2c60..3af5a11c4 100644 --- a/docs/rips/project.py +++ b/docs/rips/project.py @@ -36,7 +36,7 @@ WellPath, ) -from typing import Optional, List +from typing import Optional, List, Tuple @add_method(Project) @@ -540,28 +540,65 @@ def create_corner_point_grid( ) +# Element type and chunk field for each numpy dtype name the key-value store transports +_KEY_VALUE_ELEMENT_TYPES = { + "float32": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_FLOAT32, "values"), + "float64": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_FLOAT64, "double_values"), + "int32": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_INT32, "int_values"), + "int64": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_INT64, "int_values"), + "uint32": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_UINT32, "uint_values"), + "uint64": (KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_UINT64, "uint_values"), +} + + +def _key_value_element_type(dtype: object) -> Tuple[int, str]: + # Accepts a numpy dtype, a numpy scalar type or a dtype name, without importing numpy + if isinstance(dtype, type): + name = dtype.__name__ + else: + name = str(getattr(dtype, "name", dtype)) + if name not in _KEY_VALUE_ELEMENT_TYPES: + raise ValueError( + "Unsupported dtype {}. Supported: {}".format( + name, ", ".join(_KEY_VALUE_ELEMENT_TYPES) + ) + ) + return _KEY_VALUE_ELEMENT_TYPES[name] + + @add_method(Project) -def set_key_values(self, key, values): +def set_key_values(self, key, values, dtype="float32"): """Sets values for a given key in the key-value store. Arguments: key(str): The key (should be unique). - values(list): a list of double precision floating point numbers + values(list): a list of numbers + dtype: numpy dtype of the values: float32 (default), float64, int32, int64, + uint32 or uint64. Reading the key needs the same dtype. """ - request_iterator = self.__generate_key_value_store_input_chunks(values, key) + element_type, field = _key_value_element_type(dtype) + request_iterator = self.__generate_key_value_store_input_chunks( + values, key, element_type, field + ) reply = self.__key_value_store_stub.SetValue(request_iterator) if reply.accepted_value_count < len(values): raise IndexError @add_method(Project) -def __generate_key_value_store_input_chunks(self, array, name): +def __generate_key_value_store_input_chunks( + self, + array, + name, + element_type=KeyValueStore_pb2.KEY_VALUE_ELEMENT_TYPE_FLOAT32, + field="values", +): index = -1 while index < len(array): chunk = KeyValueStore_pb2.KeyValueStoreInputChunk() if index == -1: parameters = KeyValueStore_pb2.KeyValueInputParameters( - name=name, num_elements=len(array) + name=name, num_elements=len(array), element_type=element_type ) chunk.parameters.CopyFrom(parameters) index += 1 @@ -569,7 +606,7 @@ def __generate_key_value_store_input_chunks(self, array, name): actual_chunk_size = min(len(array) - index + 1, self.chunk_size) chunk.values.CopyFrom( KeyValueStore_pb2.KeyValueStoreChunk( - values=array[index : index + actual_chunk_size] + **{field: array[index : index + actual_chunk_size]} ) ) index += actual_chunk_size @@ -584,35 +621,46 @@ def __generate_key_value_store_input_chunks(self, array, name): def key_values_async( self, key, + dtype="float32", ): - """Get float values for a given key. Async: returns an iterator. + """Get values for a given key. Async: returns an iterator. Arguments: key(str): The key to get. + dtype: numpy dtype the values were set with: float32 (default), float64, + int32, int64, uint32 or uint64. Returns: - An iterator to a chunk object containing an array of float values + An iterator to a chunk object containing an array of values: values for + float32, double_values for float64, int_values for int32 and int64 and + uint_values for uint32 and uint64. Loop through the chunks and then the values within the chunk to get all values. """ - request = KeyValueStore_pb2.KeyValueStoreOutputRequest(name=key) + element_type, _ = _key_value_element_type(dtype) + request = KeyValueStore_pb2.KeyValueStoreOutputRequest( + name=key, element_type=element_type + ) for chunk in self.__key_value_store_stub.GetValue(request): yield chunk @add_method(Project) -def key_values(self, key): - """Get float values for a given key. Synchronous: returns a list. ` +def key_values(self, key, dtype="float32"): + """Get values for a given key. Synchronous: returns a list. ` Arguments: key(str): The key to get. + dtype: numpy dtype the values were set with: float32 (default), float64, + int32, int64, uint32 or uint64. Returns: - A list of float values + A list of values """ + _, field = _key_value_element_type(dtype) all_values = [] - generator = self.key_values_async(key) + generator = self.key_values_async(key, dtype) for chunk in generator: - for value in chunk.values: + for value in getattr(chunk, field): all_values.append(value) return all_values diff --git a/docs/rips/surface.py b/docs/rips/surface.py index d43f11226..bd684ad59 100644 --- a/docs/rips/surface.py +++ b/docs/rips/surface.py @@ -1,4 +1,5 @@ import inspect +import operator import uuid from collections.abc import Iterable @@ -12,9 +13,10 @@ SurfaceInterface, TriangulatedSurface, ) -from typing import List, Optional, Sequence, Type, TypeVar, Union +from typing import Any, Callable, List, Optional, Sequence, Type, TypeVar, Union SurfaceT = TypeVar("SurfaceT", bound=SurfaceInterface) +ValueT = TypeVar("ValueT") @add_method(RegularSurface) @@ -73,16 +75,32 @@ def get_property(self: RegularSurface, name: str) -> List[float]: pass -def _flatten(values: Sequence[Union[float, Iterable[float]]]) -> List[float]: - flat: List[float] = [] +def _flatten( + values: Sequence[Union[Any, Iterable[Any]]], convert: Callable[[Any], ValueT] +) -> List[ValueT]: + flat: List[ValueT] = [] for value in values: if isinstance(value, Iterable): - flat.extend(float(v) for v in value) + flat.extend(convert(v) for v in value) else: - flat.append(float(value)) + flat.append(convert(value)) return flat +def _triangle_index(value: Any) -> int: + # Whole-number floats such as 2.0, also numpy floats, are accepted as indices + try: + index = operator.index(value) + except TypeError: + number = float(value) + if not number.is_integer(): + raise RipsError("Invalid triangle index {}".format(value)) + index = int(number) + if index < 0: + raise RipsError("Invalid triangle index {}".format(value)) + return index + + @add_method(TriangulatedSurface) def set_geometry( self: TriangulatedSurface, @@ -95,9 +113,9 @@ def set_geometry( Arguments: vertices (List[List[float]]): x, y and depth of each vertex, depth positive - downwards (float32). A flat list of x, y, depth values is also accepted. - triangles (List[List[int]]): Three vertex indices per triangle, zero based. - A flat list of indices is also accepted. + downwards (float64). A flat list of x, y, depth values is also accepted. + triangles (List[List[int]]): Three vertex indices per triangle, zero based + (uint32). A flat list of indices is also accepted. """ project = self.ancestor(Project) if not project: @@ -106,8 +124,15 @@ def set_geometry( vertices_key = "{}_{}".format(uuid.uuid4(), "triangulated_surface_vertices") triangles_key = "{}_{}".format(uuid.uuid4(), "triangulated_surface_triangles") - project.set_key_values(vertices_key, _flatten(vertices)) - project.set_key_values(triangles_key, _flatten(triangles)) + vertex_values = _flatten(vertices, float) + indices = _flatten(triangles, _triangle_index) + + project.set_key_values(vertices_key, vertex_values, dtype="float64") + try: + project.set_key_values(triangles_key, indices, dtype="uint32") + except Exception: + project.remove_key_values(vertices_key) + raise self.set_geometry_from_keys(vertices_key=vertices_key, triangles_key=triangles_key) diff --git a/docs/rips/tests/test_key_value_store.py b/docs/rips/tests/test_key_value_store.py index 14c4c7c19..ace15dec6 100644 --- a/docs/rips/tests/test_key_value_store.py +++ b/docs/rips/tests/test_key_value_store.py @@ -60,3 +60,68 @@ def test_set_and_remove_and_get_values(rips_instance, initialize_test): with pytest.raises(rips.RipsError, match="No matching key found."): project.key_values(key) + + +@pytest.mark.parametrize( + "dtype, input_values", + [ + ("float32", [0.5, -1.25, 3.0e38]), + ("float64", [7319649.123, -1.0e-300, 1.7e308]), + ("int32", [-(2**31), 0, 2**31 - 1]), + ("int64", [-(2**63), 0, 2**63 - 1]), + ("uint32", [0, 16777217, 2**32 - 1]), + ("uint64", [0, 2**53 + 1, 2**64 - 1]), + ], +) +def test_set_and_get_typed_values(rips_instance, initialize_test, dtype, input_values): + project = rips_instance.project + key = "my-" + dtype + "-key" + project.set_key_values(key, input_values, dtype=dtype) + + output_values = project.key_values(key, dtype=dtype) + if dtype == "float32": + assert output_values == pytest.approx(input_values, rel=1e-7) + else: + assert output_values == input_values + + # Reading with another element type fails + other_dtype = "float32" if dtype != "float32" else "float64" + with pytest.raises(rips.RipsError, match="element type"): + project.key_values(key, dtype=other_dtype) + + project.remove_key_values(key) + + +def test_set_typed_values_out_of_range(rips_instance, initialize_test): + project = rips_instance.project + + # The server checks that the values fit the element type + with pytest.raises(rips.RipsError, match="out of range for element type UINT32"): + project.set_key_values("too-large-uint32", [0, 1, 2**32], dtype="uint32") + + with pytest.raises(rips.RipsError, match="out of range for element type INT32"): + project.set_key_values("too-large-int32", [2**31], dtype="int32") + + with pytest.raises(rips.RipsError, match="out of range for element type INT32"): + project.set_key_values("too-small-int32", [-(2**31) - 1], dtype="int32") + + +def test_set_typed_values_out_of_range_in_later_chunk(rips_instance, initialize_test): + project = rips_instance.project + key = "partly-out-of-range-uint32" + + # The first chunk is accepted, the out of range value is in the second chunk + input_values = list(range(project.chunk_size)) + [2**32] + with pytest.raises(rips.RipsError, match="out of range for element type UINT32"): + project.set_key_values(key, input_values, dtype="uint32") + + # Nothing is stored when the upload fails + with pytest.raises(rips.RipsError, match="No matching key found."): + project.key_values(key, dtype="uint32") + + +def test_unsupported_dtype(rips_instance, initialize_test): + project = rips_instance.project + + with pytest.raises(ValueError, match="Unsupported dtype"): + project.set_key_values("int16-key", [1, 2, 3], dtype="int16") diff --git a/docs/rips/tests/test_polygon.py b/docs/rips/tests/test_polygon.py index e822e2f43..07dea6ed2 100644 --- a/docs/rips/tests/test_polygon.py +++ b/docs/rips/tests/test_polygon.py @@ -178,3 +178,140 @@ def test_add_folder_returns_polygon_collection(rips_instance, initialize_test): typing.get_type_hints(rips.PolygonCollection.add_folder)["return"] is rips.PolygonCollection ) + + +def _write_pol_file(path, polygons): + # .pol files store depth, so z is written with the sign flipped + lines = [] + for polygon in polygons: + lines += [f"{x} {y} {-z}" for x, y, z in polygon] + lines.append("999.0 999.0 999.0") + path.write_text("\n".join(lines) + "\n") + + +def test_import_polygon_file(rips_instance, initialize_test, tmp_path): + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + first = [[0.0, 0.0, -1000.0], [100.0, 0.0, -1000.0], [100.0, 100.0, -1500.0]] + second = [[200.0, 0.0, -1000.0], [300.0, 0.0, -1000.0], [300.0, 100.0, -1000.0]] + + single_file = tmp_path / "single.pol" + _write_pol_file(single_file, [first]) + + polygon = root.import_polygon_file(file_name=str(single_file)) + assert polygon.name == "single" + assert len(polygon.coordinates) == len(first) + for expected, actual in zip(first, polygon.coordinates): + for e, a in zip(expected, actual): + assert math.isclose(e, a, rel_tol=1e-9, abs_tol=0.0) + + multi_file = tmp_path / "multi.pol" + _write_pol_file(multi_file, [first, second]) + + polygon = root.import_polygon_file(file_name=str(multi_file)) + assert polygon.name == "multi (1)" + + folder_names = [s.collection_name() for s in root.sub_collections()] + assert folder_names == ["single", "multi"] + + +def test_import_polygon_file_errors(rips_instance, initialize_test, tmp_path): + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + with pytest.raises(rips.RipsError, match="does not exist"): + root.import_polygon_file(file_name=str(tmp_path / "missing.pol")) + + empty_file = tmp_path / "empty.pol" + empty_file.write_text("") + with pytest.raises(rips.RipsError, match="No polygons found"): + root.import_polygon_file(file_name=str(empty_file)) + + assert root.sub_collections() == [] + + +def test_import_polygon_file_name_conflict(rips_instance, initialize_test, tmp_path): + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + coordinates = [[0.0, 0.0, -1000.0], [100.0, 0.0, -1000.0], [100.0, 100.0, -1000.0]] + pol_file = tmp_path / "fence.pol" + _write_pol_file(pol_file, [coordinates]) + + root.import_polygon_file(file_name=str(pol_file)) + + # The default policy is to fail on a folder name already used in the same folder + with pytest.raises(rips.RipsError, match="already exists"): + root.import_polygon_file(file_name=str(pol_file)) + + renamed = root.import_polygon_file( + file_name=str(pol_file), on_name_conflict=rips.NameConflictPolicy.AUTO_RENAME + ) + assert renamed.name == "fence_1" + + overwritten = root.import_polygon_file( + file_name=str(pol_file), on_name_conflict=rips.NameConflictPolicy.OVERWRITE + ) + assert overwritten.name == "fence" + + folder_names = [s.collection_name() for s in root.sub_collections()] + assert folder_names == ["fence_1", "fence"] + + +def test_import_polygon_file_with_name(rips_instance, initialize_test, tmp_path): + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + first = [[0.0, 0.0, -1000.0], [100.0, 0.0, -1000.0], [100.0, 100.0, -1000.0]] + second = [[200.0, 0.0, -1000.0], [300.0, 0.0, -1000.0], [300.0, 100.0, -1000.0]] + + # A single polygon is named after the folder + single_file = tmp_path / "single.pol" + _write_pol_file(single_file, [first]) + polygon = root.import_polygon_file(file_name=str(single_file), name="My Polygon") + assert polygon.name == "My Polygon" + + # Several polygons get the folder name as prefix + multi_file = tmp_path / "multi.pol" + _write_pol_file(multi_file, [first, second]) + polygon = root.import_polygon_file(file_name=str(multi_file), name="Faults") + assert polygon.name == "Faults (1)" + + folders = root.sub_collections() + assert [s.collection_name() for s in folders] == ["My Polygon", "Faults"] + polygon_names = [p.name for p in folders[1].descendants(rips.Polygon)] + assert polygon_names == ["Faults (1)", "Faults (2)"] + + +def test_import_polygon_file_with_name_conflict( + rips_instance, initialize_test, tmp_path +): + root = rips_instance.project.descendants(rips.PolygonCollection)[0] + + coordinates = [[0.0, 0.0, -1000.0], [100.0, 0.0, -1000.0], [100.0, 100.0, -1000.0]] + pol_file = tmp_path / "fence.pol" + _write_pol_file(pol_file, [coordinates]) + + root.import_polygon_file(file_name=str(pol_file), name="Boundary") + + # The conflict policy applies to the given name, not the file name + with pytest.raises(rips.RipsError, match="already exists"): + root.import_polygon_file(file_name=str(pol_file), name="Boundary") + + renamed = root.import_polygon_file( + file_name=str(pol_file), + name="Boundary", + on_name_conflict=rips.NameConflictPolicy.AUTO_RENAME, + ) + assert renamed.name == "Boundary_1" + + overwritten = root.import_polygon_file( + file_name=str(pol_file), + name="Boundary", + on_name_conflict=rips.NameConflictPolicy.OVERWRITE, + ) + assert overwritten.name == "Boundary" + + # No conflict with a folder named after the file + from_file = root.import_polygon_file(file_name=str(pol_file)) + assert from_file.name == "fence" + + folder_names = [s.collection_name() for s in root.sub_collections()] + assert folder_names == ["Boundary_1", "Boundary", "fence"] diff --git a/docs/rips/tests/test_surfaces.py b/docs/rips/tests/test_surfaces.py index e02af9bec..16b968765 100644 --- a/docs/rips/tests/test_surfaces.py +++ b/docs/rips/tests/test_surfaces.py @@ -287,6 +287,65 @@ def test_triangulated_surface_invalid_values(rips_instance, initialize_test): s.set_property("net to gross", [1.0, 2.0, 3.0]) +def test_triangulated_surface_float64_vertices( + rips_instance, initialize_test, tmp_path +): + case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID" + project = rips_instance.project + project.load_case(path=case_path) + + surface_collection = project.descendants(rips.SurfaceCollection)[0] + s = surface_collection.new_triangulated_surface(name="Utm") + + # float32 holds 7319649.123 as 7319649.0, the vertices travel as float64 + vertices = [ + [456333.25, 7319649.123, 2494.125], + [456433.25, 7319649.123, 2495.125], + [456333.25, 7319749.5, 2496.125], + ] + s.set_geometry(vertices, [[0, 1, 2]]) + + project_file = tmp_path / "utm.rsp" + project.save(project_file.as_posix()) + + surface_files = list((tmp_path / "utm_surfaces").glob("Utm_*.ts")) + assert len(surface_files) == 1 + written = surface_files[0].read_text() + assert "VRTX 1 456333.25 7319649.123 2494.125" in written + assert "VRTX 2 456433.25 7319649.123 2495.125" in written + + +def test_triangulated_surface_uint32_indices(rips_instance, initialize_test): + case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID" + rips_instance.project.load_case(path=case_path) + + surface_collection = rips_instance.project.descendants(rips.SurfaceCollection)[0] + s = surface_collection.new_triangulated_surface(name="Indices") + + vertices = [[0.0, 0.0, 1000.0], [100.0, 0.0, 1000.0], [0.0, 100.0, 1000.0]] + + # The indices travel as uint32, so an index float32 cannot hold arrives exactly + with pytest.raises(rips.RipsError, match=r"Invalid triangle index 16777217\."): + s.set_geometry(vertices, [[0, 1, 16777217]]) + + with pytest.raises(rips.RipsError, match="out of range for element type UINT32"): + s.set_geometry(vertices, [[0, 1, 2**32]]) + + with pytest.raises(rips.RipsError, match="Invalid triangle index -1"): + s.set_geometry(vertices, [[0, 1, -1]]) + + with pytest.raises(rips.RipsError, match=r"Invalid triangle index 2\.5"): + s.set_geometry(vertices, [[0.0, 1.0, 2.5]]) + + with pytest.raises(rips.RipsError, match="Invalid triangle index -1"): + s.set_geometry(vertices, [[0.0, 1.0, -1.0]]) + + # Whole-number floats are accepted as indices + s.set_geometry(vertices, [[0.0, 1.0, 2.0]]) + + s.set_geometry(vertices, [[0, 1, 2]]) + + def test_triangulated_surface_name_uniqueness(rips_instance, initialize_test): case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID" rips_instance.project.load_case(path=case_path)