コード例 #1
0
ファイル: antelopeIO.py プロジェクト: markcwill/hashpy
class RowPointerDict(dict):

    _dbptr = None

    def __init__(self, dbptr=None, record=None):
        self._dbptr = Dbptr(dbptr)
        if record is not None:
            self._dbptr.record = record
        if self._dbptr.record < 0:
            self._dbptr.record = 0

    def __getitem__(self, key):
        return self._dbptr.getv(key)[0]

    def __setitem__(self, key, value):
        self._dbptr.putv(key, value)

    def __len__(self):
        return self._dbptr.nrecs()
コード例 #2
0
class RowPointerDict(dict):
    
    _dbptr = None

    def __init__(self, dbptr=None, record=None):
        self._dbptr = Dbptr(dbptr)
        if record is not None:
            self._dbptr.record = record
        if self._dbptr.record < 0:
            self._dbptr.record = 0

    def __getitem__(self, key):
        return self._dbptr.getv(key)[0]

    def __setitem__(self, key, value):
        self._dbptr.putv(key, value)

    def __len__(self):
        return self._dbptr.nrecs()
コード例 #3
0
ファイル: test_dbhash.py プロジェクト: 717524640/hashpy
def main():
    from argparse import ArgumentParser
    
    # Get command line args
    parser = ArgumentParser()
    parser.add_argument("dbin",   help="Input database")
    parser.add_argument("dbout",  help="Output database", nargs='?')
    parser.add_argument("-p", "--plot", help="Plot result", action='store_true')
    parser.add_argument("-l", "--loc", help="dbloc2 mode", action='store_true')
    parser.add_argument("-i", "--image", help="Save image with db", action='store_true')
    parser.add_argument("--pf",   help="Parameter file")
    group = parser.add_mutually_exclusive_group() #required=True)
    group.add_argument("--evid", help="Event ID", type=int)
    group.add_argument("--orid", help="Origin ID", type=int)
    args = parser.parse_args()
    
    # Special 'dbloc2' settings
    if args.loc:
        from antelope.datascope import Dbptr
        # alter args b/c dbloc2 passes a db and a row number
        args.dbin = args.dbin.rstrip('.origin')
        db = Dbptr(args.dbin)
        db = db.lookup(table='origin')
        db.record = int(args.dbout)
        args.orid = db.getv('orid')[0]
        args.dbout = dbloc_source_db(args.dbin, pointer=False)
        args.plot = True   # force plot
        args.image = True  # force saving image to db folder
    
    # Now that we have a save location from command line args,
    # make a function to save to that database. The plotter is I/O
    # agnostic, it will accept a function to save anything anyhow anywhichway
    #
    def save_plot_to_db(fmplotter, dbname=args.dbout, dump_bitmap=args.image):
        focal_mech = fmplotter.event.focal_mechanisms[fmplotter._fm_index]
        if focal_mech is not fmplotter.event.preferred_focal_mechanism():
            fmplotter.event.preferred_focal_mechanism_id = focal_mech.resource_id.resource_id
        
        # Save to db        
        eventfocalmech2db(event=fmplotter.event, database=dbname)
        
        if dump_bitmap:
            vers = fmplotter.event.preferred_origin().creation_info.version
            dbdir = os.path.dirname(dbname)
            _dump_bitmap(figure=fmplotter.fig, directory=dbdir, uid=vers)

    # Run HASH
    hp = dbhash_run(args.dbin, orid=args.orid, pf=args.pf)

    # Launch plotter or spit out solution
    if args.plot:
        from hashpy.plotting.focalmechplotter import FocalMechPlotter
        ev = hp.output(format="OBSPY")
        p = FocalMechPlotter(ev, save=save_plot_to_db)
    else:
        # quick orid/strike/dip/rake line
        print hp.output()
        p = 0    
        if args.dbout:
            db = hp.output(format="ANTELOPE", dbout=args.dbout)
    
    # Done, return HashPype and/or FocalMechPlotter for debugging
    return hp, p
コード例 #4
0
class Dbtuple(dict, object):
    """
    Holds the pointer to a db record, NOT the data, can access the
    same as Dbrecord, but the pointer must remain open

    Useful for large datasets that may have trouble in memory
    Only stores the pointer, not contents, all attributes are
    returned by querying the open db using the pointer.
    """
    # Only holds one thing in Python namespace, Dbptr object:
    _ptr = Dbptr()
    
    # built in queries for useful info
    @property
    def TABLE_NAME(self):
        return self._ptr.query('dbTABLE_NAME')  # string of what table record came from
    
    @property
    def PRIMARY_KEY(self):
        return self._ptr.query('dbPRIMARY_KEY') # tuple of strings of fields in primary key
    
    @property
    def TABLE_FIELDS(self):              # tuple of fields from database record
        return self._ptr.query('dbTABLE_FIELDS')
    
    @property
    def Fields(self):                   # May go away in future
        flist = list(self.TABLE_FIELDS)
        flist.sort()
        return flist
    
    @property
    def _ptrNULL(self):
        """
        Return NULL record for a given pointer
        """
        nullptr = Dbptr(self._ptr)
        nullptr.record = dbNULL
        return nullptr

    def __init__(self, db=None):
        """
        Testing object relational mapper-type thing...
        """
        if db:
            if db.record == dbALL:
                raise ValueError("Rec # is 'dbALL', one record only, please.")
            self._ptr = Dbptr(db)
        else:
            self._ptr = Dbptr()
            raise NotImplementedError("No empty contructor allowed here yet...")

    def __getattr__(self, field):
        """
        Looks for attributes in fields of a db pointer
        """
        return self._ptr.getv(field)[0]

    def __setattr__(self, field, value):
        """Try to set a db field

        You must have opened your db with r+ permissions!
        """
        # Special case: trying to set the pointer. Else try to write to the db
        if field == '_ptr':
            super(Dbtuple,self).__setattr__(field, value)
        else:
            # Could try to catch an ElogComplain in else, but the same
            # error comes up for read-only or a wrong field
            if self._ptr.query('dbDATABASE_IS_WRITABLE'):
                self._ptr.putv(field, value)
            else:
                raise IOError("Database not opened with write permission!")

    # Dictionary powers activate:
    __getitem__ = __getattr__
    __setitem__ = __setattr__

    def _null(self, field):
        """
        Returns NULL value for a given field
        """
        return self._ptrNULL.getv(field)[0]

    def get(self, field):
        """Get a database value from the given field (NULL supported)
        
        If the value is a NULL value for that field, return a python None
        """
        value = self.__getattr__(field)
        if value == self._null(field):
            value = None
        return value

    def set(self, field, value):
        """Set a database field to the given value (NULL supported)
        
        Setting a field to 'None' puts a NULL value in for that record field
        """
        if value is None:
            value = self._null(field)
        self.__setattr__(field, value)

    def __repr__(self):
        """
        Useful representation - shows the table and primary key of the record.
        """
        start = "{0}('{1}' -> ".format(self.__class__.__name__, self.TABLE_NAME)
        # Build up a list containing the fields of the primary key
        # Annoyingly, times have a '::' between them, so deal with that...
        mids = []
        for k in self.PRIMARY_KEY:
            if '::' in k:
                keyf = '::'.join([str(self.__getattr__(_k)) for _k in k.split('::')])
            else:
                keyf = str(self.__getattr__(k))
            mids.append(keyf)
        middle = ' '.join(mids)
        end = ")"
        return start+middle+end

    def __str__(self):
        """
        Prints out record content as a string.

        SHOULD be the same as if you cat'ted a line from the table text file
        """
        db = Dbptr(self._ptr)
        formatting = ' '.join([db.query('dbFIELD_FORMAT') for db.field in range(len(self.TABLE_FIELDS))])
        fields = tuple([self.__getattr__(f) for f in self.TABLE_FIELDS])
        return formatting % fields
コード例 #5
0
def main():
    from argparse import ArgumentParser

    # Get command line args
    parser = ArgumentParser()
    parser.add_argument("dbin", help="Input database")
    parser.add_argument("dbout", help="Output database", nargs='?')
    parser.add_argument("-p",
                        "--plot",
                        help="Plot result",
                        action='store_true')
    parser.add_argument("-l", "--loc", help="dbloc2 mode", action='store_true')
    parser.add_argument("-i",
                        "--image",
                        help="Save image with db",
                        action='store_true')
    parser.add_argument("--pf", help="Parameter file")
    group = parser.add_mutually_exclusive_group()  #required=True)
    group.add_argument("--evid", help="Event ID", type=int)
    group.add_argument("--orid", help="Origin ID", type=int)
    args = parser.parse_args()

    # Special 'dbloc2' settings
    if args.loc:
        from antelope.datascope import Dbptr
        # alter args b/c dbloc2 passes a db and a row number
        args.dbin = args.dbin.rstrip('.origin')
        db = Dbptr(args.dbin)
        db = db.lookup(table='origin')
        db.record = int(args.dbout)
        args.orid = db.getv('orid')[0]
        args.dbout = dbloc_source_db(args.dbin, pointer=False)
        args.plot = True  # force plot
        args.image = True  # force saving image to db folder

    # Now that we have a save location from command line args,
    # make a function to save to that database. The plotter is I/O
    # agnostic, it will accept a function to save anything anyhow anywhichway
    #
    def save_plot_to_db(fmplotter, dbname=args.dbout, dump_bitmap=args.image):
        focal_mech = fmplotter.event.focal_mechanisms[fmplotter._fm_index]
        if focal_mech is not fmplotter.event.preferred_focal_mechanism():
            fmplotter.event.preferred_focal_mechanism_id = focal_mech.resource_id.resource_id

        # Save to db
        eventfocalmech2db(event=fmplotter.event, database=dbname)

        if dump_bitmap:
            vers = fmplotter.event.preferred_origin().creation_info.version
            dbdir = os.path.dirname(dbname)
            _dump_bitmap(figure=fmplotter.fig, directory=dbdir, uid=vers)

    # Run HASH
    hp = dbhash_run(args.dbin, orid=args.orid, pf=args.pf)

    # Launch plotter or spit out solution
    if args.plot:
        from hashpy.plotting.focalmechplotter import FocalMechPlotter
        ev = hp.output(format="OBSPY")
        p = FocalMechPlotter(ev, save=save_plot_to_db)
    else:
        # quick orid/strike/dip/rake line
        print hp.output()
        p = 0
        if args.dbout:
            db = hp.output(format="ANTELOPE", dbout=args.dbout)

    # Done, return HashPype and/or FocalMechPlotter for debugging
    return hp, p