Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make parent fault filter chainable #66

Merged
merged 3 commits into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
- updated flake8 and applied many docstring fixes.
- refactored participation methods into module/class.
- use valid NSHM fault names in docstring examples.
- `FilterParentFaultIds` class is now chainable, like the other filters.

## Added
- new filter package providing classes for filtering solutions
Expand All @@ -31,6 +32,7 @@
- added participation methods to fault_system_solution
- a simple rupture grouping algorithm (can this be a different type of filter??);
- `pandera` library for dataframe model validations and better docs
- ChainableSet now supports set.symmetric_difference

## Removed
- deprecated `solvis.solvis` functions removed.
Expand Down
2 changes: 2 additions & 0 deletions solvis/filter/chainable_set_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ def new_chainable_set(
instance._chained_set = set.union(result, self.chained_set) if self.chained_set else result
elif join_prior == SetOperationEnum.DIFFERENCE:
instance._chained_set = set.difference(result, self.chained_set) if self.chained_set else result
elif join_prior == SetOperationEnum.SYMMETRIC_DIFFERENCE:
instance._chained_set = set.symmetric_difference(result, self.chained_set) if self.chained_set else result
else:
raise ValueError(f"Unsupported join type {join_prior}") # pragma: no cover
return instance
Expand Down
59 changes: 39 additions & 20 deletions solvis/filter/parent_fault_id_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
This module provides a class for filtering solution parent faults.

Classes:
FilterParentFaultIds: a filter for parent faults, returning qualifying fault_ids.
FilterParentFaultIds: a chainable filter for parent faults, returning qualifying fault ids.
ParentFaultMapping: a namedtuple representing id and name of a parent fault.

Functions:
Expand All @@ -11,20 +11,26 @@

Examples:
```py
>>> model = InversionSolution.from_archive(filename).model
>>> parent_fault_ids = FilterParentFaultIds(model)\
>>> solution = InversionSolution.from_archive(filename)
>>> parent_fault_ids = FilterParentFaultIds(solution)\
.for_parent_fault_names(['Alpine: Jacksons to Kaniere', 'BooBoo'])
```

TODO:
- make FilterParentFaultIds chainable
>>> # chained with rutpure id filter
>>> rupture_ids = FilterRuptureIds(solution)\
.for_magnitude(min_mag=5.75, max_mag=6.25)\

>>> parent_fault_ids = FilterParentFaultIds(solution)\
.for_parent_fault_names(['Alpine: Jacksons to Kaniere'])\
.for_rupture_ids(rupture_ids)
```
"""

from typing import Iterable, Iterator, NamedTuple, Set
from typing import Iterable, Iterator, NamedTuple, Set, Union

import shapely.geometry

from ..solution.typing import InversionSolutionProtocol
from ..solution.typing import InversionSolutionProtocol, SetOperationEnum
from .chainable_set_base import ChainableSetBase


class ParentFaultMapping(NamedTuple):
Expand Down Expand Up @@ -71,7 +77,7 @@ def valid_parent_fault_names(solution, validate_names: Iterable[str]) -> Set[str
return set(validate_names)


class FilterParentFaultIds:
class FilterParentFaultIds(ChainableSetBase):
"""A helper class to filter parent faults, returning qualifying fault_ids.

Class methods all return sets to make it easy to combine filters with
Expand All @@ -82,6 +88,7 @@ class FilterParentFaultIds:
>>> solution = InversionSolution.from_archive(filename)
>>> parent_fault_ids = FilterParentFaultIds(solution)\
.for_parent_fault_names(['Alpine: Jacksons to Kaniere'])
.
```
"""

Expand All @@ -96,7 +103,7 @@ def __init__(self, solution: InversionSolutionProtocol):
def for_named_faults(self, named_fault_names: Iterable[str]):
raise NotImplementedError()

def all(self) -> Set[int]:
def all(self) -> ChainableSetBase:
"""Convenience method returning ids for all solution parent faults.

NB the usual `join_prior` argument is not implemented as it doesn't seem useful here.
Expand All @@ -105,16 +112,19 @@ def all(self) -> Set[int]:
the parent_fault_ids.
"""
result = set(self._solution.solution_file.fault_sections['ParentID'].tolist())
return result
return self.new_chainable_set(result, self._solution)

def for_parent_fault_names(self, parent_fault_names: Iterable[str]) -> Set[int]:
def for_parent_fault_names(
self, parent_fault_names: Iterable[str], join_prior: Union[SetOperationEnum, str] = 'intersection'
) -> ChainableSetBase:
"""Find parent fault ids for the given parent_fault names.

Args:
parent_fault_names: A list of one or more `parent_fault` names.
join_prior: How to join this methods' result with the prior chain (if any) (default = 'intersection').

Returns:
The fault_ids matching the filter.
A chainable set of fault_ids matching the filter.

Raises:
ValueError: If any `parent_fault_names` argument is not valid.
Expand All @@ -123,34 +133,43 @@ def for_parent_fault_names(self, parent_fault_names: Iterable[str]) -> Set[int]:
ids = df0[df0['ParentName'].isin(list(valid_parent_fault_names(self._solution, parent_fault_names)))][
'ParentID'
].tolist()
return set([int(id) for id in ids])
result = set([int(id) for id in ids])
return self.new_chainable_set(result, self._solution, join_prior=join_prior)

def for_subsection_ids(self, fault_section_ids: Iterable[int]) -> Set[int]:
def for_subsection_ids(
self, fault_section_ids: Iterable[int], join_prior: Union[SetOperationEnum, str] = 'intersection'
) -> ChainableSetBase:
"""Find parent fault ids that contain any of the given fault_section_ids.

Args:
fault_section_ids: A list of one or more fault_section ids.
join_prior: How to join this methods' result with the prior chain (if any) (default = 'intersection').

Returns:
The fault_ids matching the filter.
A chainable set of fault_ids matching the filter.
"""
df0 = self._solution.solution_file.fault_sections
ids = df0[df0['FaultID'].isin(list(fault_section_ids))]['ParentID'].unique().tolist()
return set([int(id) for id in ids])
result = set([int(id) for id in ids])
return self.new_chainable_set(result, self._solution, join_prior=join_prior)

def for_polygon(self, polygon: shapely.geometry.Polygon, contained: bool = True):
raise NotImplementedError()

def for_rupture_ids(self, rupture_ids: Iterable[int]) -> Set[int]:
def for_rupture_ids(
self, rupture_ids: Iterable[int], join_prior: Union[SetOperationEnum, str] = 'intersection'
) -> ChainableSetBase:
"""Find parent_fault_ids for the given rupture_ids.

Args:
rupture_ids: A list of one or more rupture ids.
join_prior: How to join this methods' result with the prior chain (if any) (default = 'intersection').

Returns:
The parent_fault_ids matching the filter.
A chainable set of parent fault_ids matching the filter.
"""
# df0 = self._solution.solution_file.rupture_sections
df0 = self._solution.model.fault_sections_with_rupture_rates
ids = df0[df0['Rupture Index'].isin(list(rupture_ids))].ParentID.unique().tolist()
return set([int(id) for id in ids])
result = set([int(id) for id in ids])
return self.new_chainable_set(result, self._solution, join_prior=join_prior)
11 changes: 5 additions & 6 deletions solvis/filter/rupture_id_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,26 @@
This module provides a class for filtering solution ruptures.

Classes:
FilterRuptureIds: a filter for ruptures, returning qualifying rupture ids.
FilterRuptureIds: a chainable filter for ruptures, returning qualifying rupture ids.

Examples:
```py
>>> # ruptures within 50km of Hamilton with magnitude between 5.75 and 6.25.
>>> ham50 = solvis.circle_polygon(50000, -37.78, 175.28) # 50km radius around Hamilton
<POLYGON ((175.849 -37.779, 175.847 -37.823, 175.839 -37.866, 175.825 -37.90...>
>>> solution = solvis.InversionSolution.from_archive(filename)
>>> model = solution.model
>>> rupture_ids = FilterRuptureIds(model)\
>>> rupture_ids = FilterRuptureIds(solution)\
.for_magnitude(min_mag=5.75, max_mag=6.25)\
.for_polygon(ham50)

>>> # ruptures on any of faults A, B, with magnitude and rupture rate limits
>>> rupture_ids = FilterRuptureIds(model)\
>>> rupture_ids = FilterRuptureIds(solution)\
>>> .for_parent_fault_names(['Alpine: Jacksons to Kaniere', 'Vernon 1' ])\
>>> .for_magnitude(7.0, 8.0)\
>>> .for_rupture_rate(1e-6, 1e-2)

>>> # ruptures on fault A that do not involve fault B:
>>> rupture_ids = FilterRuptureIds(model)\
>>> rupture_ids = FilterRuptureIds(solution)\
>>> .for_parent_fault_names(['Alpine: Jacksons to Kaniere'])\
>>> .for_parent_fault_names(['Vernon 1'], join_prior='difference')
```
Expand Down Expand Up @@ -306,5 +305,5 @@ def for_polygon(
df1 = self._solution.model.rupture_sections

df2 = df1.join(df0, 'section', how='inner')
result = set(df2[index].unique())
result = set(df2[index].tolist())
return self.new_chainable_set(result, self._solution, self._drop_zero_rates, join_prior=join_prior)
8 changes: 4 additions & 4 deletions solvis/filter/subsection_id_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
This module provides a class for filtering solution fault sections (subsections).

Classes:
FilterSubsectionIds: a filter for ruptures, returning qualifying rupture ids.
FilterSubsectionIds: a chainable filter for fault sections, returning qualifying fault section ids.

Examples:
```py
>>> ham50 = solvis.circle_polygon(50000, -37.78, 175.28) # 50km radius around Hamilton
<POLYGON ((175.849 -37.779, 175.847 -37.823, 175.839 -37.866, 175.825 -37.90...>
>>> sol = solvis.InversionSolution.from_archive(filename)
>>> rupture_ids = FilterRuptureIds(sol)\
>>> solution = solvis.InversionSolution.from_archive(filename)
>>> rupture_ids = FilterRuptureIds(solution)\
.for_magnitude(min_mag=5.75, max_mag=6.25)\
.for_polygon(ham50)

>>> subsection_ids = FilterSubsectionIds(sol)\
>>> subsection_ids = FilterSubsectionIds(solution)\
>>> .for_rupture_ids(rupture_ids)
```
"""
Expand Down
1 change: 1 addition & 0 deletions solvis/solution/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,4 @@ class SetOperationEnum(Enum):
UNION = 1
INTERSECTION = 2
DIFFERENCE = 3
SYMMETRIC_DIFFERENCE = 4
36 changes: 36 additions & 0 deletions test/filter/test_filter_parent_fault_ids.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,39 @@ def test_parent_faults_for_ruptures(filter_parent_fault_ids, filter_rupture_ids,

# there will be more parent faults, given all those ruptures on the original parents
assert filter_parent_fault_ids.for_rupture_ids(rupt_ids).issuperset(pids)


def test_parent_faults_filter_chaining(filter_parent_fault_ids, crustal_solution_fixture):
# filter_rupture_ids = FilterParentFaultIds(crustal_solution_fixture)
pnames = random.sample(crustal_solution_fixture.model.parent_fault_names, 2)

together = filter_parent_fault_ids.for_parent_fault_names(pnames)
first = filter_parent_fault_ids.for_parent_fault_names(pnames[:1])
second = filter_parent_fault_ids.for_parent_fault_names(pnames[1:])

assert together.difference(second) == first
assert together.difference(first) == second

## union
chained = filter_parent_fault_ids.for_parent_fault_names(pnames[:1]).for_parent_fault_names(
pnames[1:], join_prior='union'
)
assert together == chained

## difference
diff = filter_parent_fault_ids.for_parent_fault_names(pnames).for_parent_fault_names(
pnames[1:], join_prior='difference'
)
assert diff == second.difference(together)

## symmetric_differnce
diff = filter_parent_fault_ids.for_parent_fault_names(pnames).for_parent_fault_names(
pnames[1:], join_prior='symmetric_difference'
)
assert diff == second.symmetric_difference(together)

## intersection
intersect = filter_parent_fault_ids.for_parent_fault_names(pnames).for_parent_fault_names(
pnames[1:]
) # default join_prior is `intersection`
assert intersect == second
7 changes: 7 additions & 0 deletions test/filter/test_filter_rupture_ids.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ def test_ruptures_for_polygon_intersecting(crustal_solution_fixture, filter_rupt
).issubset(rupture_ids)


def test_ruptures_for_polygon_type(crustal_solution_fixture, filter_rupture_ids):
MRO = location_by_id('MRO')
poly = circle_polygon(1.5e5, MRO['latitude'], MRO['longitude']) # 150km circle around MRO
rids = filter_rupture_ids.for_polygon(poly)
assert isinstance(list(rids)[0], int)


def test_ruptures_for_polygons_join_iterable(crustal_solution_fixture, filter_rupture_ids):
WLG = location_by_id('WLG')
MRO = location_by_id('MRO')
Expand Down