@@ -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