Skip to content
Merged
Prev Previous commit
Next Next commit
[ENH] Added function to convert the model to binary
  • Loading branch information
Leguark committed May 25, 2025
commit 59edc1670b0083be112e5afe293cfa13ef57193b
27 changes: 15 additions & 12 deletions gempy/modules/serialization/save_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,7 @@ def save_model(model: GeoModel, path: str | None = None, validate_serialization:
# If no extension, add the valid extension
path = str(path_obj) + VALID_EXTENSION

model_json = model.model_dump_json(by_alias=True, indent=4)

# Compress the binary data
zlib = require_zlib()
compressed_binary_input = zlib.compress(model.structural_frame.input_tables_binary)
compressed_binary_grid = zlib.compress(model.grid.grid_binary)

binary_file = _to_binary(
header_json=model_json,
body_input=compressed_binary_input,
body_grid=compressed_binary_grid
)
binary_file = model_to_binary(model)

if validate_serialization:
model_deserialized = _deserialize_binary_file(binary_file)
Expand All @@ -72,6 +61,20 @@ def save_model(model: GeoModel, path: str | None = None, validate_serialization:
return path # Return the actual path used (helpful if extension was added)


def model_to_binary(model: GeoModel) -> bytes:
model_json = model.model_dump_json(by_alias=True, indent=4)
# Compress the binary data
zlib = require_zlib()
compressed_binary_input = zlib.compress(model.structural_frame.input_tables_binary)
compressed_binary_grid = zlib.compress(model.grid.grid_binary)
binary_file = _to_binary(
header_json=model_json,
body_input=compressed_binary_input,
body_grid=compressed_binary_grid
)
return binary_file


def load_model(path: str) -> GeoModel:
"""
Load a GeoModel from a file with extension validation.
Expand Down
11 changes: 2 additions & 9 deletions test/verify_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from approvaltests.reporters import GenericDiffReporter, GenericDiffReporterConfig

from gempy.core.data import GeoModel
from gempy.modules.serialization.save_load import _to_binary, _deserialize_binary_file
from gempy.modules.serialization.save_load import _to_binary, _deserialize_binary_file, model_to_binary
from gempy.optional_dependencies import require_zlib


Expand Down Expand Up @@ -120,14 +120,7 @@ def verify_model_serialization(model: GeoModel, verify_moment: Literal["before",
Raises:
ValueError: If `verify_moment` is not set to "before" or "after".
"""
model_json = model.model_dump_json(by_alias=True, indent=4)

# Compress the binary data
zlib = require_zlib()
compressed_binary = zlib.compress(model.structural_frame.input_tables_binary)

binary_file = _to_binary(model_json, compressed_binary)

binary_file = model_to_binary(model)

original_model = model
original_model.meta.creation_date = "<DATE_IGNORED>"
Expand Down