Skip to content

Commit 0308f5a

Browse files
committed
[CLN] Remove all the unnecessary code during serialization
1 parent f68bed6 commit 0308f5a

File tree

5 files changed

+21
-108
lines changed

5 files changed

+21
-108
lines changed

gempy/core/data/encoders/converters.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,18 +46,6 @@ def instantiate_if_necessary(data: dict, key: str, type: type) -> None:
4646
# First, create a context variable
4747
loading_model_context = ContextVar('loading_model_context', default={})
4848

49-
@contextmanager
50-
def loading_model_injection(surface_points_binary: np.ndarray, orientations_binary: np.ndarray):
51-
token = loading_model_context.set({
52-
'surface_points_binary': surface_points_binary,
53-
'orientations_binary' : orientations_binary
54-
})
55-
try:
56-
yield
57-
finally:
58-
loading_model_context.reset(token)
59-
60-
6149
@contextmanager
6250
def loading_model_from_binary(binary_body: bytes):
6351
token = loading_model_context.set({

gempy/core/data/structural_frame.py

Lines changed: 4 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,10 @@ def orientations(self, modified_orientations: OrientationsTable) -> None:
391391
"""Distributes the modified orientations back to the structural elements."""
392392
for element in self.structural_elements:
393393
element.orientations.data = modified_orientations.get_orientations_by_id(element.id).data
394+
395+
@property
396+
def input_tables_binary(self):
397+
return self.surface_points_copy.data.tobytes() + self.orientations_copy.data.tobytes()
394398

395399
@property
396400
def element_id_name_map(self) -> dict[int, str]:
@@ -489,49 +493,6 @@ def deserialize_binary(cls, data: Union["StructuralFrame", dict], constructor: M
489493
# Access the context variable to get injected data
490494

491495

492-
@model_validator(mode="after")
493-
def deserialize_surface_points(self: "StructuralFrame"):
494-
# Access the context variable to get injected data
495-
context = loading_model_context.get()
496-
497-
if 'surface_points_binary' not in context:
498-
return self
499-
500-
# Check if we have a binary payload to digest
501-
binary_array = context['surface_points_binary']
502-
if not isinstance(binary_array, np.ndarray):
503-
return self
504-
if binary_array.shape[0] < 1:
505-
return self
506-
507-
self.surface_points = SurfacePointsTable(
508-
data=binary_array,
509-
name_id_map=self.surface_points_copy.name_id_map
510-
)
511-
512-
return self
513-
514-
@model_validator(mode="after")
515-
def deserialize_orientations(self: "StructuralFrame"):
516-
# TODO: Check here the binary size of surface_points_binary
517-
518-
# Access the context variable to get injected data
519-
context = loading_model_context.get()
520-
if 'orientations_binary' not in context:
521-
return self
522-
523-
# Check if we have a binary payload to digest
524-
binary_array = context['orientations_binary']
525-
if not isinstance(binary_array, np.ndarray):
526-
return self
527-
528-
self.orientations = OrientationsTable(
529-
data=binary_array,
530-
name_id_map=self.orientations_copy.name_id_map
531-
)
532-
533-
return self
534-
535496
@computed_field
536497
def binary_meta_data(self) -> dict:
537498
return {

gempy/modules/serialization/save_load.py

Lines changed: 9 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,25 @@
1-
import json
2-
3-
import numpy as np
4-
51
from ...core.data import GeoModel
6-
from ...core.data.encoders.converters import loading_model_injection, loading_model_from_binary
2+
from ...core.data.encoders.converters import loading_model_from_binary
73
from ...optional_dependencies import require_zlib
84

95

106
def save_model(model: GeoModel, path: str):
11-
import zlib
127

13-
# TODO: Serialize to json
148
model_json = model.model_dump_json(by_alias=True, indent=4)
159

16-
# TODO: Serialize to binary
17-
data: np.ndarray = model.structural_frame.surface_points_copy.data
18-
sp_binary = data.tobytes()
19-
ori_binary = model.structural_frame.orientations_copy.data.tobytes()
20-
2110
# Compress the binary data
22-
compressed_binary = zlib.compress(sp_binary + ori_binary)
11+
zlib = require_zlib()
12+
compressed_binary = zlib.compress(model.structural_frame.input_tables_binary)
2313

24-
# Add compression info to metadata
25-
# model_dict = model.model_dump(by_alias=True)
26-
# model_dict["_binary_metadata"] = {
27-
# "sp_shape" : model.structural_frame.surface_points_copy.data.shape,
28-
# "sp_dtype" : str(model.structural_frame.surface_points_copy.data.dtype),
29-
# "ori_shape" : model.structural_frame.orientations_copy.data.shape,
30-
# "ori_dtype" : str(model.structural_frame.orientations_copy.data.dtype),
31-
# "compression": "zlib",
32-
# "sp_length" : len(sp_binary) # Need this to split the arrays after decompression
33-
# }
34-
35-
# TODO: Putting both together
3614
binary_file = _to_binary(model_json, compressed_binary)
15+
16+
# TODO: Add validation
17+
3718
with open(path, 'wb') as f:
3819
f.write(binary_file)
3920

21+
22+
4023
def load_model(path: str) -> GeoModel:
4124
with open(path, 'rb') as f:
4225
binary_file = f.read()
@@ -46,14 +29,8 @@ def load_model(path: str) -> GeoModel:
4629

4730
# Split header and body
4831
header_json = binary_file[4:4 + header_length].decode('utf-8')
49-
header_dict = json.loads(header_json)
50-
51-
# metadata = header_dict.pop("_binary_metadata")
52-
53-
# Decompress the binary data
54-
# ori_data, sp_data = _foo(binary_file, header_length, metadata)
55-
5632
binary_body = binary_file[4 + header_length:]
33+
5734
zlib = require_zlib()
5835
decompressed_binary = zlib.decompress(binary_body)
5936
with loading_model_from_binary(
@@ -64,19 +41,6 @@ def load_model(path: str) -> GeoModel:
6441
return model
6542

6643

67-
def _foo(binary_file, header_length, metadata):
68-
zlib = require_zlib()
69-
body = binary_file[4 + header_length:]
70-
decompressed_binary = zlib.decompress(body)
71-
# Split the decompressed data using the stored length
72-
sp_binary = decompressed_binary[:metadata["sp_length"]]
73-
ori_binary = decompressed_binary[metadata["sp_length"]:]
74-
# Reconstruct arrays
75-
sp_data = np.frombuffer(sp_binary, dtype=np.dtype(metadata["sp_dtype"])).reshape(metadata["sp_shape"])
76-
ori_data = np.frombuffer(ori_binary, dtype=np.dtype(metadata["ori_dtype"])).reshape(metadata["ori_shape"])
77-
return ori_data, sp_data
78-
79-
8044
def _to_binary(header_json, body_) -> bytes:
8145
header_json_bytes = header_json.encode('utf-8')
8246
header_json_length = len(header_json_bytes)

test/test_modules/test_serialize_model.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
import os
33
import pprint
44

5+
from gempy_engine.core.data import InterpolationOptions
6+
57
import gempy as gp
6-
from gempy.core.data.encoders.converters import loading_model_injection
8+
from gempy.core.data.encoders.converters import loading_model_from_binary
79
from gempy.core.data.enumerators import ExampleModel
810
from gempy.modules.serialization.save_load import save_model, load_model
9-
from gempy_engine.core.data import InterpolationOptions
1011
from test.verify_helper import verify_json
1112

1213

@@ -20,10 +21,8 @@ def test_generate_horizontal_stratigraphic_model():
2021
with open(file_path, "w") as f:
2122
f.write(model_json)
2223

23-
# TODO: modify this for the binary
24-
with loading_model_injection(
25-
surface_points_binary=model.structural_frame.surface_points_copy.data, # TODO: Here we need to pass the binary array
26-
orientations_binary=model.structural_frame.orientations_copy.data
24+
with loading_model_from_binary(
25+
binary_body=model.structural_frame.input_tables_binary
2726
):
2827
model_deserialized = gp.data.GeoModel.model_validate_json(model_json)
2928

test/test_modules/test_serialize_model.test_generate_horizontal_stratigraphic_model.verify/Horizontal Stratigraphic Model serialization.approved.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,9 @@
249249
},
250250
"is_dirty": true,
251251
"basement_color": "#ffbe00",
252-
"serialize_sp": 3507338795,
253-
"serialize_orientations": 553806131
252+
"binary_meta_data": {
253+
"sp_binary_length": 432
254+
}
254255
},
255256
"grid": {
256257
"_octree_grid": null,

0 commit comments

Comments
 (0)