Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
cec6e0f
feat: Add JSON I/O functionality for surface points
flohorovicic Mar 19, 2025
1e86bcd
feat: Add orientation data loading functionality
flohorovicic Mar 19, 2025
8d031e6
feat: Add horizontal stratigraphic model tutorial
flohorovicic Mar 19, 2025
7790956
fix: Update JSON loading to use surface names from series data - Add …
flohorovicic Mar 19, 2025
74ef1d3
fix: Update horizontal stratigraphic tutorial with correct data and m…
flohorovicic Mar 19, 2025
8e580d8
fix: correct IDs and positions for fault and rock1 in multiple series…
flohorovicic Mar 19, 2025
3eb7dc0
Added .json input file
flohorovicic Mar 19, 2025
5c2b339
Updated .json input file
flohorovicic Mar 19, 2025
430a5ac
Adjustments in stack-mapping for more flexible handling of faults
flohorovicic Mar 19, 2025
2f5a6b5
Added modules __init__ and minor changes in json module
flohorovicic Mar 19, 2025
04e87a1
fix: Fix metadata handling in JSON I/O for proper preservation when l…
flohorovicic Mar 22, 2025
1df8dac
Updated .gitignore (only to ignore files generated by new tutorial)
flohorovicic Mar 22, 2025
1c60ddd
Extended functionality to save .json and adjusted tests. Simple model…
flohorovicic Mar 23, 2025
427092e
Added structural relations to .json and fixed error in second example
flohorovicic Mar 23, 2025
3fd2106
Fixed problem with loading of surface layer stack
flohorovicic Mar 23, 2025
9caa992
Fixed stratigraphic pile handling in JSON I/O by reverting to working…
flohorovicic Mar 23, 2025
c5ddb5a
Included name-id mapping in .json
flohorovicic Mar 24, 2025
e6d8c23
Fix JSON serialization for NumPy types and update example data
flohorovicic Mar 24, 2025
f80c4b0
Adjusted date format
flohorovicic Mar 24, 2025
c06aa90
Simplified required json input further and added "minimal working exa…
flohorovicic Mar 25, 2025
2a2c46b
Simplified minimal input even further: now only points and orientatio…
flohorovicic Mar 25, 2025
c4f60aa
Updated minimal json examples and comparison to minimal GemPy model
flohorovicic Mar 25, 2025
e6f9794
Additional fixes to get defaults right
flohorovicic Mar 25, 2025
558a185
Added default nugget value to minimize input even further
flohorovicic Mar 25, 2025
f9862ed
Updated tests and fixed code to pass tests.
flohorovicic Mar 28, 2025
bf069e9
fix: Update fault model example with correct series mapping and visua…
flohorovicic Apr 5, 2025
77a9625
Improve scalar field visualization in fault model example - Add prope…
flohorovicic Apr 6, 2025
5948e42
Example model for a combination of series and faults from json
flohorovicic Apr 6, 2025
a615e8d
Add combination model JSON files to gitignore
flohorovicic Apr 6, 2025
56ac045
fix: preserve colors when loading models from JSON - Added color pres…
flohorovicic Apr 6, 2025
e35ec32
test: update JSON I/O tests to verify color preservation - Added colo…
flohorovicic Apr 6, 2025
986d6c8
Added TODOs for PR.
javoha Apr 11, 2025
27b2292
Added TODOs for PR.
javoha Apr 11, 2025
bb3dc7a
fix: ensure NotRequired import works for both Python 3.11+ and earlie…
flohorovicic Apr 27, 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
Extended functionality to save .json and adjusted tests. Simple model…
…s work, some problems with fault relations still remaining.
  • Loading branch information
flohorovicic authored and Leguark committed May 1, 2025
commit 1c60ddddcad3cbe23b3e0dcb566db983bb490d91
104 changes: 61 additions & 43 deletions gempy/modules/json_io/json_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
from typing import Dict, Any, Optional, List
import numpy as np
from datetime import datetime

from .schema import SurfacePoint, Orientation, GemPyModelJson
from gempy_engine.core.data.stack_relation_type import StackRelationType
Expand All @@ -14,6 +15,17 @@
class JsonIO:
"""Class for handling JSON I/O operations for GemPy models."""

@staticmethod
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):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
return obj

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

# Create id to name mapping
id_to_name = {i: name for i, name in enumerate(surface_names)}

# Create a mapping from surface points to their names
surface_point_names = {}
for sp in data['surface_points']:
surface_point_names[sp['id']] = next((name for series in data['series']
for name in series['surfaces']
if name in surface_names), "surface_0")

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

# Create structural frame
structural_frame = StructuralFrame.from_data_tables(surface_points, orientations)
Expand All @@ -60,20 +76,12 @@ def load_model_from_json(file_path: str):
resolution=data['grid_settings']['regular_grid_resolution']
)

# Create interpolation options
# Create interpolation options with kernel options
interpolation_options = InterpolationOptions(
range=1.7, # Default value
c_o=10, # Default value
mesh_extraction=True, # Default value
number_octree_levels=1 # Default value
)

# Create GeoModelMeta with all metadata fields
model_meta = GeoModelMeta(
name=data['metadata']['name'],
creation_date=data['metadata'].get('creation_date', None),
last_modification_date=data['metadata'].get('last_modification_date', None),
owner=data['metadata'].get('owner', None)
range=data['interpolation_options'].get('kernel_options', {}).get('range', 1.7),
c_o=data['interpolation_options'].get('kernel_options', {}).get('c_o', 10),
mesh_extraction=data['interpolation_options'].get('mesh_extraction', True),
number_octree_levels=data['interpolation_options'].get('number_octree_levels', 1)
)

# Create GeoModel
Expand All @@ -84,13 +92,25 @@ def load_model_from_json(file_path: str):
interpolation_options=interpolation_options
)

# Set the metadata
# Set the metadata with proper dates
model_meta = GeoModelMeta(
name=data['metadata']['name'],
creation_date=data['metadata'].get('creation_date', datetime.now().isoformat()),
last_modification_date=data['metadata'].get('last_modification_date', datetime.now().isoformat()),
owner=data['metadata'].get('owner', None)
)
model.meta = model_meta

# Map series to surfaces with structural relations
mapping_object = {series['name']: series['surfaces'] for series in data['series']}
map_stack_to_surfaces(model, mapping_object, series_data=data['series'])

# Set fault relations after structural groups are set up
if 'fault_relations' in data and data['fault_relations'] is not None:
fault_relations = np.array(data['fault_relations'])
if fault_relations.shape == (len(model.structural_frame.structural_groups), len(model.structural_frame.structural_groups)):
model.structural_frame.fault_relations = fault_relations

return model

@staticmethod
Expand All @@ -112,7 +132,7 @@ def _load_surface_points(surface_points_data: List[SurfacePoint], id_to_name: Di
from gempy.core.data.surface_points import SurfacePointsTable

# Validate data structure
required_fields = {'x', 'y', 'z', 'id', 'nugget'}
required_fields = {'x', 'y', 'z', 'nugget', 'id'} # Add 'id' back to required fields
for i, sp in enumerate(surface_points_data):
missing_fields = required_fields - set(sp.keys())
if missing_fields:
Expand All @@ -128,21 +148,16 @@ def _load_surface_points(surface_points_data: List[SurfacePoint], id_to_name: Di
x = np.array([sp['x'] for sp in surface_points_data])
y = np.array([sp['y'] for sp in surface_points_data])
z = np.array([sp['z'] for sp in surface_points_data])
ids = np.array([sp['id'] for sp in surface_points_data])
nugget = np.array([sp['nugget'] for sp in surface_points_data])

# Create name_id_map from unique IDs
unique_ids = np.unique(ids)
name_id_map = {id_to_name[id]: id for id in unique_ids}
names = [id_to_name.get(sp['id'], "surface_0") for sp in surface_points_data]

# Create SurfacePointsTable
return SurfacePointsTable.from_arrays(
x=x,
y=y,
z=z,
names=[id_to_name[id] for id in ids],
nugget=nugget,
name_id_map=name_id_map
names=names,
nugget=nugget
)

@staticmethod
Expand All @@ -164,7 +179,7 @@ def _load_orientations(orientations_data: List[Orientation], id_to_name: Dict[in
from gempy.core.data.orientations import OrientationsTable

# Validate data structure
required_fields = {'x', 'y', 'z', 'G_x', 'G_y', 'G_z', 'id', 'nugget', 'polarity'}
required_fields = {'x', 'y', 'z', 'G_x', 'G_y', 'G_z', 'nugget', 'polarity', 'id'} # Add 'id' back to required fields
for i, ori in enumerate(orientations_data):
missing_fields = required_fields - set(ori.keys())
if missing_fields:
Expand All @@ -173,10 +188,10 @@ def _load_orientations(orientations_data: List[Orientation], id_to_name: Dict[in
# Validate data types
if not all(isinstance(ori[field], (int, float)) for field in ['x', 'y', 'z', 'G_x', 'G_y', 'G_z', 'nugget']):
raise ValueError(f"Invalid data type in orientation {i}. All coordinates, gradients, and nugget must be numeric.")
if not isinstance(ori.get('polarity', 1), int) or ori.get('polarity', 1) not in {-1, 1}:
raise ValueError(f"Invalid polarity in orientation {i}. Must be 1 (normal) or -1 (reverse).")
if not isinstance(ori['id'], int):
raise ValueError(f"Invalid data type in orientation {i}. ID must be an integer.")
if not isinstance(ori['polarity'], int) or ori['polarity'] not in {-1, 1}:
raise ValueError(f"Invalid polarity in orientation {i}. Must be 1 (normal) or -1 (reverse).")

# Extract coordinates and other data
x = np.array([ori['x'] for ori in orientations_data])
Expand All @@ -185,20 +200,16 @@ def _load_orientations(orientations_data: List[Orientation], id_to_name: Dict[in
G_x = np.array([ori['G_x'] for ori in orientations_data])
G_y = np.array([ori['G_y'] for ori in orientations_data])
G_z = np.array([ori['G_z'] for ori in orientations_data])
ids = np.array([ori['id'] for ori in orientations_data])
nugget = np.array([ori['nugget'] for ori in orientations_data])
names = [id_to_name.get(ori['id'], "surface_0") for ori in orientations_data]

# Apply polarity to gradients
for i, ori in enumerate(orientations_data):
if ori['polarity'] == -1:
if ori.get('polarity', 1) == -1:
G_x[i] *= -1
G_y[i] *= -1
G_z[i] *= -1

# Create name_id_map from unique IDs
unique_ids = np.unique(ids)
name_id_map = {id_to_name[id]: id for id in unique_ids}

# Create OrientationsTable
return OrientationsTable.from_arrays(
x=x,
Expand All @@ -207,9 +218,8 @@ def _load_orientations(orientations_data: List[Orientation], id_to_name: Dict[in
G_x=G_x,
G_y=G_y,
G_z=G_z,
names=[id_to_name[id] for id in ids],
nugget=nugget,
name_id_map=name_id_map
names=names,
nugget=nugget
)

@staticmethod
Expand All @@ -233,11 +243,19 @@ def save_model_to_json(model, file_path: str) -> None:
"orientations": [],
"series": [],
"grid_settings": {
"regular_grid_resolution": model.grid._dense_grid.resolution.tolist(),
"regular_grid_extent": model.grid._dense_grid.extent.tolist(),
"regular_grid_resolution": JsonIO._numpy_to_list(model.grid._dense_grid.resolution),
"regular_grid_extent": JsonIO._numpy_to_list(model.grid._dense_grid.extent),
"octree_levels": None # TODO: Add octree levels if needed
},
"interpolation_options": {}
"interpolation_options": {
"kernel_options": {
"range": float(model.interpolation_options.kernel_options.range),
"c_o": float(model.interpolation_options.kernel_options.c_o)
},
"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
}

# Get series and surface information
Expand Down
Loading