Skip to content

Commit d230072

Browse files
authored
Merge pull request #53 from TomoATT/devel
Add average action for conflicting receiver locations and selection methods
2 parents abbf28b + 0576b2e commit d230072

6 files changed

Lines changed: 569 additions & 44 deletions

File tree

‎pytomoatt/_version.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '0.3.0'
1+
__version__ = '0.3.1'

‎pytomoatt/io/asciimodel.py‎

Lines changed: 63 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22
from ..utils.common import init_axis, ignore_nan_3d
33
from ..setuplog import SetupLog
4-
from scipy.interpolate import griddata
4+
from scipy.interpolate import griddata, RegularGridInterpolator
55

66

77
class ASCIIModel():
@@ -25,9 +25,45 @@ def read_ascii(self, usecols=(0, 1, 2, 3), comments='#', sep=None):
2525
delimiter=sep
2626
)
2727

28+
@staticmethod
29+
def _to_regular_grid(coords, values):
30+
"""Reshape points into a 3D volume if they form a complete regular grid.
31+
32+
:param coords: Point coordinates with shape ``(n, 3)``
33+
:type coords: numpy.ndarray
34+
:param values: Point values with shape ``(n,)``
35+
:type values: numpy.ndarray
36+
:return: ``(axes, volume)`` with ascending axes, or ``None`` if the
37+
points are scattered, incomplete or duplicated
38+
:rtype: tuple or None
39+
"""
40+
axes, axis_indices = [], []
41+
for column in coords.T:
42+
axis, axis_index = np.unique(column, return_inverse=True)
43+
if axis.size < 2:
44+
return None
45+
axes.append(axis)
46+
axis_indices.append(axis_index.ravel())
47+
shape = tuple(axis.size for axis in axes)
48+
if np.prod(shape) != values.size:
49+
return None
50+
flat_index = np.ravel_multi_index(axis_indices, shape)
51+
if np.unique(flat_index).size != flat_index.size:
52+
return None
53+
volume = np.empty(values.size, dtype=float)
54+
volume[flat_index] = values
55+
return axes, volume.reshape(shape)
56+
2857
def griddata(self, min_max_dep, min_max_lat, min_max_lon, n_rtp):
2958
"""Linearly interpolate velocity into regular grids
3059
60+
If the input points form a complete regular lon/lat/dep grid,
61+
trilinear interpolation is used, which is much faster than
62+
Delaunay-based interpolation. Otherwise the points are treated as
63+
scattered and interpolated by :func:`scipy.interpolate.griddata`.
64+
Grid nodes outside the input model take the value of the nearest
65+
interpolated node.
66+
3167
:param min_max_dep: min and max depth, ``[min_dep, max_dep]``
3268
:type min_max_dep: list
3369
:param min_max_lat: Min and max latitude, ``[min_lat, max_lat]``
@@ -45,13 +81,32 @@ def griddata(self, min_max_dep, min_max_lat, min_max_lon, n_rtp):
4581

4682
# Grid data
4783
new_dep, new_lat, new_lon = np.meshgrid(self.dd, self.tt, self.pp, indexing='ij')
48-
self.log.Modellog.info('Grid data, please wait for a few minutes')
49-
grid_vp = griddata(
50-
self.points[:, [2,1,0]],
51-
self.points[:, 3],
52-
(new_dep, new_lat, new_lon),
53-
method='linear'
54-
)
84+
coords = self.points[:, [2, 1, 0]]
85+
values = self.points[:, 3]
86+
regular_grid = self._to_regular_grid(coords, values)
87+
if regular_grid is not None:
88+
axes, volume = regular_grid
89+
self.log.Modellog.info(
90+
'Input model is on a regular grid, using trilinear interpolation'
91+
)
92+
interpolator = RegularGridInterpolator(
93+
axes, volume, method='linear',
94+
bounds_error=False, fill_value=np.nan
95+
)
96+
grid_vp = interpolator(
97+
np.stack([new_dep, new_lat, new_lon], axis=-1)
98+
)
99+
else:
100+
self.log.Modellog.info(
101+
'Input model is scattered, grid data with Delaunay '
102+
'triangulation, please wait for a few minutes'
103+
)
104+
grid_vp = griddata(
105+
coords,
106+
values,
107+
(new_dep, new_lat, new_lon),
108+
method='linear'
109+
)
55110

56111
# Set NaN to nearest value
57112
vel = ignore_nan_3d(grid_vp)

‎pytomoatt/src_rec.py‎

Lines changed: 188 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -257,9 +257,10 @@ def read(
257257
conflicting receiver location and stops reading; ``"remove"``
258258
removes all observations involving those receiver names;
259259
``"max_count"`` keeps the location with the highest occurrence
260-
count and removes observations at other locations; and
261-
``"rename"`` keeps the locations and appends ``_A``, ``_B``, ...
262-
to distinguish them.
260+
count and removes observations at other locations; ``"average"``
261+
replaces all conflicting locations by their count-weighted mean
262+
location; and ``"rename"`` keeps the locations and appends ``_A``,
263+
``_B``, ... to distinguish them.
263264
:type conflicting_receiver_action: str
264265
:return: class of SrcRec
265266
:rtype: SrcRec
@@ -269,12 +270,13 @@ def read(
269270
"remove",
270271
"rename",
271272
"max_count",
273+
"average",
272274
}
273275
if conflicting_receiver_action not in valid_conflicting_receiver_actions:
274276
raise ValueError(
275277
"Invalid conflicting_receiver_action: "
276278
f"{conflicting_receiver_action!r}. Supported actions are "
277-
"'error', 'remove', 'rename', and 'max_count'."
279+
"'error', 'remove', 'rename', 'max_count', and 'average'."
278280
)
279281

280282
sr = cls(fname=fname, **kwargs)
@@ -745,17 +747,19 @@ def update_unique_src_rec(self, conflicting_receiver_action="error"):
745747
:class:`ValueError` containing all conflicting locations;
746748
``"remove"`` removes all observations involving those names;
747749
``"max_count"`` keeps the location with the highest occurrence
748-
count and removes observations at other locations; and
749-
``"rename"`` appends ``_A``, ``_B``, ... to each distinct
750+
count and removes observations at other locations; ``"average"``
751+
replaces all conflicting locations by their count-weighted mean
752+
location, so that locations observed more often contribute more;
753+
and ``"rename"`` appends ``_A``, ``_B``, ... to each distinct
750754
location.
751755
:type conflicting_receiver_action: str
752756
"""
753-
valid_actions = {"error", "remove", "rename", "max_count"}
757+
valid_actions = {"error", "remove", "rename", "max_count", "average"}
754758
if conflicting_receiver_action not in valid_actions:
755759
raise ValueError(
756760
"Invalid conflicting_receiver_action: "
757761
f"{conflicting_receiver_action!r}. Supported actions are "
758-
"'error', 'remove', 'rename', and 'max_count'."
762+
"'error', 'remove', 'rename', 'max_count', and 'average'."
759763
)
760764

761765
# get sources
@@ -831,6 +835,30 @@ def update_unique_src_rec(self, conflicting_receiver_action="error"):
831835
"Kept max-count receiver locations and removed "
832836
f"other conflicting locations:\n{kept_receivers}"
833837
)
838+
elif conflicting_receiver_action == "average":
839+
average_map = self._build_average_receiver_location_map(
840+
receiver_rows,
841+
conflicting_receiver_names,
842+
)
843+
self._set_receiver_records_location(average_map)
844+
self._drop_stale_distaz_columns()
845+
averaged_receivers = pd.DataFrame(
846+
[
847+
{
848+
"staname": name,
849+
"stla": latitude,
850+
"stlo": longitude,
851+
"stel": elevation,
852+
}
853+
for name, (latitude, longitude, elevation)
854+
in average_map.items()
855+
]
856+
).to_string(index=False)
857+
self.log.SrcReclog.warning(
858+
f"{conflict_message}\n"
859+
"Replaced conflicting locations by their count-weighted "
860+
f"mean location:\n{averaged_receivers}"
861+
)
834862
else:
835863
rename_map = self._build_conflicting_receiver_rename_map(
836864
receiver_rows,
@@ -926,6 +954,106 @@ def _remove_receiver_records_except_location(
926954
receiver_records.drop(index=receiver_records.index[~keep], inplace=True)
927955
receiver_records.reset_index(drop=True, inplace=True)
928956

957+
@staticmethod
958+
def _build_average_receiver_location_map(
959+
receiver_rows,
960+
conflicting_receiver_names,
961+
):
962+
"""Map each conflicting receiver name to its count-weighted mean location."""
963+
average_map = {}
964+
for receiver_name in conflicting_receiver_names:
965+
locations = receiver_rows.loc[
966+
receiver_rows["staname"].astype(str) == receiver_name,
967+
["stla", "stlo", "stel", "count"],
968+
]
969+
counts = locations["count"].to_numpy(dtype=float)
970+
average_map[receiver_name] = (
971+
float(np.average(
972+
locations["stla"].to_numpy(dtype=float), weights=counts
973+
)),
974+
SrcRec._weighted_mean_longitude(
975+
locations["stlo"].to_numpy(dtype=float), counts
976+
),
977+
float(np.average(
978+
locations["stel"].to_numpy(dtype=float), weights=counts
979+
)),
980+
)
981+
return average_map
982+
983+
@staticmethod
984+
def _weighted_mean_longitude(longitudes, weights):
985+
"""Weighted mean of longitudes that stays correct across the dateline.
986+
987+
Longitudes are unwrapped around the highest-weight longitude before
988+
averaging, so 179 and -179 average to 180 rather than 0. The result
989+
is returned in the input convention: [0, 360] if any input exceeds
990+
180, otherwise [-180, 180].
991+
"""
992+
longitudes = np.asarray(longitudes, dtype=float)
993+
weights = np.asarray(weights, dtype=float)
994+
reference = longitudes[np.argmax(weights)]
995+
unwrapped = reference + (
996+
(longitudes - reference + 180.0) % 360.0 - 180.0
997+
)
998+
mean = float(np.average(unwrapped, weights=weights))
999+
lower, upper = (0.0, 360.0) if (longitudes > 180.0).any() \
1000+
else (-180.0, 180.0)
1001+
if mean < lower:
1002+
mean += 360.0
1003+
elif mean > upper:
1004+
mean -= 360.0
1005+
return mean
1006+
1007+
_DISTAZ_COLUMNS = ("dist_deg", "dist_km", "dist_3d_km", "az", "baz")
1008+
1009+
def _drop_stale_distaz_columns(self):
1010+
"""Drop distance/azimuth columns after receiver locations change.
1011+
1012+
Methods that need them recalculate them with :meth:`calc_distaz`
1013+
when the columns are missing.
1014+
"""
1015+
stale_columns = [
1016+
column for column in self._DISTAZ_COLUMNS
1017+
if column in self.rec_points.columns
1018+
]
1019+
if stale_columns:
1020+
self.rec_points.drop(columns=stale_columns, inplace=True)
1021+
self.log.SrcReclog.warning(
1022+
"Receiver locations changed; dropped stale columns "
1023+
f"{stale_columns}. They will be recalculated when needed."
1024+
)
1025+
1026+
@staticmethod
1027+
def _set_receiver_location(
1028+
receiver_records,
1029+
name_col,
1030+
latitude_col,
1031+
longitude_col,
1032+
elevation_col,
1033+
location_map,
1034+
):
1035+
"""Overwrite receiver locations by name for one record column set."""
1036+
if receiver_records.empty:
1037+
return
1038+
receiver_names = receiver_records[name_col].astype(str)
1039+
for receiver_name, location in location_map.items():
1040+
name_mask = receiver_names == receiver_name
1041+
if not name_mask.any():
1042+
continue
1043+
for column, value in zip(
1044+
(latitude_col, longitude_col, elevation_col), location
1045+
):
1046+
receiver_records.loc[name_mask, column] = value
1047+
1048+
def _set_receiver_records_location(self, location_map):
1049+
"""Apply one location per receiver name to all record types."""
1050+
for receiver_records, field_names in self._iter_receiver_fields():
1051+
self._set_receiver_location(
1052+
receiver_records,
1053+
*field_names,
1054+
location_map,
1055+
)
1056+
9291057
def _remove_receiver_records_except_locations(self, keep_map):
9301058
"""Remove non-max-count receiver locations from all record types."""
9311059
for receiver_records, field_names in self._iter_receiver_fields():
@@ -1287,21 +1415,20 @@ def remove_rec_by_new_src(self,):
12871415
def remove_src_by_new_rec(self):
12881416
"""
12891417
remove ``src_points`` by new receivers
1418+
1419+
A source is kept if it is referenced by any remaining absolute,
1420+
common-source, or common-receiver record, including the second
1421+
event (``event_id2``) of a common-receiver record.
12901422
"""
1291-
self.src_points = self.src_points[
1292-
self.src_points.index.isin(self.rec_points["src_index"])
1293-
]
1294-
if not self.rec_points_cr.empty:
1295-
self.src_points = pd.concat(
1296-
[self.src_points, self.src_points[
1297-
self.src_points.index.isin(self.rec_points_cr["src_index"])
1298-
]])
1423+
keep = self.src_points.index.isin(self.rec_points["src_index"])
12991424
if not self.rec_points_cs.empty:
1300-
self.src_points = pd.concat(
1301-
[self.src_points, self.src_points[
1302-
self.src_points.index.isin(self.rec_points_cs["src_index"])
1303-
]])
1304-
self.src_points = self.src_points.drop_duplicates()
1425+
keep |= self.src_points.index.isin(self.rec_points_cs["src_index"])
1426+
if not self.rec_points_cr.empty:
1427+
keep |= self.src_points.index.isin(self.rec_points_cr["src_index"])
1428+
keep |= self.src_points["event_id"].isin(
1429+
self.rec_points_cr["event_id2"]
1430+
).to_numpy()
1431+
self.src_points = self.src_points[keep]
13051432

13061433
def update_num_rec(self):
13071434
"""
@@ -1562,6 +1689,46 @@ def remove_specified_recs(self, rec_list, **kwargs):
15621689
"receiver records after removing: {}".format(self._count_records())
15631690
)
15641691

1692+
def _keep_receiver_records(self, rec_list):
1693+
"""Keep only named receivers in all record types."""
1694+
receiver_names = {str(receiver_name) for receiver_name in rec_list}
1695+
for receiver_records, field_names in self._iter_receiver_fields():
1696+
if receiver_records.empty:
1697+
continue
1698+
name_col = field_names[0]
1699+
remove_mask = ~receiver_records[name_col].astype(str).isin(
1700+
receiver_names
1701+
)
1702+
receiver_records.drop(
1703+
index=receiver_records.index[remove_mask],
1704+
inplace=True,
1705+
)
1706+
receiver_records.reset_index(drop=True, inplace=True)
1707+
1708+
def select_by_rec_names(self, rec_list, **kwargs):
1709+
"""Select receivers by name and remove others
1710+
1711+
Only observations of receivers in ``rec_list`` are retained in
1712+
absolute, common-source, and common-receiver records. A
1713+
common-source record is kept only if both of its receivers are
1714+
listed in ``rec_list``.
1715+
1716+
:param rec_list: Name(s) of receivers to be retained
1717+
:type rec_list: list or str
1718+
"""
1719+
if not isinstance(rec_list, (list, tuple, set, pd.Series, np.ndarray, str)):
1720+
raise TypeError("rec_list should be in list or str")
1721+
if isinstance(rec_list, str):
1722+
rec_list = [rec_list]
1723+
self.log.SrcReclog.info(
1724+
"receiver records before selection: {}".format(self._count_records())
1725+
)
1726+
self._keep_receiver_records(rec_list)
1727+
self.update(**kwargs)
1728+
self.log.SrcReclog.info(
1729+
"receiver records after selection: {}".format(self._count_records())
1730+
)
1731+
15651732
def select_by_box_region(self, region, **kwargs):
15661733
"""
15671734
Select sources and station in a box region

0 commit comments

Comments
 (0)