Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
b4548f2
feat: Add JSON I/O functionality for surface points
flohorovicic Mar 19, 2025
e27ca15
feat: Add orientation data loading functionality
flohorovicic Mar 19, 2025
cb34e62
feat: Add horizontal stratigraphic model tutorial
flohorovicic Mar 19, 2025
f91fa03
fix: Update JSON loading to use surface names from series data - Add …
flohorovicic Mar 19, 2025
9b78ac2
fix: Update horizontal stratigraphic tutorial with correct data and m…
flohorovicic Mar 19, 2025
49b4f25
fix: correct IDs and positions for fault and rock1 in multiple series…
flohorovicic Mar 19, 2025
1e7b405
Added .json input file
flohorovicic Mar 19, 2025
c926296
Updated .json input file
flohorovicic Mar 19, 2025
f82abf2
Adjustments in stack-mapping for more flexible handling of faults
flohorovicic Mar 19, 2025
0f1734b
Added modules __init__ and minor changes in json module
flohorovicic Mar 19, 2025
6cf9a44
fix: Fix metadata handling in JSON I/O for proper preservation when l…
flohorovicic Mar 22, 2025
4c1d177
Updated .gitignore (only to ignore files generated by new tutorial)
flohorovicic Mar 22, 2025
61b7dec
Extended functionality to save .json and adjusted tests. Simple model…
flohorovicic Mar 23, 2025
6a40125
Added structural relations to .json and fixed error in second example
flohorovicic Mar 23, 2025
2a7d8f8
Fixed problem with loading of surface layer stack
flohorovicic Mar 23, 2025
e6fade1
Fixed stratigraphic pile handling in JSON I/O by reverting to working…
flohorovicic Mar 23, 2025
660ae65
Included name-id mapping in .json
flohorovicic Mar 24, 2025
1637ddb
Fix JSON serialization for NumPy types and update example data
flohorovicic Mar 24, 2025
e31bda4
Adjusted date format
flohorovicic Mar 24, 2025
c92878b
Simplified required json input further and added "minimal working exa…
flohorovicic Mar 25, 2025
6d1e029
Simplified minimal input even further: now only points and orientatio…
flohorovicic Mar 25, 2025
84d3332
Updated minimal json examples and comparison to minimal GemPy model
flohorovicic Mar 25, 2025
0386163
Additional fixes to get defaults right
flohorovicic Mar 25, 2025
360a103
Added default nugget value to minimize input even further
flohorovicic Mar 25, 2025
36fec0d
Updated tests and fixed code to pass tests.
flohorovicic Mar 28, 2025
949f7e0
fix: Update fault model example with correct series mapping and visua…
flohorovicic Apr 5, 2025
601e523
Improve scalar field visualization in fault model example - Add prope…
flohorovicic Apr 6, 2025
94f6fd3
Example model for a combination of series and faults from json
flohorovicic Apr 6, 2025
593dbbd
Add combination model JSON files to gitignore
flohorovicic Apr 6, 2025
a4f4264
fix: preserve colors when loading models from JSON - Added color pres…
flohorovicic Apr 6, 2025
cb5693c
test: update JSON I/O tests to verify color preservation - Added colo…
flohorovicic Apr 6, 2025
0e95fb7
Added TODOs for PR.
javoha Apr 11, 2025
369ef46
Added TODOs for PR.
javoha Apr 11, 2025
20ad605
fix: ensure NotRequired import works for both Python 3.11+ and earlie…
flohorovicic Apr 27, 2025
9d9f304
[BUG] Ensure compatibility with older Python versions
Leguark May 1, 2025
040d84a
Merge branch 'main' into fork/flohorovicic/feature/json_io
Leguark May 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fix JSON serialization for NumPy types and update example data
  • Loading branch information
flohorovicic committed Mar 24, 2025
commit 1637ddbbcd9ce838441226f96dbc8c19d1473595
65 changes: 46 additions & 19 deletions gempy/modules/json_io/json_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import numpy as np
from datetime import datetime

from .schema import SurfacePoint, Orientation, GemPyModelJson
from .schema import SurfacePoint, Orientation, GemPyModelJson, IdNameMapping
from gempy_engine.core.data.stack_relation_type import StackRelationType


Expand All @@ -20,12 +20,17 @@ def _numpy_to_list(obj):
"""Convert numpy arrays to lists for JSON serialization."""
if isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, np.integer):
elif isinstance(obj, (np.integer, np.int32, np.int64)):
return int(obj)
elif isinstance(obj, np.floating):
elif isinstance(obj, (np.floating, np.float32, np.float64)):
return float(obj)
return obj

@staticmethod
def _create_id_to_name(name_to_id: Dict[str, int]) -> Dict[int, str]:
"""Create an id_to_name mapping from a name_to_id mapping."""
return {id: name for name, id in name_to_id.items()}

@staticmethod
def load_model_from_json(file_path: str):
"""
Expand Down Expand Up @@ -56,23 +61,32 @@ def load_model_from_json(file_path: str):
for series in data['series']:
surface_names.extend(series['surfaces'])

# Create a mapping from surface points to their names
surface_point_names = {}
for sp in data['surface_points']:
# Find the surface name that corresponds to this ID
surface_name = None
# Use the id_name_mapping if available, otherwise create one from series data
if 'id_name_mapping' in data and data['id_name_mapping']:
name_to_id = data['id_name_mapping']['name_to_id']
id_to_name = JsonIO._create_id_to_name(name_to_id)
else:
# Create a mapping from surface points to their names
surface_point_names = {}
# First, create a mapping from surface names to their IDs
surface_id_map = {}
for series in data['series']:
for i, name in enumerate(series['surfaces']):
if i == sp['id']: # Match the ID with the index in the series
surface_name = name
break
if surface_name is not None:
break
surface_point_names[sp['id']] = surface_name if surface_name is not None else f"surface_{sp['id']}"
# Find the first surface point with this name
for sp in data['surface_points']:
if sp['id'] not in surface_id_map:
surface_id_map[sp['id']] = name
break

# Now create the mapping from IDs to names
for sp in data['surface_points']:
surface_point_names[sp['id']] = surface_id_map.get(sp['id'], f"surface_{sp['id']}")
id_to_name = surface_point_names
name_to_id = {name: id for id, name in id_to_name.items()}

# Load surface points and orientations
surface_points = JsonIO._load_surface_points(data['surface_points'], surface_point_names)
orientations = JsonIO._load_orientations(data['orientations'], surface_point_names)
surface_points = JsonIO._load_surface_points(data['surface_points'], id_to_name)
orientations = JsonIO._load_orientations(data['orientations'], id_to_name)

# Create structural frame
structural_frame = StructuralFrame.from_data_tables(surface_points, orientations)
Expand Down Expand Up @@ -262,8 +276,8 @@ def save_model_to_json(model, file_path: str) -> None:
"orientations": [],
"series": [],
"grid_settings": {
"regular_grid_resolution": JsonIO._numpy_to_list(model.grid._dense_grid.resolution),
"regular_grid_extent": JsonIO._numpy_to_list(model.grid._dense_grid.extent),
"regular_grid_resolution": [int(x) for x in model.grid._dense_grid.resolution],
"regular_grid_extent": [float(x) for x in model.grid._dense_grid.extent],
"octree_levels": None # TODO: Add octree levels if needed
},
"interpolation_options": {
Expand All @@ -274,7 +288,10 @@ def save_model_to_json(model, file_path: str) -> None:
"mesh_extraction": bool(model.interpolation_options.mesh_extraction),
"number_octree_levels": int(model.interpolation_options.number_octree_levels)
},
"fault_relations": JsonIO._numpy_to_list(model.structural_frame.fault_relations) if hasattr(model.structural_frame, 'fault_relations') else None
"fault_relations": [[int(x) for x in row] for row in model.structural_frame.fault_relations] if hasattr(model.structural_frame, 'fault_relations') else None,
"id_name_mapping": {
"name_to_id": {k: int(v) for k, v in model.structural_frame.element_name_id_map.items()}
}
}

# Get series and surface information
Expand Down Expand Up @@ -373,4 +390,14 @@ def _validate_json_schema(data: Dict[str, Any]) -> bool:
if not isinstance(ori['polarity'], int) or ori['polarity'] not in {-1, 1}:
return False

# Validate id_name_mapping if present
if 'id_name_mapping' in data:
mapping = data['id_name_mapping']
if not isinstance(mapping, dict):
return False
if 'name_to_id' not in mapping:
return False
if not isinstance(mapping['name_to_id'], dict):
return False

return True