Пример #1
0
def test_readLine(capfd):
    '''Simple test for function readLine'''
    dirname = os.path.dirname(__file__)
    demFileName = os.path.join(dirname, 'data', 'testShpConv', 'testShpConv.asc')
    dem = ascUtils.readRaster(demFileName)
    shpFileName = os.path.join(dirname, 'data', 'testShpConv', 'testLine.shp')

    # do we react properly when the input line exceeds the dem?
    with pytest.raises(Exception) as e:
        assert shpConv.readLine(shpFileName, '', dem)
    assert str(e.value) == "Nan Value encountered. Try with another path"

    # do we react properly when the input line exceeds the dem?
    shpFileName = os.path.join(dirname, 'data', 'testShpConv', 'testLineOut.shp')
    with pytest.raises(Exception) as e:
        assert shpConv.readLine(shpFileName, '', dem)
    assert str(e.value) == "The avalanche path exceeds dem extent. Try with another path"

    shpFileName = os.path.join(dirname, 'data', 'testShpConv', 'testLineGood.shp')
    Line = shpConv.readLine(shpFileName, '', dem)

    # check lines name
    atol = 1e-10
    assert Line['Name'] == ['goodLine']

    # check start index lines
    Sol = np.array([0])
    testRes = np.allclose(Line['Start'], Sol, atol=atol)
    assert testRes

    # check length lines
    Sol = np.array([3])
    testRes = np.allclose(Line['Length'], Sol, atol=atol)
    assert testRes

    # check line x coord
    Sol = np.array([19.34206385, 35.20773381, 83.14231115])
    testRes = np.allclose(Line['x'], Sol, atol=atol)
    assert testRes

    # check line y coord
    Sol = np.array([83.06609712, 72.43272257, 71.42002023])
    testRes = np.allclose(Line['y'], Sol, atol=atol)
    assert testRes

    # check line z coord
    Sol = np.array([0., 0., 0.])
    testRes = np.allclose(Line['z'], Sol, atol=atol)
    assert testRes
Пример #2
0
def com2ABMain(cfg, avalancheDir):
    """ Main AlphaBeta model function

    Loops on the given AvaPaths and runs com2AB to compute AlpahBeta model

    Parameters
    ----------
    cfg : configparser
        configparser with all requiered fields in com2ABCfg.ini
    avalancheDir : str
        path to directory of avalanche to analyze

    Returns
    -------
    resAB : dict
        dictionary with AlphaBeta model results
    """
    abVersion = '4.1'
    cfgsetup = cfg['ABSETUP']
    smallAva = cfgsetup.getboolean('smallAva')
    resAB = {}
    # Extract input file locations
    cfgPath = readABinputs(avalancheDir)

    log.info(
        "Running com2ABMain model on DEM \n \t %s \n \t with profile \n \t %s ",
        cfgPath['demSource'], cfgPath['profileLayer'])

    resAB['saveOutPath'] = cfgPath['saveOutPath']
    # Read input data for ALPHABETA
    dem = IOf.readRaster(cfgPath['demSource'])
    resAB['dem'] = dem
    AvaPath = shpConv.readLine(cfgPath['profileLayer'], cfgPath['defaultName'],
                               dem)
    resAB['AvaPath'] = AvaPath
    resAB['splitPoint'] = shpConv.readPoints(cfgPath['splitPointSource'], dem)

    # Read input setup
    eqParams = setEqParameters(cfg, smallAva)
    resAB['eqParams'] = eqParams

    NameAva = AvaPath['Name']
    StartAva = AvaPath['Start']
    LengthAva = AvaPath['Length']

    for i in range(len(NameAva)):
        name = NameAva[i]
        start = StartAva[i]
        end = start + LengthAva[i]
        avapath = {}
        avapath['x'] = AvaPath['x'][int(start):int(end)]
        avapath['y'] = AvaPath['y'][int(start):int(end)]
        avapath['Name'] = name
        log.info('Running Alpha Beta %s on: %s ', abVersion, name)
        resAB = com2ABKern(avapath, resAB, cfgsetup.getfloat('distance'),
                           cfgsetup.getfloat('dsMin'))

        if cfg.getboolean('FLAGS', 'fullOut'):
            # saving results to pickle saveABResults(resAB, name)
            savename = name + '_com2AB_eqparam.pickle'
            save_file = os.path.join(cfgPath['saveOutPath'], savename)
            pickle.dump(resAB['eqParams'], open(save_file, "wb"))
            log.info('Saving intermediate results to: %s' % (save_file))
            savename = name + '_com2AB_eqout.pickle'
            save_file = os.path.join(cfgPath['saveOutPath'], savename)
            pickle.dump(resAB[name], open(save_file, "wb"))
            log.info('Saving intermediate results to: %s' % (save_file))

    return resAB
Пример #3
0
def makeDomainTransfo(cfgPath, cfgSetup, cfgFlags):
    """
    Make domain transformation :
    This function returns the information about this domain transformation
    Data given on a regular grid is projected on a nonuniform grid following
    a polyline

    input: cfgPath, cfgSetup, cfgFlags
    ouput: rasterTransfo as a dictionary
            -(gridx,gridy) coordinates of the points of the new raster
            -(s,l) new coordinate System
            -(x,y) coordinates of the resampled polyline
            -rasterArea, real area of the cells of the new raster
            -indRunoutPoint start of the runout area

    """
    # Read input parameters
    rasterSource = cfgPath['pressurefileList'][0]
    demSource = cfgPath['demSource']
    ProfileLayer = cfgPath['profileLayer']
    outpath = cfgPath['pathResult']
    DefaultName = cfgPath['projectName']

    w = float(cfgSetup['domainWidth'])
    runoutAngle = float(cfgSetup['runoutAngle'])
    interpMethod = cfgSetup['interpMethod']

    log.info('Data-file %s analysed' % rasterSource)
    # read data
    # read raster data
    sourceData = IOf.readRaster(rasterSource)
    dem = IOf.readRaster(demSource)
    header = sourceData['header']
    xllc = header.xllcorner
    yllc = header.yllcorner
    cellsize = header.cellsize
    rasterdata = sourceData['rasterData']
    # Initialize transformation dictionary
    rasterTransfo = {}
    rasterTransfo['domainWidth'] = w
    rasterTransfo['xllc'] = xllc
    rasterTransfo['yllc'] = yllc
    rasterTransfo['cellsize'] = cellsize

    # read avaPath
    Avapath = shpConv.readLine(ProfileLayer, DefaultName, sourceData['header'])
    # read split point
    splitPoint = shpConv.readPoints(cfgPath['splitPointSource'],
                                    sourceData['header'])
    # add 'z' coordinate to the avaPath
    Avapath = geoTrans.projectOnRaster(dem, Avapath)
    # reverse avaPath if necessary
    _, Avapath = geoTrans.checkProfile(Avapath, projSplitPoint=None)

    log.info('Creating new raster along polyline: %s' % ProfileLayer)

    # Get new Domain Boundaries DB
    # input: ava path
    # output: Left and right side points for the domain
    rasterTransfo = geoTrans.path2domain(Avapath, rasterTransfo)

    # Make transformation matrix
    rasterTransfo = makeTransfoMat(rasterTransfo)

    # calculate the real area of the new cells as well as the scoord
    rasterTransfo = getSArea(rasterTransfo)

    log.info('Size of rasterdata- old: %d x %d - new: %d x %d' %
             (np.size(rasterdata, 0), np.size(
                 rasterdata, 1), np.size(rasterTransfo['gridx'], 0),
              np.size(rasterTransfo['gridx'], 1)))

    ##########################################################################
    # affect values
    rasterTransfo['header'] = header
    # put back scale and origin
    rasterTransfo['s'] = rasterTransfo['s'] * cellsize
    rasterTransfo['l'] = rasterTransfo['l'] * cellsize
    rasterTransfo['gridx'] = rasterTransfo['gridx'] * cellsize + xllc
    rasterTransfo['gridy'] = rasterTransfo['gridy'] * cellsize + yllc
    rasterTransfo[
        'rasterArea'] = rasterTransfo['rasterArea'] * cellsize * cellsize
    # (x,y) coordinates of the resamples avapth (centerline where l = 0)
    n = np.shape(rasterTransfo['l'])[0]
    indCenter = int(np.floor(n / 2) + 1)
    rasterTransfo['x'] = rasterTransfo['gridx'][:, indCenter]
    rasterTransfo['y'] = rasterTransfo['gridy'][:, indCenter]

    #################################################################
    # add 'z' coordinate to the centerline
    rasterTransfo = geoTrans.projectOnRaster(dem, rasterTransfo)
    # find projection of split point on the centerline centerline
    projPoint = geoTrans.findSplitPoint(rasterTransfo, splitPoint)
    rasterTransfo['indSplit'] = projPoint['indSplit']
    # prepare find start of runout area points
    log.info('Measuring run-out length from the %s ° point' % runoutAngle)
    rasterTransfo['runoutAngle'] = runoutAngle
    _, tmp, delta_ind = geoTrans.prepareAngleProfile(runoutAngle,
                                                     rasterTransfo)
    # find the runout point: first point under runoutAngle
    indRunoutPoint = geoTrans.findAngleProfile(tmp, delta_ind)
    rasterTransfo['indRunoutPoint'] = indRunoutPoint

    avalData = transform(rasterSource, rasterTransfo, interpMethod)

    ###########################################################################
    # visualisation
    inputData = {}
    inputData['avalData'] = avalData
    inputData['sourceData'] = sourceData
    inputData['Avapath'] = Avapath

    outAimec.visuTransfo(rasterTransfo, inputData, cfgPath, cfgFlags)

    return rasterTransfo
Пример #4
0
def makeDomainTransfo(cfgPath, cfgSetup):
    """ Make domain transformation

    This function returns the information about the domain transformation
    Data given on a regular grid is projected on a nonuniform grid following
    a polyline to end up with "straightend raster"

    Parameters
    ----------
    cfgPath : dict
        dictionary with path to data to analyze
    cfgSetup : configparser
        configparser with ana3AIMEC settings defined in ana3AIMECCfg.ini
        regarding domain transformation (domain width w, startOfRunoutAreaAngle or
        interpolation method)

    Returns
    -------
    rasterTransfo: dict
        domain transformation information:
            gridx: 2D numpy array
                x coord of the new raster points in old coord system
            gridy: 2D numpy array
                y coord of the new raster points in old coord system
            s: 1D numpy array
                new coord system in the polyline direction
            l: 1D numpy array
                new coord system in the cross direction
            x: 1D numpy array
                coord of the resampled polyline in old coord system
            y: 1D numpy array
                coord of the resampled polyline in old coord system
            rasterArea: 2D numpy array
                real area of the cells of the new raster
            indStartOfRunout: int
                index for start of the runout area (in s)
    """
    # Read input parameters
    demSource = cfgPath['demSource']
    ProfileLayer = cfgPath['profileLayer']
    splitPointSource = cfgPath['splitPointSource']
    DefaultName = cfgPath['projectName']

    w = float(cfgSetup['domainWidth'])
    startOfRunoutAreaAngle = float(cfgSetup['startOfRunoutAreaAngle'])

    log.info('Data-file %s analysed' % demSource)
    # read data
    # read dem data
    dem = IOf.readRaster(demSource)
    header = dem['header']
    xllc = header.xllcenter
    yllc = header.yllcenter
    cellSize = header.cellsize
    rasterdata = dem['rasterData']
    # Initialize transformation dictionary
    rasterTransfo = {}
    rasterTransfo['domainWidth'] = w
    rasterTransfo['xllc'] = xllc
    rasterTransfo['yllc'] = yllc
    rasterTransfo['cellSize'] = cellSize

    # read avaPath
    avaPath = shpConv.readLine(ProfileLayer, DefaultName, dem)
    # read split point
    splitPoint = shpConv.readPoints(splitPointSource, dem)
    # add 'z' coordinate to the avaPath
    avaPath, _ = geoTrans.projectOnRaster(dem, avaPath)
    # reverse avaPath if necessary
    _, avaPath = geoTrans.checkProfile(avaPath, projSplitPoint=None)

    log.info('Creating new raster along polyline: %s' % ProfileLayer)

    # Get new Domain Boundaries DB
    # input: ava path
    # output: Left and right side points for the domain
    rasterTransfo = geoTrans.path2domain(avaPath, rasterTransfo)

    # Make transformation matrix
    rasterTransfo = makeTransfoMat(rasterTransfo)

    # calculate the real area of the new cells as well as the scoord
    rasterTransfo = getSArea(rasterTransfo)

    log.debug('Size of rasterdata- old: %d x %d - new: %d x %d' %
              (np.size(rasterdata, 0), np.size(
                  rasterdata, 1), np.size(rasterTransfo['gridx'], 0),
               np.size(rasterTransfo['gridx'], 1)))

    ##########################################################################
    rasterTransfo['header'] = header
    # put back scale and origin
    rasterTransfo['s'] = rasterTransfo['s'] * cellSize
    rasterTransfo['l'] = rasterTransfo['l'] * cellSize
    rasterTransfo['gridx'] = rasterTransfo['gridx'] * cellSize + xllc
    rasterTransfo['gridy'] = rasterTransfo['gridy'] * cellSize + yllc
    rasterTransfo[
        'rasterArea'] = rasterTransfo['rasterArea'] * cellSize * cellSize
    # (x,y) coordinates of the resamples avapth (centerline where l = 0)
    n = np.shape(rasterTransfo['l'])[0]
    indCenter = int(np.floor(n / 2))
    rasterTransfo['x'] = rasterTransfo['gridx'][:, indCenter]
    rasterTransfo['y'] = rasterTransfo['gridy'][:, indCenter]

    #################################################################
    # add 'z' coordinate to the centerline
    rasterTransfo, _ = geoTrans.projectOnRaster(dem, rasterTransfo)
    # find projection of split point on the centerline centerline
    projPoint = geoTrans.findSplitPoint(rasterTransfo, splitPoint)
    rasterTransfo['indSplit'] = projPoint['indSplit']
    # prepare find start of runout area points
    angle, tmp, ds = geoTrans.prepareAngleProfile(startOfRunoutAreaAngle,
                                                  rasterTransfo)
    # find the runout point: first point under startOfRunoutAreaAngle
    indStartOfRunout = geoTrans.findAngleProfile(tmp, ds,
                                                 cfgSetup.getfloat('dsMin'))
    rasterTransfo['indStartOfRunout'] = indStartOfRunout
    rasterTransfo['xBetaPoint'] = rasterTransfo['x'][indStartOfRunout]
    rasterTransfo['yBetaPoint'] = rasterTransfo['y'][indStartOfRunout]
    rasterTransfo['startOfRunoutAreaAngle'] = angle[indStartOfRunout]
    log.info(
        'Measuring run-out length from the %.2f ° point of coordinates (%.2f, %.2f)'
        % (rasterTransfo['startOfRunoutAreaAngle'],
           rasterTransfo['xBetaPoint'], rasterTransfo['yBetaPoint']))

    return rasterTransfo
Пример #5
0
cfg = cfgUtils.getModuleConfig(com2AB)

cfgSetup = cfg['ABSETUP']
cfgFlags = cfg['FLAGS']

# Dump config to log file
logUtils.writeCfg2Log(cfg, 'com2AB')

# Extract input file locations
cfgPath = com2AB.readABinputs(avalancheDir)

log.info(
    "Running com2ABMain model on DEM \n \t %s \n \t with profile \n \t %s ",
    cfgPath['demSource'], cfgPath['profileLayer'])

# Read input data for ALPHABETA
dem = IOf.readRaster(cfgPath['demSource'])
avaPath = shpConv.readLine(cfgPath['profileLayer'], cfgPath['defaultName'],
                           dem['header'])
splitPoint = shpConv.readPoints(cfgPath['splitPointSource'], dem['header'])

# Calculate ALPHABETA
com2AB.com2ABMain(dem, avaPath, splitPoint, cfgPath['saveOutPath'], cfgSetup)

# Analyse/ plot/ write results #
plotFile, writeFile = outAB.writeABpostOut(dem, avaPath, splitPoint,
                                           cfgPath['saveOutPath'], cfgFlags)

log.info('Plotted to: %s', plotFile)
log.info('Data written: %s', writeFile)