示例#1
0
文件: util.py 项目: larean/obsinfo
def create_comments(temp):

    # gerer le cas de str et dict (pour le champ processing)
    if type(temp) in [str, dict]:
        return [obspy_util.Comment(temp)]
    comments = []
    for id, comment in enumerate(temp):
        value = comment["value"] if "value" in comment else comment
        begin_effective_time = (comment["BeginEffectiveTime"]
                                if "BeginEffectiveTime" in comment else None)
        end_effective_time = (comment["EndEffectiveTime"]
                              if "EndEffectiveTime" in comment else None)
        authors = create_authors(comment) if "authors" in comment else None
        comments.append(
            obspy_util.Comment(
                value,
                begin_effective_time=begin_effective_time,
                end_effective_time=end_effective_time,
                authors=authors,
            ))
    return comments
示例#2
0
def comments(comments,
             clock_corrections,
             supplements,
             loc_code,
             location,
             debug=False):
    """
    Create obspy comments from station information
    
    Also stuffs fields that are otherwise not put into StationXML:
         "supplement" elements as JSON strings, 
          "location:location_methods" 
    """
    obspy_comments = []
    if debug:
        print("supplements=", end='')
        print(supplements)
    for comment in comments:
        obspy_comments.append(obspy_util.Comment(comment))
    if supplements:
        for key, val in supplements.items():
            obspy_comments.append(obspy_util.Comment(json.dumps({key: val})))
    if clock_corrections:
        for key, val in clock_corrections.items():
            obspy_comments.append(
                obspy_util.Comment(json.dumps({"clock_correction": {
                    key: val
                }})))
    else:
        obspy_comments.append(
            obspy_util.Comment(json.dumps({"clock_correction": None})))
    loc_comment = 'Using location "{}"'.format(loc_code)
    if 'localisation_method' in location:
        loc_comment = loc_comment + ', localised using : {}'.format(
            location['localisation_method'])
    obspy_comments.append(obspy_util.Comment(loc_comment))
    return obspy_comments
示例#3
0
 def __make_obspy_network(self,stations,debug=False):
     """Make an obspy network object with a subset of stations"""
     obspy_stations=[]    
     for station in stations:
         obspy_stations.append(station.make_obspy_station())
 
     temp=self.network_info.comments
     if temp:
         comments=[]
         for comment in temp:
             comments.append(obspy_util.Comment(comment))
     my_net = obspy_inventory.network.Network(
                         self.network_info.code,
                         obspy_stations,
                         description = self.network_info.description,
                         comments =    comments,
                         start_date =  self.network_info.start_date,
                         end_date   =  self.network_info.end_date
                     )
     return my_net
示例#4
0
    def make_obspy_station(self,debug=False):
        """
        Create an obspy station object from a fully informed station
        """
        # CREATE CHANNELS

        #if debug:
        #    print(self)
        channels=[]
        resource_id=self.instrument.resource_id
        for key,chan in self.instrument.das_components.items():
            if debug:
                print(key)
                print(yaml.dump(chan))
            response=oi_obspy.response(chan['response'])
            #loc_code=key.split(':')[1]
            loc_code=chan['location_code']
            try:
                location = self.locations[loc_code]
            except:
                print(f'location code {loc_code} not found in self.locations, valid keys are:');
                for key in self.locations.keys():
                    print(key)
                sys.exit(2)
            obspy_lon,obspy_lat = oi_obspy.lon_lats(location)
            azimuth,dip=oi_misc.get_azimuth_dip(
                                        chan['sensor'].seed_codes,
                                        chan['orientation_code'])
            start_date=None
            end_date=None
            # Give at least 3 seconds margin around start and end dates
            if hasattr(self,'start_date'):
                if self.start_date:
                    try:
                        start_date=round_down_minute(UTCDateTime(self.start_date),3)
                    except:
                        print(f"There is a problem with the station start date: {self.start_date}")
                        sys.exit(2)
            if hasattr(self,'end_date'):
                if self.end_date:
                    #print(self.end_date)
                    #print(UTCDateTime(self.end_date))
                    try:
                        end_date=round_up_minute(UTCDateTime(self.end_date),3)
                    except:
                        print(f"There is a problem with the station end date: {self.end_date}")
                        sys.exit(2)
            if debug:
                print(key)
                print(yaml.dump(chan))
            #print(location)
            if 'localisation_method' in location:
                channel_comment=obspy_util.Comment('Localised using : {}'.format(
                        location['localisation_method']))
            channel_code=make_channel_code(chan['sensor'].seed_codes,
                                            chan['band_code'],
                                            chan['inst_code'],
                                            chan['orientation_code'],
                                            chan['sample_rate'])
            channel = obspy_inventory.channel.Channel(
                    code = channel_code,
                    location_code  = loc_code,
                    latitude  = obspy_lat,
                    longitude = obspy_lon,
                    elevation = obspy_types.FloatWithUncertaintiesAndUnit(
                                        location['position'][2],
                                        lower_uncertainty=location['uncertainties.m'][2],
                                        upper_uncertainty=location['uncertainties.m'][2]),
                    depth     = location['depth.m'],
                    azimuth   = obspy_types.FloatWithUncertainties(
                                        azimuth[0],
                                        lower_uncertainty=azimuth[1],
                                        upper_uncertainty=azimuth[1]),
                    dip       = dip[0],
                    types      =['CONTINUOUS','GEOPHYSICAL'],
                    sample_rate=chan['sample_rate'], 
                    clock_drift_in_seconds_per_sample=1/(1e8*float(chan['sample_rate'])),
                    sensor     =oi_obspy.equipment(chan['sensor'].equipment),
                    pre_amplifier=oi_obspy.equipment(chan['preamplifier'].equipment),
                    data_logger=oi_obspy.equipment(chan['datalogger'].equipment),
                    equipment  =None,
                    response   =response,
                    description=None,
                    comments=[channel_comment],
                    start_date = start_date,
                    end_date   = end_date,
                    restricted_status = None,
                    alternate_code=None,
                    data_availability=None
                )
            channels.append(channel)
            if debug:
                print(yaml.dump(channel))
        # CREATE STATION
        station_loc_code=self.station_location
        if station_loc_code in self.locations:
            sta_loc=self.locations[station_loc_code]
            obspy_lon,obspy_lat = oi_obspy.lon_lats(sta_loc)
        else:
            print ("No valid location code for station, either set station_location_code or provide a location '00'")
            sys.exit()
    
    
        obspy_comments = oi_obspy.comments(
                        self.comments,
                        self.clock_corrections,
                        self.supplements,
                        station_loc_code,
                        sta_loc
                    )
        # DEFINE Operator
        agency=self.operator['full_name']
        contacts=None
        if 'email' in self.operator:
            contacts=[obspy_util.Person(emails=[self.operator['email']])]
        website=self.operator.get('website',None)
        operator = obspy_util.Operator([agency],contacts,website)
    
        if debug:
            print(obspy_comments)
        sta=obspy_inventory.station.Station(
                    code      = self.code,
                    latitude  = obspy_lat,
                    longitude = obspy_lon,
                    elevation = obspy_types.FloatWithUncertaintiesAndUnit(
                                        sta_loc['position'][2],
                                        lower_uncertainty=sta_loc['uncertainties.m'][2],
                                        upper_uncertainty=sta_loc['uncertainties.m'][2]),
                    channels = channels,
                    site     = obspy_util.Site(getattr(self,'site','')),
                    vault    = sta_loc['vault'],
                    geology  = sta_loc['geology'],
                    equipments= [oi_obspy.equipment(self.instrument.equipment)],
                    operators=[operator],
                    creation_date=start_date,   # Necessary for obspy to write StationXML
                    termination_date=end_date,
                    description=None,
                    comments = obspy_comments,
                    start_date = start_date,
                    end_date   = end_date,
                    restricted_status = None,
                    alternate_code=None,
                    data_availability=None,
                )
        if debug:
            print(sta)
        return sta
示例#5
0
    def make_obspy_station(self, debug=False):
        """
        Create an obspy station object from a fully informed station
        """
        # CREATE CHANNELS

        # if debug:
        #    print(self)
        channels = []
        for instrument in self.instruments:
            # resource_id = instrument.resource_id
            for key, chan in instrument.das_components.items():
                if debug:
                    print(key)
                    print(yaml.dump(chan))
                response = oi_obspy.response(chan["response"])
                # loc_code=key.split(':')[1]
                loc_code = chan["location_code"]
                try:
                    location = self.locations[loc_code]
                except KeyError:
                    print(f"location code {loc_code} not found in ")
                    print("self.locations, valid keys are:")
                    for key in self.locations.keys():
                        print(key)
                    sys.exit(2)
                obspy_lon, obspy_lat = oi_obspy.lon_lats(location)
                azi, dip = oi_misc.get_azimuth_dip(chan["sensor"].seed_codes,
                                                   chan["orientation_code"])
                start_date = None
                end_date = None
                start_date_chan = None
                end_date_chan = None
                # Give at least 3 seconds margin around start and end dates

                if "start_date" in chan:
                    start_date_chan = UTCDateTime(chan["start_date"])

                if self.start_date:
                    start_date = UTCDateTime(self.start_date)

                if "end_date" in chan:
                    end_date_chan = UTCDateTime(chan["end_date"])

                if self.end_date:

                    end_date = UTCDateTime(self.end_date)

                if debug:
                    print(key)
                    print(yaml.dump(chan))
                # print(location)
                if "localisation_method" in location:
                    channel_comment = obspy_util.Comment(
                        "Localised using : {}".format(
                            location["localisation_method"]))
                else:
                    channel_comment = None
                channel_code = make_channel_code(
                    chan["sensor"].seed_codes,
                    chan["band_code"],
                    chan["inst_code"],
                    chan["orientation_code"],
                    chan["datalogger"].sample_rate,
                )
                start_date = start_date_chan if start_date_chan else start_date
                channel = obspy_inventory.channel.Channel(
                    code=channel_code,
                    location_code=loc_code,
                    latitude=obspy_lat,
                    longitude=obspy_lon,
                    elevation=obspy_types.FloatWithUncertaintiesAndUnit(
                        location["position"]["elev"],
                        lower_uncertainty=location["uncertainties.m"]["elev"],
                        upper_uncertainty=location["uncertainties.m"]["elev"],
                    ),
                    depth=location["depth.m"],
                    azimuth=obspy_types.FloatWithUncertainties(
                        azi[0],
                        lower_uncertainty=azi[1] if len(azi) == 2 else 0,
                        upper_uncertainty=azi[1] if len(azi) == 2 else 0,
                    ),
                    dip=dip[0],
                    types=["CONTINUOUS", "GEOPHYSICAL"],
                    sample_rate=chan["datalogger"].sample_rate,
                    clock_drift_in_seconds_per_sample=1 /
                    (1e8 * float(chan["datalogger"].sample_rate)),
                    sensor=oi_obspy.equipment(chan["sensor"].equipment),
                    pre_amplifier=oi_obspy.equipment(
                        chan["preamplifier"].equipment)
                    if "preamplifier" in chan else None,
                    data_logger=oi_obspy.equipment(
                        chan["datalogger"].equipment),
                    equipments=None,
                    response=response,
                    description=None,
                    comments=[channel_comment] if channel_comment else None,
                    start_date=start_date,
                    end_date=end_date_chan if end_date_chan else end_date,
                    restricted_status=None,
                    alternate_code=None,
                    data_availability=None,
                )
                channels.append(channel)
                if debug:
                    print(yaml.dump(channel))
            # CREATE STATION
            station_loc_code = self.station_location  # david
            if station_loc_code in self.locations:
                sta_loc = self.locations[station_loc_code]
                obspy_lon, obspy_lat = oi_obspy.lon_lats(sta_loc)
            else:
                print("No valid location code for station, either ", end='')
                print("set station_location_code or provide a location '00'")
                sys.exit()

            obspy_comments = oi_obspy.comments(
                self.comments,
                self.processing,
                self.supplements,
                station_loc_code,
                sta_loc,
            )

            # DEFINE Operator
            agency = self.operator["full_name"]
            contacts = None
            if "email" in self.operator:
                contacts = [obspy_util.Person(emails=[self.operator["email"]])]
            website = self.operator.get("website", None)
            operator = obspy_util.Operator(agency, contacts, website)

            if debug:
                print(obspy_comments)
            sta = obspy_inventory.station.Station(
                code=self.code,
                latitude=obspy_lat,
                longitude=obspy_lon,
                elevation=obspy_types.FloatWithUncertaintiesAndUnit(
                    sta_loc["position"]["elev"],
                    lower_uncertainty=sta_loc["uncertainties.m"]["elev"],
                    upper_uncertainty=sta_loc["uncertainties.m"]["elev"],
                ),
                channels=channels,
                site=obspy_util.Site(getattr(self, "site", "")),
                vault=sta_loc["vault"],
                geology=sta_loc["geology"],
                equipments=[
                    oi_obspy.equipment(instrument.equipment)
                    for instrument in self.instruments
                ],
                operators=[operator],
                creation_date=start_date,  # Needed to write StationXML
                termination_date=end_date,
                description=None,
                comments=obspy_comments,
                start_date=start_date if start_date else None,
                end_date=end_date if end_date else None,
                restricted_status=None,
                alternate_code=None,
                data_availability=None,
            )
        if debug:
            print(sta)
        return sta