Ejemplo n.º 1
0
def version():
    """
    Check version of TCRM code.

    :returns: Current git commit hash and the date/time
             of the commit.

    :rtype: str
    :raises: :mod:`subprocess.CalledProcessError` if the git
             command fails.
             
    .. note:: This requires ``git`` to be installed to execute.
    """
    
    vers = ''

    try:
        vers = git('log -1 --date=iso --pretty=format:"%H"')
    except subprocess.CalledProcessError:
        # Case for missing git:
        import inspect
        path, name, ext = flModulePath(len(inspect.stack()))
        fname = os.path.join(path, name+ext)
        fdate = flModDate(fname)
        vers = '{0} modified {1}'.format(fname, fdate)
    
    return vers
Ejemplo n.º 2
0
def parseShapefile(shape_file):
    """
    Read shapes and records from a shape file and return them.

    :param str shape_file: Shape file to parse.

    :returns: list of :class:`shapefile._Shape` instances (one for each
              feature), a list of lists containing the records for each 
              feature and list of field descriptions.

    """

    LOG.info('Parsing shapefile {0}'.format(os.path.abspath(shape_file)))

    moddate = flModDate(shape_file)
    LOG.debug('Last modified: {0}'.format(moddate))

    # read shapefile
    sf = shapefile.Reader(shape_file)
    shapes = sf.shapes()
    records = sf.records()
    fields = sf.fields

    # remove first header field - no corresponding value in "records"
    fields = fields[1:]

    LOG.debug("{0} features in {1}".format(len(shapes), shape_file))
    LOG.debug("{0} fields in {1}".format(len(fields) - 1, shape_file))
    return shapes, fields, records
Ejemplo n.º 3
0
def pArchiveFile( filename ):
    """
    Move the file to the archive directory (if specified), inserting a
    timestamp in the name.

    :param str filename: Full path of the file to be archived.

    :return: `True` if the file is successfully moved, `False` otherwise.
    :rtype: bool
    
    """
    path, ext = os.path.splitext( filename )
    path, base = os.path.split( path )
    archive_dir = pArchiveDir( )
    ext = ext.lstrip('.')
    if ( archive_dir ):
        if os.path.isdir( archive_dir ):
            pass
        else:
            try:
                os.makedirs( archive_dir )
            except:
                logger.critcal( "Cannot create %s"%( archive_dir ) )
                raise

    if ( pArchiveTimestamp( ) ):
        archive_date = flModDate( filename, g_archive_date_format )
        archive_file_name = os.path.join( archive_dir, "%s.%s.%s"%( base, archive_date, ext ) )
    else:
        archive_file_name = os.path.join( archive_dir, "%s.%s"%( base, ext ) )

    rc = pMoveFile( filename, archive_file_name )
    return rc
Ejemplo n.º 4
0
def version():
    """
    Check version of TCRM code.

    :returns: Current git commit hash and the date/time
             of the commit.

    :rtype: str
    :raises: :mod:`subprocess.CalledProcessError` if the git
             command fails.

    .. note:: This requires ``git`` to be installed to execute.
    """

    vers = ''

    try:
        vers = git('log -1 --date=iso --pretty=format:"%H"')
    except subprocess.CalledProcessError:
        # Case for missing git:
        import inspect
        path, name, ext = flModulePath(len(inspect.stack()))
        fname = os.path.join(path, name + ext)
        fdate = flModDate(fname)
        vers = '{0} modified {1}'.format(fname, fdate)

    return vers
Ejemplo n.º 5
0
def pArchiveFile( filename ):
    """pArchiveFile
    Move the file to the archive directory (if specified), inserting a
    timestamp in the name.
    """
    path, ext = os.path.splitext( filename )
    path, base = os.path.split( path )
    archive_dir = pArchiveDir( )
    ext = ext.lstrip('.')
    if ( archive_dir ):
        if os.path.isdir( archive_dir ):
            pass
        else:
            try:
                os.makedirs( archive_dir )
            except:
                logger.critcal( "Cannot create %s"%( archive_dir ) )
                raise

    if ( pArchiveTimestamp( ) ):
        archive_date = flModDate( filename, g_archive_date_format )
        archive_file_name = os.path.join( archive_dir, "%s.%s.%s"%( base, archive_date, ext ) )
    else:
        archive_file_name = os.path.join( archive_dir, "%s.%s"%( base, ext ) )

    rc = pMoveFile( filename, archive_file_name )
    return rc
Ejemplo n.º 6
0
def parseVulnerability(vuln_file):
    """
    Return a dict of building classes, with each value another dict
    containing the alpha and beta values for the vulnerability model
    for that class of building.
    """

    LOG.info('Reading vulnerability parameters from {0}'.format(
        abspath(vuln_file)))
    moddate = flModDate(vuln_file)
    LOG.info('Last modified: {0}'.format(moddate))

    up_vuln_type = []
    mu = []
    sigma = []
    scale = []
    with open(vuln_file, 'rb') as csvfile:
        reader = csv.reader(csvfile, quotechar='"')
        for row in reader:
            if reader.line_num == 1:
                pass
            else:
                try:
                    up_vuln_type.append(row[0])
                    # set vulnerabilities for different building types
                    mu.append(float(row[1]))
                    sigma.append(float(row[2]))
                    scale.append(float(row[3]))
                except ValueError:
                    # Catch the case of missing values:
                    mu.append(10000.0)
                    sigma.append(0.1)
                    scale.append(0.0)

    params = dict()
    LOG.debug("Class : mu : sigma")
    for i, k in enumerate(up_vuln_type):
        params[k] = {'mu': mu[i], 'sigma': sigma[i], 'scale': scale[i]}
        LOG.debug(("{0:<6}: \
                       {1:<5.3f} : \
                       {2:<5.2f} : \
                       {3:<5.2f}").format(k, mu[i], sigma[i], scale[i]))
    return params
Ejemplo n.º 7
0
def parseVulnerability(vuln_file):
    """
    Return a dict of building classes, with each value another dict
    containing the alpha and beta values for the vulnerability model
    for that class of building.
    """

    LOG.info('Reading vulnerability parameters from {0}'.format(
                    abspath(vuln_file)))
    moddate = flModDate(vuln_file)
    LOG.info('Last modified: {0}'.format(moddate))

    params = AvDict()
    with open(vuln_file, 'rb') as csvfile:
        reader = csv.reader(csvfile, quotechar='"')
        for row in reader:
            if reader.line_num == 1:
                pass
            else:
                try:
                    params[str(row[0])] = {'mu':float(row[1]),
                                           'sigma':float(row[2]),
                                           'scale':float(row[3]),
                                           'sl_mu':float(row[4]),
                                           'sl_sd':float(row[5]),
                                           'sl_scale':float(row[6]),
                                           'mod_mu':float(row[7]),
                                           'mod_sd':float(row[8]),
                                           'mod_scale':float(row[9]),
                                           'ext_mu':float(row[10]),
                                           'ext_sd':float(row[11]),
                                           'ext_scale':float(row[12]),
                                           'c_mu':float(row[13]),
                                           'c_sd':float(row[14]),
                                           'c_scale':float(row[15])}

                except ValueError:
                    # Catch the case of missing values:
                    params[str(row[0])] ={'mu':10000.0,
                                           'sigma':0.1,
                                           'scale':0.0,
                                           'sl_mu':10000.,
                                           'sl_sd':0.1,
                                           'sl_scale':0.0,
                                           'mod_mu':10000.,
                                           'mod_sd':0.1,
                                           'mod_scale':0.0,
                                           'ext_mu':10000.,
                                           'ext_sd':0.1,
                                           'ext_scale':0.0,
                                           'c_mu':10000.,
                                           'c_sd':0.1,
                                           'c_scale':0.0}
                    
    LOG.debug("Vulnerability information")
    LOG.debug("Class : mu : sigma : scale ")
    for key, value in params.items():
        LOG.debug(("{0:<6}: {1:<5.3f} : {2:<5.2f} : {3:<6.4f} : "
                   "{4:<5.3f} : {5:<5.2f} : {6:<6.4f} : "
                   "{7:<5.3f} : {8:<5.2f} : {9:<6.4f} : "
                   "{10:<5.3f} : {11:<5.2f} : {12:<6.4f} : "
                   "{13:<5.3f} : {14:<5.2f} : {15:<6.4f}" ).format(
                       key, value['mu'], value['sigma'], value['scale'],
                       value['sl_mu'], value['sl_sd'], value['sl_scale'],
                       value['mod_mu'], value['mod_sd'], value['mod_scale'],
                       value['ext_mu'], value['ext_sd'], value['ext_scale'],
                       value['c_mu'], value['c_sd'], value['c_scale']))

    return params