Skip to content

Commit

Permalink
more work on inversion_solution/* docs/typing;
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisbc committed Oct 3, 2024
1 parent ba82679 commit 26b56f9
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 26 deletions.
29 changes: 29 additions & 0 deletions docs/api/inversion_solution/inversion_solution.md
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
::: solvis.inversion_solution.inversion_solution

::: solvis.inversion_solution.inversion_solution.InversionSolution
options:
inherited_members: true
members:
- from_archive
- filter_solution
- to_archive
- archive
- archive_path
- from_archive
# from InversionSolutionFile
- ruptures
- rupture_rates
- logic_tree_branch
- fault_regime
- indices
- average_slips
- section_target_slip_rates
- section_participation_rates
- fault_participation_rates
- fault_sections
- rupture_sections
- fault_sections_with_rupture_rates
- parent_fault_names
- fault_sections_with_solution_slip_rates
- rs_with_rupture_rates
- ruptures_with_rupture_rates

10 changes: 3 additions & 7 deletions docs/api/inversion_solution/inversion_solution_file.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
::: solvis.inversion_solution.inversion_solution_file
options:
<!-- options:
docstring_options:
ignore_init_summary: false
merge_init_into_class: true
members:
- WARNING
- InversionSolutionFile
- data_to_zip_direct
- reindex_dataframe
merge_init_into_class: true -->

Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
options:
filters:
- "!^_[^_]"
- "!^get_ruptures_" # Deprecated function signatures
- "!^get_" # Deprecated function signatures
4 changes: 2 additions & 2 deletions solvis/fault_system_solution_helper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, Iterator, List, Iterable
from typing import Dict, Iterator, List, Optional

from solvis.inversion_solution.typing import InversionSolutionProtocol

Expand All @@ -13,7 +13,7 @@


def build_rupture_groups(
solution: InversionSolutionProtocol, rupture_ids: Iterable[int] = None, min_overlap: float = 0.8
solution: InversionSolutionProtocol, rupture_ids: Optional[List[int]] = None, min_overlap: float = 0.8
) -> Iterator[Dict]:
dfrs = solution.rupture_sections
rupture_ids = rupture_ids or dfrs['rupture'].unique().tolist()
Expand Down
3 changes: 1 addition & 2 deletions solvis/filter/parent_fault_id_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
TODO:
- make FilterParentFaultIds chainable
"""
from collections import namedtuple
from typing import Iterable, Iterator, Set, NamedTuple
from typing import Iterable, Iterator, NamedTuple, Set

import shapely.geometry

Expand Down
4 changes: 2 additions & 2 deletions solvis/inversion_solution/composite_solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import io
import zipfile
from pathlib import Path
from typing import Any, Dict, Iterable, Union, Optional
from typing import Any, Dict, Iterable, Optional, Union

import geopandas as gpd
import pandas as pd
Expand Down Expand Up @@ -50,7 +50,7 @@ def add_fault_system_solution(self, fault_system: str, fault_system_solution: Fa
return self

@property
def archive_path(self) -> Path:
def archive_path(self) -> Union[Path, None]:
"""Get the path of the instance."""
return self._archive_path

Expand Down
9 changes: 7 additions & 2 deletions solvis/inversion_solution/inversion_solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,16 @@

from .inversion_solution_file import InversionSolutionFile
from .inversion_solution_operations import InversionSolutionOperations
from .typing import InversionSolutionProtocol, ModelLogicTreeBranch
from .typing import ModelLogicTreeBranch


class InversionSolution(InversionSolutionFile, InversionSolutionOperations):
"""A python interface for an OpenSHA Inversion Solution archive."""
"""A python interface for an OpenSHA Inversion Solution archive.
Methods:
from_archive: deserialise an instance from zip archive.
filter_solution: get a new InversionSolution instance, filtered by rupture ids.
"""

@staticmethod
def from_archive(instance_or_path: Union[Path, str, io.BytesIO]) -> 'InversionSolution':
Expand Down
19 changes: 19 additions & 0 deletions solvis/inversion_solution/inversion_solution_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,22 @@ def reindex_dataframe(dataframe: pd.DataFrame) -> pd.DataFrame:
class InversionSolutionFile(InversionSolutionProtocol):
"""
Class to handle the OpenSHA modular archive file form.
Methods:
to_archive: serialise an instance to a zip archive.
filter_solution: get a new InversionSolution instance, filtered by rupture ids.
set_props:
Attributes:
archive: the archive instance.
archive_path: the archive path name.
ruptures: get the solution ruptures dataframe.
fault_regime:
indices:
logic_tree_branch:
rupture_rates:
ruptures:
section_target_slip_rates:
"""

RATES_PATH = 'solution/rates.csv'
Expand Down Expand Up @@ -160,6 +176,7 @@ def archive_path(self) -> Optional[Path]:

@property
def archive(self) -> zipfile.ZipFile:
"""Get an in-memory archive instance."""
log.debug('archive path: %s archive: %s ' % (self._archive_path, self._archive))
archive = None
if self._archive is None:
Expand Down Expand Up @@ -232,6 +249,7 @@ def get_regime() -> str:

@property
def rupture_rates(self) -> gpd.GeoDataFrame:
"""Get a dataframe containing ruptures and their rates"""
dtypes: defaultdict = defaultdict(lambda: 'Float32')
# dtypes = {}
dtypes["Rupture Index"] = 'UInt32' # pd.UInt32Dtype()
Expand All @@ -242,6 +260,7 @@ def rupture_rates(self) -> gpd.GeoDataFrame:

@property
def ruptures(self) -> gpd.GeoDataFrame:
"""Ruptures ruptres."""
dtypes: defaultdict = defaultdict(lambda: 'Float32')
# dtypes = {}
dtypes["Rupture Index"] = 'UInt32'
Expand Down
41 changes: 32 additions & 9 deletions solvis/inversion_solution/inversion_solution_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@


class InversionSolutionOperations(InversionSolutionProtocol):
"""
helper methods for analysis of InversionSolutionProtocol subtypes.
Deprecated:
the following methods are replaced by solvis.filter classes.
- get_rupture_ids_for_fault_names
- get_rupture_ids_for_location_radius
- get_rupture_ids_for_parent_fault
- get_rupture_ids_intersecting
- get_ruptures_for_parent_fault
- get_ruptures_intersecting
- get_solution_slip_rates_for_parent
"""

def fault_surfaces(self) -> gpd.GeoDataFrame:
return SolutionSurfacesBuilder(self).fault_surfaces()

Expand Down Expand Up @@ -188,12 +203,9 @@ def parent_fault_names(self) -> List[str]:

@property
def fault_sections_with_solution_slip_rates(self) -> gpd.GeoDataFrame:
"""
Calculate and cache fault sections and their solution slip rates.
Solution slip rate combines input (avg slips) and solution (rupture rates).
"""Calculate and cache fault sections and their solution slip rates.
Returns:
a gpd.GeoDataFrame
NB: Solution slip rate combines input (avg slips) and solution (rupture rates).
"""
if self._fs_with_soln_rates is not None:
return self._fs_with_soln_rates
Expand Down Expand Up @@ -223,6 +235,7 @@ def _get_soln_rates(self):

@property
def rs_with_rupture_rates(self) -> gpd.GeoDataFrame:
"""Get a dataframe joining rupture_sections and rupture_rates."""
if self._rs_with_rupture_rates is not None:
return self._rs_with_rupture_rates # pragma: no cover

Expand All @@ -244,6 +257,7 @@ def rs_with_rupture_rates(self) -> gpd.GeoDataFrame:

@property
def ruptures_with_rupture_rates(self) -> pd.DataFrame:
"""Get a dataframe joining ruptures and rupture_rates."""
if self._ruptures_with_rupture_rates is not None:
return self._ruptures_with_rupture_rates # pragma: no cover

Expand All @@ -261,8 +275,12 @@ def ruptures_with_rupture_rates(self) -> pd.DataFrame:
return self._ruptures_with_rupture_rates

def get_rupture_ids_intersecting(self, polygon: shapely.geometry.Polygon) -> pd.Series:
"""Return IDs for any ruptures intersecting the polygon."""
warnings.warn("Please use solvis.filter.classes *.for_polygons method instead", DeprecationWarning)
"""Return IDs for any ruptures intersecting the polygon.
Warning:
Deprecated: please use solvis.filter.*.for_polygons method instead
"""
warnings.warn("Please use solvis.filter.*.for_polygons method instead", DeprecationWarning)
return pd.Series(list(FilterRuptureIds(self).for_polygon(polygon)))

def get_rupture_ids_for_location_radius(
Expand Down Expand Up @@ -322,6 +340,7 @@ def get_rupture_ids_for_parent_fault(self, parent_fault_name: str) -> pd.Series:
Returns:
a Pandas series of rupture IDs
"""
warnings.warn("Please use solvis.filter.classes instead.", DeprecationWarning)
# sr = sol.rs_with_rupture_rates
# print(f"Sections with rate (sr_, where parent fault name = '{parent_fault_name}'.")
sects = self.fault_sections[self.fault_sections['ParentName'] == parent_fault_name]
Expand Down Expand Up @@ -362,6 +381,8 @@ def get_rupture_ids_for_fault_names(
```
Returns a set of 1440 rupture IDs in the intersection of the two datasets.
"""
warnings.warn("Please use solvis.filter.classes instead.", DeprecationWarning)

first = True
rupture_ids: Set[int]
for fault_name in corupture_fault_names:
Expand Down Expand Up @@ -390,12 +411,14 @@ def get_rupture_ids_for_fault_names(

def get_ruptures_for_parent_fault(self, parent_fault_name: str) -> pd.Series:
"""Deprecated signature for get_rupture_ids_for_parent_fault."""
warnings.warn("Please use updated method name: get_rupture_ids_for_parent_fault", category=DeprecationWarning)
warnings.warn("Please use solvis.filter.classes instead.", DeprecationWarning)

Check warning on line 414 in solvis/inversion_solution/inversion_solution_operations.py

View check run for this annotation

Codecov / codecov/patch

solvis/inversion_solution/inversion_solution_operations.py#L414

Added line #L414 was not covered by tests
# warnings.warn("Please use updated method name: get_rupture_ids_for_parent_fault", category=DeprecationWarning)
return self.get_rupture_ids_for_parent_fault(parent_fault_name)

def get_ruptures_intersecting(self, polygon) -> pd.Series:
"""Deprecated signature for get_rupture_ids_intersecting."""
warnings.warn("Please use updated method name: get_rupture_ids_intersecting", category=DeprecationWarning)
warnings.warn("Please use solvis.filter.classes instead.", DeprecationWarning)

Check warning on line 420 in solvis/inversion_solution/inversion_solution_operations.py

View check run for this annotation

Codecov / codecov/patch

solvis/inversion_solution/inversion_solution_operations.py#L420

Added line #L420 was not covered by tests
# warnings.warn("Please use updated method name: get_rupture_ids_intersecting", category=DeprecationWarning)
return self.get_rupture_ids_intersecting(polygon)

def get_solution_slip_rates_for_parent_fault(self, parent_fault_name: str) -> pd.DataFrame:
Expand Down
2 changes: 1 addition & 1 deletion solvis/inversion_solution/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def archive(self) -> Optional[zipfile.ZipFile]:
class CompositeSolutionProtocol(Protocol):

_solutions: Mapping[str, InversionSolutionProtocol] = {}
_archive_path: Union[Path, str] = ''
_archive_path: Optional[Path]

def rupture_surface(self, fault_system: str, rupture_id: int) -> gpd.GeoDataFrame:
"""builder method returning the rupture surface of a given rupture id."""
Expand Down

0 comments on commit 26b56f9

Please sign in to comment.