Example #1
0
 def map_stamag2stationmagnitude(self, db):
     """
     Map stamag record to StationMagnitude
     """
     originID_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())
     stamagID_rid = "{0}/{1}-{2}-{3}-{4}".format(
         'stamag',
         db.get('sta'),
         db.get('magtype'),
         db.get('orid') or uuid.uuid4(),
         db.get('magid') or uuid.uuid4(),
     )
     
     stationmagnitude = Dict([
         ('@publicID', self._uri(stamagID_rid)),
         ('mag', Dict([
             ('value', db.get('magnitude')),
             ('uncertainty', db.get('uncertainty')),
             ]),
         ),
         ('type', db.get('magtype')),
         ('creationInfo', Dict([
             ('creationTime', self._utc(db.get('lddate'))),
             ('agencyID', self.agency),
             ('author', db.get('auth')),
             ('version', db.get('magid')),
             ]),
         ),
         ('originID', self._uri(originID_rid)),
     ])
     return stationmagnitude
Example #2
0
 def map_event(self, db, anss=False):
     """
     Create a QML Event from a CSS event
     (will also accept a CSS origin row dict)
     """
     evid = db.get('evid')
     lddate = db.get('lddate') or _ts(datetime.datetime.utcnow())
     prefor = db.get('prefor') or db.get('orid')
     eventID_rid = "{0}/{1}".format('event', evid)
     
     event = Dict([
         ('@publicID', self._uri(eventID_rid)),
         ('type', "not reported"),
         ('creationInfo', Dict([
             ('creationTime', self._utc(lddate)),
             ('agencyID', self.agency),
             ('version', str(evid)),
             ])
         ),
     ])
     # Set the prefor if you gave on origin or the event table has one
     if prefor:
         originID_rid = "{0}/{1}".format('origin', prefor)
         event['preferredOriginID'] = self._uri(originID_rid)
     #
     # Add the ANSS NS parameters automatically
     #
     if anss:
         cat_event_attr = anss_params(self.agency, evid)
         event.update(cat_event_attr)
     return event
Example #3
0
    def map_assoc2arrival(self, db):
        """
        Experimental to map CSS assoc just to QML arrival

        Inputs
        ======
        db : dict of key/values of CSS fields related to the phases (see Join)

        Returns
        =======
        dict of QuakeML Arrival type

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.

        Join
        ----
        assoc
        """
        css_timedef = _str(db.get('timedef'))
        pickID_rid = "{0}/{1}".format('arrival',
                                      db.get('arid') or uuid.uuid4())
        vmodelID_rid = "{0}/{1}".format('vmodel',
                                        db.get('vmodel') or uuid.uuid4())
        assocID_rid = "{0}/{1}-{2}".format(
            'assoc',
            db.get('orid') or uuid.uuid4(),
            db.get('arid') or uuid.uuid4(),
        )

        arrival = Dict([
            ('@publicID', self._uri(assocID_rid)),
            ('pickID', self._uri(pickID_rid)),
            ('phase', db.get('phase')),
            ('azimuth', db.get('esaz')),
            ('distance', db.get('delta')),
            ('timeResidual', db.get('timeres')),
            ('timeWeight', db.get('wgt')),
            ('earthModelID', self._uri(vmodelID_rid, schema="smi")),
            ('creationInfo',
             Dict([
                 ('creationTime', self._utc(db.get('lddate'))),
                 ('agencyID', self.agency),
                 ('version', db.get('arid')),
             ])),
            # ('css:timedef', css_timedef),
        ])

        # Assign a default weight based on timedef if none in db
        if arrival.get('timeWeight') is None:
            arrival['timeWeight'] = TIMEDEF_WEIGHT.get(css_timedef)

        return arrival
Example #4
0
    def map_origin2magnitude(self, db, mtype='ml'):
        """
        Return a dict of magnitude from an dict of CSS key/values
        corresponding to one record.

        Inputs
        ======
        db : dict of key/values of CSS fields from the 'origin' table
        mtype : str of valid field from origin to use as mag ('ml', 'mb') etc

        Returns
        =======
        dict of key/values of QuakeML fields of "magnitude"

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.
        """
        agency, author, _, _, _ = self.split_auth(_str(db.get('auth')))
        mode, status = self.get_event_status(author)

        origin_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())

        # If foreign key to netmag table exists, use it as a unique id,
        # otherwise unique id is unique origin + local field
        netmagid = "{0}id".format(mtype)
        if db.get(netmagid):
            origmag_rid = "{0}/{1}".format('netmag', db.get(netmagid))
            public_uri = self._uri(origmag_rid)
        else:
            public_uri = self._uri(origin_rid, local_id=mtype)

        magnitude = Dict([
            ('@publicID', public_uri),
            ('mag', _quan(value=db.get(mtype))),
            ('type', mtype),
            ('originID', self._uri(origin_rid)),
            ('evaluationMode', mode),
            ('evaluationStatus', status),
            (
                'creationInfo',
                Dict([
                    ('creationTime', self._utc(db.get('lddate'))),
                    ('agencyID', self.agency or agency),
                    ('author', author),
                    # ('version', db.get('orid')),
                ])),
        ])
        return magnitude
Example #5
0
    def map_stamag2stationmagnitude(self, db):
        """
        Map stamag record to StationMagnitude
        """
        agency, author, _, method, info = self.split_auth(_str(db.get('auth')))

        css_sta = db.get('sta')
        css_chan = db.get('chan')
        wf_rid = "{0}/{1}-{2}-{3}".format(
            'wfdisc',
            css_sta,
            css_chan,
            int(db.get('time') * 10**6),
        )
        origin_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())
        stamag_rid = "{0}/{1}-{2}-{3}-{4}".format(
            'stamag',
            db.get('sta'),
            db.get('magtype'),
            db.get('orid') or uuid.uuid4(),
            db.get('magid') or uuid.uuid4(),
        )

        stationmagnitude = Dict([
            ('@publicID', self._uri(stamag_rid)),
            ('mag',
             Dict([('value', db.get('magnitude')),
                   ('uncertainty', db.get('uncertainty'))])),
            (
                'waveformID',
                Dict([
                    ('@stationCode', db.get('fsta') or css_sta),
                    ('@channelCode', db.get('fchan') or css_chan),
                    ('@networkCode', db.get('snet') or self.default_network),
                    ('@locationCode', db.get('loc') or ""),
                    ('#text', self._uri(wf_rid, schema="smi")),
                    # 'resourceURI' in schema
                ])),
            ('type', db.get('magtype')),
            (
                'creationInfo',
                Dict([
                    ('creationTime', self._utc(db.get('lddate'))),
                    ('agencyID', agency if agency != '' else self.agency),
                    ('author', author),
                    # ('version', db.get('magid')),
                ])),
            ('originID', self._uri(origin_rid)),
        ])
        return stationmagnitude
Example #6
0
    def map_netmag2magnitude(self, db):
        """
        Return a dict of QuakeML magnitude from a dict of CSS key/values
        corresponding to one record.

        Inputs
        ======
        db : dict of key/values of CSS fields from the 'netmag' table

        Returns
        =======
        dict of key/values of QuakeML fields of "magnitude"

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.
        """
        # TODO: add station_magnitude_contributions
        posted_author = _str(db.get('auth'))
        mode, status = self.get_event_status(posted_author)
        originID_rid = "{0}/{1}".format('origin',
                                        db.get('orid') or uuid.uuid4())
        netmagID_rid = "{0}/{1}".format('netmag',
                                        db.get('magid') or uuid.uuid4())

        magnitude = Dict([
            ('@publicID', self._uri(netmagID_rid)),
            ('mag',
             _quan([
                 ('value', db.get('magnitude')),
                 ('uncertainty', db.get('uncertainty')),
             ])),
            ('type', db.get('magtype')),
            ('stationCount', db.get('nsta')),
            ('originID', self._uri(originID_rid)),
            ('evaluationMode', mode),
            ('evaluationStatus', status),
            ('creationInfo',
             Dict([
                 ('creationTime', self._utc(db.get('lddate'))),
                 ('agencyID', self.agency),
                 ('author', posted_author),
                 ('version', db.get('magid')),
             ])),
        ])
        return magnitude
Example #7
0
def _dict(*args, **kwargs):
    """
    Return a dict only if at least one value is not None
    """
    dict_ = Dict(*args, **kwargs)
    if dict_.values() == [None] * len(dict_):
        return None
    return dict_
Example #8
0
def _quan(*args, **kwargs):
    """
    Return a dict only if the value for key "value" is not None
    """
    dict_ = Dict(*args, **kwargs)
    if dict_.get('value') is None:
        return None
    return dict_
Example #9
0
    def description(nearest_string, type="nearest cities"):
        """
        Return a dict eventDescription of type 'nearest cities'

        Inputs
        ======
        nearest_string : str of decription for the text field
        """
        return Dict(text=nearest_string, type=type)
Example #10
0
 def map_stamag2stationmagnitude(self, db):
     """
     Map stamag record to StationMagnitude
     """
     def_net = self.agency[:2].upper()
     originID_rid = "{0}/{1}".format('origin',
                                     db.get('orid') or uuid.uuid4())
     stamagID_rid = "{0}/{1}-{2}-{3}-{4}".format(
         'stamag',
         db.get('sta'),
         db.get('magtype'),
         db.get('orid') or uuid.uuid4(),
         db.get('magid') or uuid.uuid4(),
     )
     # TODO: add amplitude_id, method_id
     # TODO: add comments (if remark table/commid available)
     stationmagnitude = Dict([
         ('@publicID', self._uri(stamagID_rid)),
         ('mag',
          Dict([('value', db.get('magnitude')),
                ('uncertainty', db.get('uncertainty'))])),
         (
             'waveformID',
             Dict([
                 ('@stationCode', db.get('sta')),
                 ('@channelCode', db.get('chan') or ""),  # not in stamag
                 ('@networkCode', def_net),
                 ('@locationCode', db.get('loc') or ""),  # not in stamag
                 ('#text', self._uri(stamagID_rid, schema="smi")),
             ])),
         ('type', db.get('magtype')),
         ('creationInfo',
          Dict([
              ('creationTime', self._utc(db.get('lddate'))),
              ('agencyID', self.agency),
              ('author', db.get('auth')),
              ('version', db.get('magid')),
          ])),
         ('originID', self._uri(originID_rid)),
     ])
     return stationmagnitude
Example #11
0
    def map_mt2focalmech(self, db):
        """
        Map BRTT CSS table 'mt' record to a FocalMechanism
        
        Notes
        =====
        1) This should not be first choice, mt table lacks many attributes of a 
        moment tensor solution, only use if nothing else is available.

        2) This treats derived parameters weirdly, there can be an orid, but
        also derived lat/lon etc, which should be in the origin table? So this
        method uses orid as the triggering origin and ignores the derived
        origin parameters. A more comprehensive one would build
        origin/magnitude and make the necessary ID's but leaves that for other
        methods, i.e. map_mt2origin, map_mt2magnitude. There should be an "Mw"
        in the netmag table, not here.
        """
        originID_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())
        mtID_rid = "{0}/{1}".format('mt', db.get('mtid') or uuid.uuid4())
        
        # This is wrong in the GS feed, have to map to valid QuakeML enum
        # the right place for this is Quakeml -> mt table, but do it here
        # in case no one did on ETL.
        mode = dict([
            ('automatic', "automatic"),
            ('manual', "manual"),
            ('reviewed', "manual"),
        ]).get(db.get('rstatus')) # should be EvaluationModeType
        status = db.get('estatus') # should be EvaluationStatusType
        
        moment_tensor = Dict([
            ('@publicID', self._uri(mtID_rid, local_id="tensor")),
            ('derivedOriginID', self._uri(originID_rid)),
            ('scalarMoment', _quan(value=db.get('scm'))),
            ('doubleCouple', db.get('pdc')),
            ('tensor', Dict([
                ('Mrr', Dict(value=db.get('tmrr'))),
                ('Mtt', Dict(value=db.get('tmtt'))),
                ('Mpp', Dict(value=db.get('tmpp'))),
                ('Mrt', Dict(value=db.get('tmrt'))),
                ('Mrp', Dict(value=db.get('tmrp'))),
                ('Mtp', Dict(value=db.get('tmtp'))),
                ])
            ),
            ('creationInfo', Dict([
                ('creationTime', self._utc(db['lddate'])), 
                ('agencyID', self.agency),
                ('author', db.get('auth')),
                ('version', db.get('mtid')), 
                ])
            ),
        ])
        
        nodal_planes = Dict([
            ('nodalPlane1', Dict([
                ('strike', Dict(value = db.get('str1'))),
                ('dip', Dict(value = db.get('dip1'))),
                ('rake', Dict(value = db.get('rake1'))),
                ])
            ),
            ('nodalPlane2', Dict([
                ('strike', Dict(value = db.get('str2'))),
                ('dip', Dict(value = db.get('dip2'))),
                ('rake', Dict(value = db.get('rake2'))),
                ])
            ),
            ('@preferredPlane', 1),
        ])

        principal_axes = Dict([
            ('tAxis', Dict([
                ('azimuth', Dict(value = db.get('taxazm'))),
                ('plunge', Dict(value = db.get('taxplg'))),
                ('length', Dict(value = db.get('taxlength'))),
                ])
            ),
            ('pAxis', Dict([
                ('azimuth', Dict(value = db.get('paxazm'))),
                ('plunge', Dict(value = db.get('paxplg'))),
                ('length', Dict(value = db.get('paxlength'))),
                ])
            ),
            ('nAxis', Dict([
                ('azimuth', Dict(value = db.get('naxazm'))),
                ('plunge', Dict(value = db.get('naxplg'))),
                ('length', Dict(value = db.get('naxlength'))),
                ])
            ),
        ])
        
        focal_mechanism = Dict([
            ('@publicID', self._uri(mtID_rid, local_id="focalmech")),
            ('triggeringOriginID', self._uri(originID_rid)),
            ('nodalPlanes', nodal_planes),
            ('principalAxes', principal_axes),
            ('momentTensor', moment_tensor),
            ('creationInfo', Dict([
                ('creationTime', self._utc(db.get('lddate'))), 
                ('agencyID', self.agency),
                ('author', db.get('auth')),
                ('version', db.get('mtid')), 
                ])
            ),
            # These determined from auth?? or weird incorrect mt fields...
            ('evaluationMode', db.get('rstatus')),
            ('evaluationStatus', db.get('estatus')),
        ])
        return focal_mechanism
Example #12
0
    def map_fplane2focalmech(self, db):
        """
        Return a dict of focalMechanism from an dict of CSS key/values
        corresponding to one record. See the 'Join' section for the implied
        database join expected.
        
        Inputs
        ======
        db : dict of key/values of CSS fields from the 'fplane' table

        Returns
        =======
        dict of key/values of QuakeML "focalMechansim"

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.
        """
        #
        # NOTE: Antelope schema for this is wrong, no nulls defined
        # 
        originID_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())
        fplaneID_rid = "{0}/{1}".format('fplane', db.get('mechid') or uuid.uuid4())
        author_string = ':'.join([db.get('algorithm'), db.get('auth')])
        
        # Determine from auth field
        mode, status = self.get_event_status(_str(db.get('auth')))

        nodal_planes = Dict([
            ('nodalPlane1', Dict([
                ('strike', Dict(value = db.get('str1'))),
                ('dip', Dict(value = db.get('dip1'))),
                ('rake', Dict(value = db.get('rake1'))),
                ])
            ),
            ('nodalPlane2', Dict([
                ('strike', Dict(value = db.get('str2'))),
                ('dip', Dict(value = db.get('dip2'))),
                ('rake', Dict(value = db.get('rake2'))),
                ])
            ),
            ('@preferredPlane', 1),
        ])

        principal_axes = Dict([
            ('tAxis', Dict([
                ('azimuth', Dict(value = db.get('taxazm'))),
                ('plunge', Dict(value = db.get('taxplg'))),
                ])
            ),
            ('pAxis', Dict([
                ('azimuth', Dict(value = db.get('paxazm'))),
                ('plunge', Dict(value = db.get('paxplg'))),
                ])
            ),
        ])

        focal_mechanism = Dict([
            ('@publicID', self._uri(fplaneID_rid)),
            ('triggeringOriginID', self._uri(originID_rid)),
            ('nodalPlanes', nodal_planes),
            ('principalAxes', principal_axes),
            ('creationInfo', Dict([
                ('creationTime', self._utc(db.get('lddate'))), 
                ('agencyID', self.agency),
                ('author', author_string),
                ('version', db.get('mtid')), 
                ])
            ),
            ('evaluationMode', mode),
            ('evaluationStatus', status),
        ])
        return focal_mechanism
Example #13
0
    def map_arrival2pick(self, db):
        """
        Experimental map of just CSS arrival to QML pick.
        
        IF snetsta and schanloc are joined, will use those for SEED SNCL.
        Otherwise, will just use your converter agencyID for net and the 
        sta/chan recorded with the pick.

        Inputs
        ======
        db : dict of key/values of CSS fields related to the phases (see Join)

        Returns
        =======
        dict of QuakeML schema for Pick type

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.
        
        Join
        ----
        arrival <- snetsta [sta] (outer) <- schanloc [sta chan] (outer)
        """
        def_net = self.agency[:2].upper()
        css_sta = db.get('sta')
        css_chan = db.get('chan')
        wfID_rid = "{0}/{1}-{2}-{3}".format(
            'wfdisc', 
            css_sta,
            css_chan,
            int(db.get('time') * 10**6),
        )
        pickID_rid = "{0}/{1}".format('arrival', db.get('arid') or uuid.uuid4())
        
        
        on_qual = _str(db.get('qual')).lower()
        if 'i' in on_qual:
            onset = "impulsive"
        elif 'e' in on_qual:
            onset = "emergent"
        elif 'w' in on_qual:
            onset = "questionable"
        else:
            onset =  None
        
        pol = _str(db.get('fm')).lower()
        if 'c' in pol or 'u' in pol:
            polarity = "positive"
        elif 'd' in pol or 'r' in pol:
            polarity = "negative"
        elif '.' in pol:
            polarity = "undecidable"
        else:
            polarity = None
        
        pick_mode = "automatic"
        if 'orbassoc' not in _str(db.get('auth')):
            pick_mode = "manual"
        
        pick_status = "preliminary"
        if pick_mode is "manual":
            pick_status = "reviewed"
        
        pick = Dict([
            ('@publicID', self._uri(pickID_rid)),
            ('time', _quan([
                ('value', self._utc(db.get('time'))),
                ('uncertainty', db.get('deltim')),
                ])
            ),
            ('waveformID', Dict([
                ('@stationCode', db.get('fsta') or css_sta), 
                ('@channelCode', db.get('fchan') or css_chan),
                ('@networkCode', db.get('snet') or def_net),
                ('@locationCode', db.get('loc') or ""),
                ('#text', self._uri(wfID_rid, schema="smi")),  #'resourceURI' in schema
                ])
            ),
            ('phaseHint', db.get('iphase')),  #'code' in schema
            ('polarity', polarity),
            ('onset', onset),
            ('backazimuth', _quan([
                ('value', db.get('azimuth')), 
                ('uncertainty', db.get('delaz'))
                ])
            ),
            ('horizontalSlowness', _quan([
                ('value', db.get('slow')), 
                ('uncertainty', db.get('delslo'))
                ])
            ),
            ('creationInfo', Dict([
                ('creationTime', self._utc(db.get('arrival.lddate') or db.get('lddate'))), 
                ('agencyID', self.agency), 
                ('author', db.get('auth')),
                ('version', db.get('arid')), 
                ])
            ),
            ('evaluationMode', pick_mode),
            ('evaluationStatus', pick_status),
        ])
        return pick
Example #14
0
    def map_origin2origin(self, db):
        """
        Return a dict of QuakeML origin from a dict of CSS key/values
        
        Inputs
        ======
        db : dict of key/values of CSS fields related to the origin (see Join)

        Returns
        =======
        dict of key/values of QuakeML fields of "origin"

        Notes
        =====
        Any object that supports the dict 'get' method can be passed as
        input, e.g. OrderedDict, custom classes, etc.
        
        Join
        ----
        origin <- origerr [orid] (outer)
        """
        css_etype = _str(db.get('etype'))
        posted_author = _str(db.get('auth'))
        mode, status = self.get_event_status(posted_author)
        originID_rid = "{0}/{1}".format('origin', db.get('orid') or uuid.uuid4())
        
        #-- Solution Uncertainties ----------------------------------
        # in CSS the ellipse is projected onto the horizontal plane
        # using the covariance matrix
        a = _km2m(db.get('smajax'))
        b = _km2m(db.get('sminax'))
        s = db.get('strike')
        
        if all([a, b, s]):
            n, e = _get_NE_on_ellipse(a, b, s)
            lat_u = _m2deg_lat(n)
            lon_u = _m2deg_lon(e, lat=db.get('lat') or 0.0)
            
            uncertainty = Dict([
                ('preferredDescription', "uncertainty ellipse"),
                ('maxHorizontalUncertainty', a),
                ('minHorizontalUncertainty', b),
                ('azimuthMaxHorizontalUncertainty', s),
            ])
            if db.get('conf') is not None:
                uncertainty['confidenceLevel'] = db.get('conf') * 100.  
        else:
            lat_u = None
            lon_u = None
            uncertainty = None
        
        #-- Basic Hypocenter ----------------------------------------
        origin = Dict([
            ('@publicID', self._uri(originID_rid)),
            ('latitude', _quan([
                ('value', db.get('lat')),
                ('uncertainty', lat_u),
                ])
            ),
            ('longitude', _quan([
                ('value', db.get('lon')),
                ('uncertainty', lon_u),
                ])
            ),
            ('depth', _quan([
                ('value', _km2m(db.get('depth'))),
                ('uncertainty', _km2m(db.get('sdepth'))),
                ]),
            ),
            ('time', _quan([
                ('value', self._utc(db.get('time'))),
                ('uncertainty', db.get('stime')),
                ]),
            ),
            ('quality' , Dict([
                ('standardError', db.get('sdobs')),
                ('usedPhaseCount', db.get('ndef')),
                ('associatedPhaseCount', db.get('nass')),
                ]),
            ),
            ('originUncertainty', uncertainty),
            ('evaluationMode', mode),
            ('evaluationStatus', status),
            ('creationInfo', Dict([
                ('creationTime', self._utc(db.get('lddate'))),
                ('agencyID', self.agency), 
                ('author', posted_author),
                ('version', db.get('orid')),
                ])
            ),
            ('comment', [
                Dict([
                    ('@id', self._uri(originID_rid, local_id="etype")),
                    ('text', css_etype),
                ]),
            ]),
            ('arrival', []),
            #('css:etype', css_etype),
        ])
        return origin
Example #15
0
    def get_event(self, anss=False):
        """
        Build an obspy moment tensor focal mech event

        This makes the tensor output into an Event containing:
        1) a FocalMechanism with a MomentTensor, NodalPlanes, and PrincipalAxes
        2) a Magnitude of the Mw from the Tensor

        Which is what we want for outputting QuakeML using
        the (slightly modified) obspy code.

        Input
        -----
        filehandle => open file OR str from filehandle.read()

        Output
        ------
        event => instance of Event() class as described above
        """
        # Get best creation time you can
        ichi = self.parser.run()
        hypo = ichi.get('event_info', {})
        evid = ichi.get('evid')
        orid = ichi.get('orid')
        dt = ichi.get('creation_time') or datetime.datetime.utcnow()
        ustamp = int((dt-datetime.datetime(1970, 01, 01, 00, 00, 00)).total_seconds())
        vers = "{0}-{1}-{2}".format(evid, orid, ustamp)
        ichiID_rid = "{0}/{1}".format('ichinose', vers) # TODO: format/errcheck
        originID_rid = "{0}/{1}".format('origin', orid or uuid.uuid4())
        eventID_rid = "{0}/{1}".format('event', evid)

        origin = Dict([
            ('@publicID', self._uri(ichiID_rid, local_id="origin")),
            ('latitude', _quan([
                ('value', hypo.get('lat')),
                ])
            ),
            ('longitude', _quan([
                ('value', hypo.get('lon')),
                ])
            ),
            ('depth', _quan([
                ('value', _km2m(ichi.get('derived_depth'))),
                ]),
            ),
            ('time', _quan([
                ('value', _dt2str(hypo.get('time'))),
                ]),
            ),
            ('depthType', "from moment tensor inversion"),
            ('evaluationMode', ichi.get('mode')),
            ('evaluationStatus', ichi.get('status')),
            ('creationInfo', Dict([
                ('creationTime', _dt2str(ichi.get('creation_time'))),
#                ('version', str(orid)),
                ])
            ),
        ])

        magnitude = Dict([
            ('@publicID', self._uri(ichiID_rid, local_id="mag")),
            ('mag', Dict(value=ichi.get('mag'))),
            ('type', ichi.get('magtype')),
            ('evaluationMode', ichi.get('mode')),
            ('evaluationStatus', ichi.get('status')),
            ('creationInfo', Dict([
                ('creationTime', _dt2str(ichi.get('creation_time'))),
#                ('version', vers)
                ])
            ),
        ])

        moment_tensor = Dict([
            ('@publicID', self._uri(ichiID_rid, local_id="mt")),
            ('derivedOriginID', origin.get('@publicID')),
            ('momentMagnitudeID', magnitude.get('@publicID')),
            ('scalarMoment', Dict(value=ichi.get('scalar_moment'))),
            ('doubleCouple', ichi.get('double_couple')),
            ('clvd', ichi.get('clvd')),
            ('variance', ichi.get('variance')),
            ('varianceReduction', ichi.get('variance_reduction')),
            ('tensor', ichi.get('tensor')),
            ('category', "regional"),
            ('dataUsed', Dict([
                ('waveType', "combined"),
                ('stationCount', ichi.get('data_used_station_count')),
                ])
            ),
            ('creationInfo', Dict([
                ('creationTime', _dt2str(ichi.get('creation_time'))),
#                ('version', vers),
                ])
            ),
        ])

        focal_mechanism = Dict([
            ('@publicID', self._uri(ichiID_rid, local_id="focalmech")),
            ('triggeringOriginID', self._uri(originID_rid)),
            ('nodalPlanes', ichi.get('nodal_planes')),
            ('principalAxes', ichi.get('principal_axes')),
            ('momentTensor', moment_tensor),
            ('creationInfo', Dict([
                ('creationTime', _dt2str(ichi.get('creation_time'))),
#                ('version', vers),
                ])
            ),
            ('evaluationMode', ichi.get('mode')),
            ('evaluationStatus', ichi.get('status')),
        ])

        event = Dict([
            ('@publicID', self._uri(eventID_rid)),
            ('focalMechanism', [focal_mechanism]),
            ('magnitude', [magnitude]),
            ('origin', [origin]),
            ('preferredMagnitudeID', magnitude.get('@publicID')),
            ('preferredFocalMechanismID', focal_mechanism.get('@publicID')),
            ('creationInfo', Dict([
                ('creationTime', _dt2str(ichi.get('creation_time'))),
#                ('version', str(evid)),
                ])
            ),
        ])
        if anss:
            event.update(anss_params(self.agency, evid))
        return event
Example #16
0
    def run(self):
        """
        In future, parse the file and have attributes available
        """
        p = self
        ichi = Dict()

        # Maybe get rid of all this stuff...
        event         = Dict(event_type='earthquake')
        origin        = Dict()
        focal_mech    = Dict()
        nodal_planes  = Dict()
        moment_tensor = Dict()
        principal_ax  = Dict()
        magnitude     = Dict()
        data_used     = Dict()
        creation_info = Dict()

        ichi['mode'] = 'automatic'
        ichi['status'] = 'preliminary'
        # Parse the entire file line by line.
        for n,l in enumerate(p.line):
            if 'REVIEWED BY NSL STAFF' in l:
                ichi['mode'] = 'manual'
                ichi['status'] = 'reviewed'
            if 'Event ID' in l:
                ichi['evid'] = p._id(n)
            if 'Origin ID' in l:
                ichi['orid'] = p._id(n)
            if 'Ichinose' in l:
                ichi['category'] = 'regional'
            if re.match(r'^\d{4}\/\d{2}\/\d{2}', l):
                ichi['event_info'] = p._event_info(n)
            if 'Depth' in l:
                ichi['derived_depth'] = p._depth(n)
            if 'Mw' in l:
                ichi['mag'] = p._mw(n)
                ichi['magtype'] = 'Mw'
            if 'Mo' in l and 'dyne' in l:
                ichi['scalar_moment'] = p._mo(n)
            if 'Percent Double Couple' in l:
                ichi['double_couple'] = p._percent(n)
            if 'Percent CLVD' in l:
                ichi['clvd'] = p._percent(n)
            if 'Epsilon' in l:
                ichi['variance'] = p._epsilon(n)
            if 'Percent Variance Reduction' in l:
                ichi['variance_reduction'] = p._percent(n)
            if 'Major Double Couple' in l and 'strike' in p.line[n+1]:
                np = p._double_couple(n)

                ichi['nodal_planes'] = Dict([
                    ('nodalPlane1', Dict([
                        ('strike', Dict(value = np[0][0])),
                        ('dip', Dict(value = np[0][1])),
                        ('rake', Dict(value = np[0][2])),
                        ])
                    ),
                    ('nodalPlane2', Dict([
                        ('strike', Dict(value = np[1][0])),
                        ('dip', Dict(value = np[1][1])),
                        ('rake', Dict(value = np[1][2])),
                        ])
                    ),
                    ('@preferredPlane', 1),
                ])
            if 'Spherical Coordinates' in l:
                mt = p._mt_sphere(n)

                ichi['tensor'] = Dict([
                    ('Mrr', Dict(value=mt.get('Mrr'))),
                    ('Mtt', Dict(value=mt.get('Mtt'))),
                    ('Mpp', Dict(value=mt.get('Mff'))),
                    ('Mrt', Dict(value=mt.get('Mrt'))),
                    ('Mrp', Dict(value=mt.get('Mrf'))),
                    ('Mtp', Dict(value=mt.get('Mtf'))),
                ])
            if 'Eigenvalues and eigenvectors of the Major Double Couple' in l:
                ax = p._vectors(n)
                t_axis = (ax['T']['trend'], ax['T']['plunge'], ax['T']['ev'])
                p_axis = (ax['P']['trend'], ax['P']['plunge'], ax['P']['ev'])
                n_axis = (ax['N']['trend'], ax['N']['plunge'], ax['N']['ev'])

                ichi['principal_axes'] = Dict([
                    ('tAxis', Dict([
                        ('azimuth', Dict(value = t_axis[0])),
                        ('plunge', Dict(value = t_axis[1])),
                        ('length', Dict(value = t_axis[2])),
                        ])
                    ),
                    ('pAxis', Dict([
                        ('azimuth', Dict(value = p_axis[0])),
                        ('plunge', Dict(value = p_axis[1])),
                        ('length', Dict(value = p_axis[2])),
                        ])
                    ),
                    ('nAxis', Dict([
                        ('azimuth', Dict(value = n_axis[0])),
                        ('plunge', Dict(value = n_axis[1])),
                        ('length', Dict(value = n_axis[2])),
                        ])
                    ),
                ])
            if 'Number of Stations' in l:
                ichi['data_used_station_count'] = p._number_of_stations(n)
            if 'Maximum' in l and 'Gap' in l:
                ichi['azimuthal_gap'] = p._gap(n)
            if re.match(r'^Date', l):
                ichi['creation_time'] = p._creation_time(n)
        return ichi