Example #1
0
def dbloc_source_db(db, pointer=True):
    """
    Checks if you are in a dbloc2 'trial' db and returns the source
    one if you are, otherwise returns the same Dbptr. This is for running
    interactive scripts lauched from dbloc2 and writing to a non-volitile
    original db.
    
    INPUT: Dbptr of current temp database in dbloc2
    OUTPUT: Dbptr to database that dbloc2 is using.
    """
    try:
        from antelope.stock import pfget
    except ImportError:
        from antelope.stock import pfread as pfget

    db = Dbptr(db, perm="r+")
    dbname = db.query("dbDATABASE_NAME")
    pf_settings = pfget("dbloc2")
    pfdef = pf_settings["Define"]
    tempdb = pfdef["Temporary_db"]
    workdir = pfdef["Work_dir"]
    dblocdb = os.path.join(workdir, tempdb)
    if dbname.endswith(tempdb):
        # path of trial db from dbloc2
        dbcwd = os.path.dirname(dbname)
        # relative name of 1st db in 'trial' database decriptor file
        dbpath0 = db.query("dbDBPATH").split(":")[0].translate(None, "{}")
        # full absolute path database name to source
        dbname = os.path.abspath(os.path.join(dbcwd, dbpath0))
        db.close()
        db = Dbptr(dbname, perm="r+")
    if pointer:
        return db
    else:
        db.close()
        return dbname
Example #2
0
def dbloc_source_db(db, pointer=True):
    """
    Checks if you are in a dbloc2 'trial' db and returns the source
    one if you are, otherwise returns the same Dbptr. This is for running
    interactive scripts lauched from dbloc2 and writing to a non-volitile
    original db.
    
    INPUT: Dbptr of current temp database in dbloc2
    OUTPUT: Dbptr to database that dbloc2 is using.
    """
    try:
        from antelope.stock import pfget
    except ImportError:
        from antelope.stock import pfread as pfget
    
    db = Dbptr(db, perm='r+') 
    dbname = db.query('dbDATABASE_NAME')
    pf_settings = pfget('dbloc2')
    pfdef = pf_settings['Define']
    tempdb = pfdef['Temporary_db']
    workdir = pfdef['Work_dir']
    dblocdb = os.path.join(workdir,tempdb)
    if dbname.endswith(tempdb):
        # path of trial db from dbloc2
        dbcwd = os.path.dirname(dbname)
        # relative name of 1st db in 'trial' database decriptor file
        dbpath0 = db.query('dbDBPATH').split(':')[0].translate(None,'{}')
        # full absolute path database name to source
        dbname = os.path.abspath(os.path.join(dbcwd, dbpath0))
        db.close()
        db = Dbptr(dbname, perm='r+')
    if pointer:
        return db
    else:
        db.close()
        return dbname
Example #3
0
def eventfocalmech2db(event=None, database=None):
    """
    Write the preferred HASH solution to Datascope database.
    
    Writes to 'fplane', 'predmech' and 'predarr' tables
    """
    focm = event.preferred_focal_mechanism()
    o = focm.triggering_origin_id.getReferredObject()

    plane1 = focm.nodal_planes.nodal_plane_1
    plane2 = focm.nodal_planes.nodal_plane_2
    T = focm.principal_axes.t_axis
    P = focm.principal_axes.p_axis
    orid = int(o.creation_info.version)

    db = Dbptr(database, perm="r+")
    try:
        # Use the original db if in a dbloc2 'tmp/trial' db
        # db = dbloc_source_db(db)
        # save solution as a new mechid
        mechid = db.nextid("mechid")
        # in fplane...
        dbfpln = dblookup(db, table="fplane")
        dbfpln.record = dbfpln.addnull()
        dbfpln.putv(
            "orid",
            orid,
            "str1",
            round(plane1.strike, 1),
            "dip1",
            round(plane1.dip, 1),
            "rake1",
            round(plane1.rake, 1),
            "str2",
            round(plane2.strike, 1),
            "dip2",
            round(plane2.dip, 1),
            "rake2",
            round(plane2.rake, 1),
            "taxazm",
            round(T.azimuth, 1),
            "taxplg",
            round(T.plunge, 1),
            "paxazm",
            round(P.azimuth, 1),
            "paxplg",
            round(P.plunge, 1),
            "algorithm",
            focm.method_id.resource_id,
            "auth",
            focm.creation_info.author,
            "mechid",
            mechid,
        )
        dbpmec = dblookup(db, table="predmech")
        dbparr = dblookup(db, table="predarr")
        for av in o.arrivals:
            pk = av.pick_id.getReferredObject()
            if pk.polarity is "positive":
                fm = "U"
            elif pk.polarity is "negative":
                fm = "D"
            else:
                continue

            arid = int(av.creation_info.version)

            # ..and predmech
            dbpmec.record = dbpmec.addnull()
            dbpmec.putv("arid", arid, "orid", orid, "mechid", mechid, "fm", fm)
            # if there are entries for this arrival already, write over it...
            dbparr.record = dbparr.find("arid=={0} && orid=={1}".format(arid, orid))
            if dbparr.record < 0:
                dbparr.record = dbparr.addnull()
            dbparr.putv("arid", arid, "orid", orid, "esaz", av.azimuth, "dip", av.takeoff_angle)
    except Exception as e:
        raise e
    finally:
        db.close()
Example #4
0
def input(hp, dbname, evid=None, orid=None):
    """Input HASH data from Antelope database
    
    This will accept a database name OR Antelope Dbptr, and either
    an ORID, or an EVID, in which case the 'prefor' ORID is looked
    up and used.
    
    Inputs
    ------
    dbname  :   str or antelope.datascope.Dbptr
    orid    :   int of ORID
    evid    :   int of EVID
    """

    db = Dbptr(dbname)

    if orid is None:
        dbv = dbprocess(db, ["dbopen event", "dbsubset evid == " + str(evid)])
        orid = RowPointerDict(dbv)["prefor"]

    db = dbprocess(
        db,
        [
            "dbopen origin",
            "dbsubset orid == " + str(orid),
            "dbjoin origerr",
            "dbjoin assoc",
            "dbjoin arrival",
            "dbjoin affiliation",
            "dbjoin site",
            "dbsubset iphase =~ /.*[Pp].*/",
            "dbsubset (ondate <= time)",
            "dbsubset (time <= offdate) || (offdate == -1)",
        ],
    )

    ph = RowPointerDict(db, record=0)

    hp.nrecs = len(ph)
    if len(ph) <= 0:
        raise ValueError("No picks for this ORID: {0}".format(orid))

    hp.tstamp = ph["origin.time"]
    hp.qlat = ph["origin.lat"]
    hp.qlon = ph["origin.lon"]
    hp.qdep = ph["origin.depth"]
    hp.qmag = ph["origin.ml"]
    hp.icusp = ph["origin.orid"]
    hp.seh = ph["origerr.smajax"]
    hp.sez = ph["origerr.sdepth"]

    aspect = np.cos(hp.qlat / degrad)  # convert using python later.

    # The index 'k' is deliberately non-Pythonic to deal with the fortran
    # subroutines which need to be called and the structure of the original HASH code.
    # May be able to update with a rewrite... YMMV
    k = 0
    for n in range(len(ph)):
        # Extract pick data from the db
        ph = RowPointerDict(db, record=n)

        hp.sname[k] = ph["sta"]
        hp.snet[k] = ph["net"]
        hp.scomp[k] = ph["chan"]
        hp.pickonset[k] = ph["qual"].strip(".")
        hp.pickpol[k] = ph["fm"]
        hp.arid[k] = ph["arid"]

        flat, flon, felv = ph["site.lat"], ph["site.lon"], ph["site.elev"]
        hp.esaz[k] = ph["esaz"]

        # Distance and Azimuth filtering
        dx = (flon - hp.qlon) * 111.2 * aspect
        dy = (flat - hp.qlat) * 111.2
        dist = np.sqrt(dx ** 2 + dy ** 2)
        qazi = 90.0 - np.arctan2(dy, dx) * degrad

        if qazi < 0.0:
            qazi = qazi + 360.0

        if dist > hp.delmax:
            continue

        # Try to get an up/down polarity
        if not hp.pickpol[k].lower():
            continue
        if hp.pickpol[k].lower() in "cu":
            hp.p_pol[k] = 1
        elif hp.pickpol[k].lower() in "dr":
            hp.p_pol[k] = -1
        else:
            continue

        # Save them for other functions
        hp.dist[k] = dist
        hp.qazi[k] = qazi
        hp.flat[k] = flat
        hp.flon[k] = flon
        hp.felv[k] = felv

        # Try to get the onset, impulsive if none
        if hp.pickonset[k].lower() == "i":
            hp.p_qual[k] = 0
        elif hp.pickonset[k].lower() == "e":
            hp.p_qual[k] = 1
        elif hp.pickonset[k].lower() == "w":
            hp.p_qual[k] = 1
        else:
            hp.p_qual[k] = 0

        # polarity check in original code... doesn't work here
        # hp.p_pol[k] = hp.p_pol[k] * hp.spol
        k += 1
    hp.npol = k  # k is zero indexed in THIS loop
    db.close()
Example #5
0
def eventfocalmech2db(event=None, database=None):
    """
    Write the preferred HASH solution to Datascope database.
    
    Writes to 'fplane', 'predmech' and 'predarr' tables
    """
    focm = event.preferred_focal_mechanism()
    o = focm.triggering_origin_id.getReferredObject()
    
    plane1 = focm.nodal_planes.nodal_plane_1
    plane2 = focm.nodal_planes.nodal_plane_2
    T = focm.principal_axes.t_axis
    P = focm.principal_axes.p_axis
    orid = int(o.creation_info.version)
    
    db = Dbptr(database, perm='r+')
    try:
        # Use the original db if in a dbloc2 'tmp/trial' db
        #db = dbloc_source_db(db)
        # save solution as a new mechid
        mechid = db.nextid('mechid')
        # in fplane...
        dbfpln = dblookup(db,table='fplane')
        dbfpln.record = dbfpln.addnull()
        dbfpln.putv('orid', orid,
            'str1', round(plane1.strike,1) ,
            'dip1', round(plane1.dip,1) ,
            'rake1',round(plane1.rake,1),
            'str2', round(plane2.strike,1) ,
            'dip2', round(plane2.dip,1) ,
            'rake2',round(plane2.rake,1),
            'taxazm',round(T.azimuth,1),
            'taxplg',round(T.plunge,1),
            'paxazm',round(P.azimuth,1),
            'paxplg',round(P.plunge,1),
            'algorithm', focm.method_id.resource_id,
            'auth', focm.creation_info.author,
            'mechid', mechid,
            )
        dbpmec = dblookup(db,table='predmech')
        dbparr = dblookup(db,table='predarr')
        for av in o.arrivals:
            pk = av.pick_id.getReferredObject()
            if pk.polarity is 'positive':
                fm = 'U'
            elif pk.polarity is 'negative':
                fm = 'D'
            else:
                continue
            
            arid = int(av.creation_info.version)
            
            # ..and predmech
            dbpmec.record = dbpmec.addnull()
            dbpmec.putv('arid', arid,
                        'orid', orid,
                        'mechid', mechid,
                        'fm', fm,
                        )
            # if there are entries for this arrival already, write over it...
            dbparr.record = dbparr.find('arid=={0} && orid=={1}'.format(arid, orid))
            if dbparr.record < 0:
                dbparr.record = dbparr.addnull()
            dbparr.putv('arid', arid,
                        'orid', orid, 
                        'esaz', av.azimuth, 
                        'dip' , av.takeoff_angle,
                        )
    except Exception as e:
        raise e
    finally:
        db.close()
Example #6
0
def input(hp, dbname, evid=None, orid=None):
    '''Input HASH data from Antelope database
    
    This will accept a database name OR Antelope Dbptr, and either
    an ORID, or an EVID, in which case the 'prefor' ORID is looked
    up and used.
    
    Inputs
    ------
    dbname  :   str or antelope.datascope.Dbptr
    orid    :   int of ORID
    evid    :   int of EVID
    '''
    
    db = Dbptr(dbname)

    if orid is None:
        dbv = dbprocess(db,['dbopen event', 'dbsubset evid == '+str(evid)])
        orid = RowPointerDict(dbv)['prefor']
    
    db = dbprocess(db,[ 'dbopen origin', 'dbsubset orid == '+str(orid),
                    'dbjoin origerr', 'dbjoin assoc',  'dbjoin arrival',
                    'dbjoin affiliation', 'dbjoin site',
                    'dbsubset iphase =~ /.*[Pp].*/',
                    'dbsubset (ondate <= time)',
                    'dbsubset (time <= offdate) || (offdate == -1)']
                    )
    
    ph = RowPointerDict(db, record=0)

    hp.nrecs = len(ph)
    if len(ph) <= 0:
        raise ValueError("No picks for this ORID: {0}".format(orid) )
        
    hp.tstamp = ph['origin.time']
    hp.qlat   = ph['origin.lat']
    hp.qlon   = ph['origin.lon']
    hp.qdep   = ph['origin.depth']
    hp.qmag   = ph['origin.ml']
    hp.icusp  = ph['origin.orid']
    hp.seh    = ph['origerr.smajax']
    hp.sez    = ph['origerr.sdepth']
    
    aspect = np.cos(hp.qlat / degrad) # convert using python later.
    
    # The index 'k' is deliberately non-Pythonic to deal with the fortran
    # subroutines which need to be called and the structure of the original HASH code.
    # May be able to update with a rewrite... YMMV
    k = 0
    for n in range(len(ph)):
        
        ph = RowPointerDict(db, record=n)

        hp.sname[k]   = ph['sta']
        hp.snet[k]    = ph['net']
        hp.scomp[k]   = ph['chan']
        hp.pickonset[k] = 'I'
        hp.pickpol[k]   = ph['fm']
        hp.arid[k]    = ph['arid']
        
        flat, flon, felv = ph['site.lat'],ph['site.lon'],ph['site.elev']
        hp.esaz[k] = ph['esaz']

        
        # dist @ azi, get from db OR obspy or another python mod (antelope) could do this on WGS84
        dx = (flon - hp.qlon) * 111.2 * aspect
        dy = (flat - hp.qlat) * 111.2
        dist = np.sqrt(dx**2 + dy**2)
        qazi = 90. - np.arctan2(dy,dx) * degrad
        
        if (qazi < 0.):
            qazi = qazi + 360.
        if (dist > hp.delmax):
            continue
        if (hp.pickpol[k] in 'CcUu'):
            hp.p_pol[k] = 1
        elif (hp.pickpol[k] in 'RrDd'):
            hp.p_pol[k] = -1
        else:
            continue
        
        # save them for other functions -MCW
        hp.dist[k] = dist
        hp.qazi[k] = qazi
        hp.flat[k] = flat
        hp.flon[k] = flon
        hp.felv[k] = felv
        
        if (hp.pickonset[k] in 'Ii'):
            hp.p_qual[k] = 0
        else:
            hp.p_qual[k] = 1
        
        # polarity check in original code... doesn't work here
        #hp.p_pol[k] = hp.p_pol[k] * hp.spol
        k += 1
    #npol = k - 1
    hp.npol = k # k is zero indexed in THIS loop
    db.close()