def visuComparison(rasterTransfo, inputs, cfgPath, cfgFlags): """ Plot and save the comparison between current simulation and Reference in the run-out area """ #################################### # Get input data # read paths projectName = cfgPath['projectName'] # read data s = rasterTransfo['s'] l = rasterTransfo['l'] indStartOfRunout = rasterTransfo['indStartOfRunout'] sStart = s[indStartOfRunout] runoutLength = inputs['runoutLength'] refData = inputs['refData'] compData = inputs['compData'] refRasterMask = inputs['refRasterMask'] newRasterMask = inputs['newRasterMask'] i = inputs['i'] resType = inputs['resType'] unit = pU.cfgPlotUtils['unit' + resType] name = pU.cfgPlotUtils['name' + resType] thresholdArray = inputs['thresholdArray'] thresholdValue = thresholdArray[-1] contCmap = cfgPath['contCmap'] ############################################ # Figure: Raster comparison (mask for the pThreshold given in the ini file) fig = plt.figure(figsize=(pU.figW * 2, pU.figH)) ax1 = plt.subplot2grid((1, 2), (0, 0)) # get color map cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, thresholdValue, np.nanmax((refData)), continuous=contCmap) cmap.set_bad(color='w') refDataPlot = np.ma.masked_where(refData == 0.0, refData) ref0, im = pU.NonUnifIm(ax1, l, s, refDataPlot, 'l [m]', 's [m]', extent=[l.min(), l.max(), s.min(), s.max()], cmap=cmap, norm=norm) ax1.axhline(y=s[indStartOfRunout], color='k', linestyle='--', label='start of run-out area point : %.1f °' % rasterTransfo['startOfRunoutAreaAngle']) ax1.set_title('Reference %s in the RunOut area' % name + '\n' + '%s threshold: %.1f %s' % (name, thresholdValue, unit)) pU.addColorBar(im, ax1, ticks, unit) yLim = s[max(np.max(np.nonzero(np.any(refData != 0, axis=1))[0]), np.max(np.nonzero(np.any(compData != 0, axis=1))[0]))] ax1.set_ylim([0, yLim]) ax1.legend(loc='lower right') pU.putAvaNameOnPlot(ax1, projectName) ax2 = plt.subplot2grid((1, 2), (0, 1)) colorsList = [[0, 0, 1], [1, 1, 1], [1, 0, 0]] cmap = matplotlib.colors.ListedColormap(colorsList) cmap.set_under(color='b') cmap.set_over(color='r') cmap.set_bad(alpha=0) data = newRasterMask - refRasterMask data = np.ma.masked_where(data == 0.0, data) ref1, im1 = pU.NonUnifIm(ax2, l, s, data, 'l [m]', 's [m]', extent=[l.min(), l.max(), s.min(), s.max()], cmap=cmap) if cfgPath['compType'][0] == 'comModules': namePrint = 'refMod:' + cfgPath['compType'][ 1] + '_' + 'compMod:' + cfgPath['compType'][2] pU.putAvaNameOnPlot(ax2, namePrint) ax2.set_ylim([s[indStartOfRunout], yLim]) ax2.set_title('Difference %s current - reference in runout area' % resType + '\n' + 'Blue = FN, Red = FP') outFileName = '_'.join([ projectName, 'thresholdValue', str(thresholdValue).replace('.', 'p'), 'sim', str(i), 'AreaComparisonToReference' ]) pU.saveAndOrPlot(cfgPath, cfgFlags, outFileName, fig) ############################################ # Figure: Raster comparison fig = plt.figure(figsize=(pU.figW * 3, pU.figH * 2)) #, constrained_layout=True) ax1 = plt.subplot2grid((3, 3), (0, 0), rowspan=3) # get color map cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, thresholdValue, np.nanmax((refData)), continuous=pU.contCmap) cmap.set_bad(color='w') refDataPlot = np.ma.masked_where(refData == 0.0, refData) ref0, im = pU.NonUnifIm(ax1, l, s, refDataPlot, 'l [m]', 's [m]', extent=[l.min(), l.max(), 0, yLim], cmap=cmap, norm=norm) ax1.axhline(y=s[indStartOfRunout], color='k', linestyle='--', label='start of run-out area point : %.1f °' % rasterTransfo['startOfRunoutAreaAngle']) ax1.set_title('Reference %s' % name) pU.addColorBar(im, ax1, ticks, unit) ax1.set_ylim([0, yLim]) ax1.legend(loc='lower right') pU.putAvaNameOnPlot(ax1, projectName) compData = compData[indStartOfRunout:, :] refData = refData[indStartOfRunout:, :] dataDiff = compData - refData dataDiff = np.where((refData == 0) & (compData == 0), np.nan, dataDiff) dataDiffPlot = dataDiff[np.isnan(dataDiff) == False] # only plot hist and CDF if there is a difference in the data if dataDiffPlot.size: indDiff = dataDiffPlot > 0 if indDiff.any(): ax2 = plt.subplot2grid((3, 3), (0, 1), rowspan=2, colspan=2) else: ax2 = plt.subplot2grid((3, 3), (0, 1), rowspan=3, colspan=3) cmap = pU.cmapdiv cmap.set_bad(color='w') elev_max = inputs['diffLim'] ref0, im3 = pU.NonUnifIm( ax2, l, s[indStartOfRunout:], (dataDiff), 'l [m]', 's [m]', extent=[l.min(), l.max(), s[indStartOfRunout:].min(), yLim], cmap=cmap) im3.set_clim(vmin=-elev_max, vmax=elev_max) L, S = np.meshgrid(l, s[indStartOfRunout:]) colorsP = pU.cmapPres['colors'][1:5] contourRef = ax2.contour(L, S, refData, levels=thresholdArray[:-1], linewidths=1, colors=colorsP) contourComp = ax2.contour(L, S, compData, levels=thresholdArray[:-1], linewidths=1, colors=colorsP, linestyles='dashed') labels = [str(level) + unit for level in thresholdArray[:-1]] for j in range(len(contourRef.collections)): contourRef.collections[j].set_label(labels[j]) ax2.set_title('%s difference and contour lines' % name + '\n' + 'refMod = full, compMod = dashed line') if cfgPath['compType'][0] == 'comModules': namePrint = 'refMod:' + cfgPath['compType'][ 1] + '_' + 'compMod:' + cfgPath['compType'][2] pU.putAvaNameOnPlot(ax2, namePrint) ax2.set_ylim([s[indStartOfRunout], yLim]) ax2.legend(loc='lower right') pU.addColorBar(im3, ax2, ticks, unit, title=name, extend='both') # only plot hist and CDF if there is a difference in the data if dataDiffPlot.size: indDiff = dataDiffPlot > 0 if indDiff.any(): ax3 = plt.subplot2grid((3, 3), (2, 1)) ax4 = plt.subplot2grid((3, 3), (2, 2)) # there is data to compare in the run out area centiles = sPlot.plotHistCDFDiff( dataDiffPlot, ax4, ax3, insert='False', title=[ '%s diff histogram' % name, '%s diff CDF (95%% and 99%% centiles)' % name ]) else: log.warning('No data in the run out area!') fig.subplots_adjust(hspace=0.3, wspace=0.3) outFileName = '_'.join([ projectName, 'plim', str(thresholdValue).replace('.', 'p'), 'sim', str(i), 'ContourComparisonToReference' ]) pU.saveAndOrPlot(cfgPath, cfgFlags, outFileName, fig) outFilePath = os.path.join(cfgPath['pathResult'], 'pics', outFileName + '.png') return outFilePath
def visuTransfo(rasterTransfo, inputData, cfgSetup, cfgPath, cfgFlags): """ Plot and save the domain transformation figure """ #################################### # Get input data resType = cfgSetup['resType'] unit = pU.cfgPlotUtils['unit' + resType] # read paths projectName = cfgPath['projectName'] # read rasterdata slRaster = inputData['slRaster'] xyRaster = inputData['xyRaster'] # read avaPath with scale xPath = rasterTransfo['x'] yPath = rasterTransfo['y'] # read domain boundarries with scale xllc = rasterTransfo['xllc'] yllc = rasterTransfo['yllc'] cellSize = rasterTransfo['cellSize'] DBXl = rasterTransfo['DBXl'] * cellSize + xllc DBXr = rasterTransfo['DBXr'] * cellSize + xllc DBYl = rasterTransfo['DBYl'] * cellSize + yllc DBYr = rasterTransfo['DBYr'] * cellSize + yllc ############################################ # prepare for plot n, m = np.shape(xyRaster) x = np.arange(m) * cellSize + xllc y = np.arange(n) * cellSize + yllc indStartOfRunout = rasterTransfo['indStartOfRunout'] xx = rasterTransfo['x'][indStartOfRunout] yy = rasterTransfo['y'][indStartOfRunout] l = rasterTransfo['l'] s = rasterTransfo['s'] maskedArray = np.ma.masked_where(xyRaster == 0, xyRaster) maskedArraySL = np.ma.masked_where(slRaster == 0, slRaster) cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, 0.0, np.nanmax(maskedArray), continuous=pU.contCmap) cmap.set_under(color='w') ############################################ # Figure: Raster transformation fig = plt.figure(figsize=(pU.figW * 2, pU.figH)) ax1 = plt.subplot(121) ref0, im = pU.NonUnifIm(ax1, x, y, maskedArray, 'x [m]', 'y [m]', extent=[x.min(), x.max(), y.min(), y.max()], cmap=cmap, norm=norm) plt.plot(xx, yy, 'k+', label='start of run-out area point : %.1f °' % rasterTransfo['startOfRunoutAreaAngle']) plt.plot(xPath, yPath, 'k--', label='flow path') plt.plot(DBXl, DBYl, 'k-', label='domain') plt.plot(DBXr, DBYr, 'k-') plt.plot([DBXl, DBXr], [DBYl, DBYr], 'k-') ax1.set_title('XY Domain') ax1.legend(loc=4) pU.putAvaNameOnPlot(ax1, cfgPath['projectName']) ax2 = plt.subplot(122) ref0, im = pU.NonUnifIm(ax2, l, s, maskedArraySL, 'l [m]', 's [m]', extent=[l.min(), l.max(), s.min(), s.max()], cmap=cmap, norm=norm) ax2.axhline(y=s[indStartOfRunout], color='k', linestyle='--', label='start of run-out area point : %.1f °' % rasterTransfo['startOfRunoutAreaAngle']) ax2.set_title('sl Domain' + '\n' + 'Black = out of raster') ax2.legend(loc=4) pU.addColorBar(im, ax2, ticks, unit) outFileName = '_'.join([projectName, 'DomainTransformation']) pU.saveAndOrPlot(cfgPath, cfgFlags, outFileName, fig)
def visuSimple(rasterTransfo, resAnalysis, newRasters, cfgPath, cfgFlags): """ Plot and save the Peak Pressure Peak Flow depth and Peak speed fields after coord transfo """ #################################### # Get input data # read paths projectName = cfgPath['projectName'] nRef = cfgPath['referenceFile'] # read data plim = resAnalysis['thresholdValue'] s = rasterTransfo['s'] l = rasterTransfo['l'] indStartOfRunout = rasterTransfo['indStartOfRunout'] dataPressure = newRasters['newRasterPPR'] rasterdataPres = dataPressure[nRef] dataDepth = newRasters['newRasterPFD'] rasterdataDepth = dataDepth[nRef] dataSpeed = newRasters['newRasterPFV'] rasterdataSpeed = dataSpeed[nRef] runout = resAnalysis['runout'][0] ############################################ # prepare for plot Cmap = [pU.cmapPres, pU.cmapDepth, pU.cmapSpeed] Title = ['Peak Pressure', 'Peak Flow Depth', 'Peak Speed'] Unit = [ pU.cfgPlotUtils['unitppr'], pU.cfgPlotUtils['unitpfd'], pU.cfgPlotUtils['unitpfv'] ] Data = np.array(([None] * 3)) Data[0] = rasterdataPres Data[1] = rasterdataDepth Data[2] = rasterdataSpeed ############################################ # Figure: Pressure depth speed fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(pU.figW * 3, pU.figH)) fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, hspace=0.3) for ax, cmap, data, title, unit in zip(axes.flatten(), Cmap, Data, Title, Unit): maskedArray = np.ma.masked_where(data == 0, data) cmap, _, _, norm, ticks = makePalette.makeColorMap( cmap, 0.0, np.nanmax(maskedArray), continuous=pU.contCmap) cmap.set_bad('w', 1.) ax.axhline(y=runout[0], color='k', linestyle='-', label='runout') ax.axhline(y=s[indStartOfRunout], color='k', linestyle='--', label='Start or run-out point : %.1f °' % resAnalysis['startOfRunoutAreaAngle']) ref3, im = pU.NonUnifIm(ax, l, s, maskedArray, 'l [m]', 's [m]', extent=[l.min(), l.max(), s.min(), s.max()], cmap=cmap, norm=norm) ax.set_title(title) ax.legend(loc=4) pU.addColorBar(im, ax, ticks, unit) pU.putAvaNameOnPlot(ax, cfgPath['projectName']) outFileName = '_'.join([ projectName, 'plim', str((plim)).replace('.', 'p'), 'referenceFields' ]) pU.saveAndOrPlot(cfgPath, cfgFlags, outFileName, fig)
def visuRunoutStat(rasterTransfo, resAnalysis, newRasters, cfgSetup, cfgPath, cfgFlags): """ Plot and save the Peak field distribution after coord transfo used when more then 2 simulations are compared """ #################################### # Get input data resType = cfgSetup['resType'] thresholdValue = cfgSetup['thresholdValue'] unit = pU.cfgPlotUtils['unit' + resType] name = pU.cfgPlotUtils['name' + resType] # read paths projectName = cfgPath['projectName'] nRef = cfgPath['referenceFile'] # read data s = rasterTransfo['s'] l = rasterTransfo['l'] indStartOfRunout = rasterTransfo['indStartOfRunout'] dataPressure = newRasters['newRaster' + resType.upper()] rasterdataPres = dataPressure[nRef] runout = resAnalysis['runout'][0] PPRCrossMax = resAnalysis[resType.upper() + 'CrossMax'] ############################################ # prepare for plot pMean = np.mean(PPRCrossMax, axis=0) pMedian = np.median(PPRCrossMax, axis=0) pPercentile = np.percentile(PPRCrossMax, [2.5, 50, 97.5], axis=0) maskedArray = np.ma.masked_where(rasterdataPres == 0, rasterdataPres) cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, 0.0, np.nanmax(maskedArray), continuous=pU.contCmap) cmap.set_bad('w', 1.) ############################################ # Figure: Analysis runout fig = plt.figure(figsize=(pU.figW * 2, pU.figH)) ax1 = plt.subplot(121) ax1.axhline(y=np.max(runout), color='k', linestyle='-.', label='runout max') ax1.axhline(y=np.average(runout), color='k', linestyle='-', label='runout mean') ax1.axhline(y=np.min(runout), color='k', linestyle=':', label='runout min') ax1.axhline(y=s[indStartOfRunout], color='k', linestyle='--', label='start of run-out area point : %.1f °' % resAnalysis['startOfRunoutAreaAngle']) ref5, im = pU.NonUnifIm(ax1, l, s, maskedArray, 'l [m]', 's [m]', extent=[l.min(), l.max(), s.min(), s.max()], cmap=cmap, norm=norm) ax1.set_title('Peak Pressure 2D plot for the reference') ax1.legend(loc=4) pU.putAvaNameOnPlot(ax1, projectName) pU.addColorBar(im, ax1, ticks, unit) ax2 = plt.subplot(122) ax2.fill_betweenx(s, pPercentile[2], pPercentile[0], facecolor=[.8, .8, .8], alpha=0.5, label='quantiles') matplotlib.patches.Patch(alpha=0.5, color=[.8, .8, .8]) ax2.plot(pMedian, s, color='r', label='median') ax2.plot(pMean, s, color='b', label='mean') ax2.set_title('%s distribution along the path between runs' % name) ax2.legend(loc=4) ax2.set_ylabel('s [m]') ax2.set_ylim([s.min(), s.max()]) ax2.set_xlim(auto=True) ax2.set_xlabel('$P_{max}(s)$ [%s]' % unit) outFileName = '_'.join([ projectName, resType, 'thresholdValue', str(thresholdValue).replace('.', 'p'), 'slComparisonStat' ]) pU.saveAndOrPlot(cfgPath, cfgFlags, outFileName, fig)
def generateOnePlot(dataDict, outDir, cfg, plotDict): """ Create plots of ascii dataset Parameters ---------- dataDict : dict dictionary with info on both datasets to be plotted avaName : str name of avalanche outDir : str path to dictionary where plots shall be saved to cfg : dict main configuration settings plotDict : dict dictionary with information about plots, for example release area Returns ------- plotDict : dict updated plot dictionary with info about e.g. min, mean, max of difference between datasets """ # Extract info for plotting data1 = dataDict['data1'] name1 = dataDict['name1'] cellSize = dataDict['cellSize'] simName = 'Analyse' if plotDict['resType'] != '': unit = pU.cfgPlotUtils['unit%s' % plotDict['resType']] nameRes = pU.cfgPlotUtils['name%s' % plotDict['resType']] else: unit = '' nameRes = 'Result parameter' # Set dimensions of plots ny = data1.shape[0] nx = data1.shape[1] Ly = ny * cellSize Lx = nx * cellSize axis = plotDict['axis'] # Location of Profiles location = float(plotDict['location']) if axis == 'x': nx_loc = int(location / cellSize) elif axis == 'y': ny_loc = int(location / cellSize) else: log.error('Not an axis, please provide axis of profile') # Plot data # Figure 1 shows the result parameter data fig = plt.figure(figsize=(pU.figW * 2, pU.figH)) suptitle = fig.suptitle(name1, fontsize=14, color='0.5') ax1 = fig.add_subplot(121) cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, np.nanmin(data1), np.nanmax(data1), continuous=pU.contCmap) im1 = plt.imshow(data1, cmap=cmap, extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny, norm=norm) pU.addColorBar(im1, ax1, ticks, unit) ax1.set_aspect('auto') title = str('%s' % name1) ax1.set_title(title) ax1.set_xlabel('x [m]') ax1.set_ylabel('y [m]') ax3 = fig.add_subplot(122) if axis == 'x': ax3.plot(data1[:, nx_loc], 'k', label='Reference') else: ax3.plot(data1[ny_loc, :], 'k', label='Reference') ax3.set_xlabel('Location across track [nrows]') ax3.set_ylabel('%s [%s]' % (nameRes, unit)) if axis == 'x': ax3.set_title('Profile at x ~ %d [%s] (%d)' % (location, unit, nx_loc)) else: ax3.set_title('Profile at y ~ %d [%s] (%d)' % (location, unit, ny_loc)) fig.savefig( os.path.join(outDir, 'Profiles_%s.%s' % (name1, pU.outputFormat))) log.info('Figures saved to: %s' % outDir) if cfg['FLAGS'].getboolean('showPlot'): plt.show() plotDict['plots'].append( os.path.join(outDir, 'Profiles_%s.%s' % (name1, pU.outputFormat))) plt.close('all') return plotDict
def generatePlot(dataDict, avaName, outDir, cfg, plotDict): """ Create plots of two ascii datasets that shall be compared Parameters ---------- dataDict : dict dictionary with info on both datasets to be plotted avaName : str name of avalanche outDir : str path to dictionary where plots shall be saved to cfg : dict main configuration settings plotDict : dict dictionary with information about plots, for example release area Returns ------- plotDict : dict updated plot dictionary with info about e.g. min, mean, max of difference between datasets """ # Extract info for plotting data1 = dataDict['data1'] data2 = dataDict['data2'] name1 = dataDict['name1'] name2 = dataDict['name2'] cellSize = dataDict['cellSize'] if dataDict['compareType'] == 'compToRef': simName = dataDict['simName'] + '_' + dataDict['suffix'] unit = dataDict['unit'] else: simName = 'compare' unit = '' # Set dimensions of plots ny = data2.shape[0] nx = data2.shape[1] Ly = ny * cellSize Lx = nx * cellSize # Location of Profiles ny_loc = int(nx * 0.5) nx_loc = int(ny * 0.5) # Difference between datasets dataDiff = data1 - data2 dataDiff = np.where((data1 == 0) & (data2 == 0), np.nan, dataDiff) diffMax = np.nanmax(dataDiff) diffMin = np.nanmin(dataDiff) diffMean = np.nanmean(dataDiff) # Location of box nybox = int(nx * 0.2) nxbox = int(ny * 0.2) minVal = min(np.nanmin(data1), np.nanmin(data2)) maxVal = max(np.nanmax(data1), np.nanmax(data2)) # Plot data # Figure 1 shows the result parameter data fig = plt.figure(figsize=(pU.figW * 3, pU.figH * 2)) suptitle = fig.suptitle(avaName, fontsize=14, color='0.5') ax1 = fig.add_subplot(221) cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, np.nanmin(data1), np.nanmax(data1), continuous=pU.contCmap) cmap.set_bad('w') data1P = ma.masked_where(data1 == 0.0, data1) im1 = plt.imshow(data1P, cmap=cmap, extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny, norm=norm, vmin=minVal, vmax=maxVal) pU.addColorBar(im1, ax1, ticks, unit) ax1.set_aspect('auto') title = str('%s' % name1) ax1.set_title(title) ax1.set_xlabel('x [m]') ax1.set_ylabel('y [m]') ax2 = fig.add_subplot(222) cmap, _, _, norm, ticks = makePalette.makeColorMap(pU.cmapPres, np.nanmin(data2), np.nanmax(data2), continuous=pU.contCmap) cmap.set_bad('w') data2P = ma.masked_where(data2 == 0.0, data2) im2 = plt.imshow(data2P, cmap=cmap, extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny, norm=norm, vmin=minVal, vmax=maxVal) pU.addColorBar(im2, ax2, ticks, unit) ax2.set_aspect('auto') ax2.set_xlabel('x [m]') title = str('%s' % name2) ax2.set_title(title) ax3 = fig.add_subplot(223) cmap = pU.cmapdiv elev_max = np.nanmax(np.abs(dataDiff)) im3 = plt.imshow(dataDiff, cmap=cmap, clim=(-elev_max, elev_max), extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny) pU.addColorBar(im3, ax3, None, unit) ax3.text(nybox, nxbox, 'Mean: %.2e %s\n Max: %.2e %s\n Min: %.2e %s' % (diffMean, unit, diffMax, unit, diffMin, unit), horizontalalignment='left', verticalalignment='bottom') ax3.set_aspect('auto') ax3.set_xlabel('x [m]') ax3.set_title('Difference ref-sim') # for difference histogramm - remove dataDiff == 0 values from array dataDiffPlot = dataDiff[np.isnan(dataDiff) == False] ax4 = fig.add_subplot(224) cmap = pU.cmapdiv if 'suffix' in dataDict: if dataDict['suffix'] == 'pfd': elev_max = 1 elif dataDict['suffix'] == 'ppr': elev_max = 100 elif dataDict['suffix'] == 'pfv': elev_max = 10 ax4.set_title('Difference capped at max difference in %s: +-%d %s' % (dataDict['suffix'], elev_max, unit)) else: cutVal = 0.5 elev_max = cutVal * elev_max ax4.set_title( 'Difference capped at %.1f times max difference: +-%.2f' % (cutVal, elev_max)) # for difference histogramm - remove dataDiff == 0 values from array dataDiffZoom = np.where( (dataDiffPlot < -elev_max) | (dataDiffPlot > elev_max), np.nan, dataDiffPlot) diffMaxZoom = np.nanmax(dataDiffZoom) diffMinZoom = np.nanmin(dataDiffZoom) diffMeanZoom = np.nanmean(dataDiffZoom) im4 = plt.imshow(dataDiff, cmap=cmap, clim=(-elev_max, elev_max), extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny) pU.addColorBar(im4, ax4, None, unit, extend='both') ax4.set_aspect('auto') ax4.set_xlabel('x [m]') # if difference is zero dont insert CDF plots indDiff = dataDiffPlot > 0 if indDiff.any(): axin3 = ax3.inset_axes([0.6, 0.1, 0.4, 0.25]) axin3.patch.set_alpha(0.0) axin4 = ax4.inset_axes([0.6, 0.1, 0.4, 0.25]) axin4.patch.set_alpha(0.0) centiles = sPlot.plotHistCDFDiff(dataDiffPlot, axin4, axin3) ax4.text(nybox, nxbox, '95%% centile: %.2e %s\n 99%% centile: %.2e %s' % (centiles[0], unit, centiles[1], unit), horizontalalignment='left', verticalalignment='bottom') fig.savefig( os.path.join(outDir, 'Diff_%s_%s.%s' % (avaName, simName, pU.outputFormat))) # Fgiure 2 cross and lonprofile fig, ax = plt.subplots(ncols=2, figsize=(pU.figW * 2, pU.figH)) suptitle = fig.suptitle(avaName, fontsize=14, color='0.5') ax[0].plot(data1[:, ny_loc], 'k', label='Reference') ax[0].plot(data2[:, ny_loc], 'b--', label='Simulation') ax[0].set_xlabel('Location across track [nrows]') ax[0].set_ylabel('Result parameter') ax[0].set_title('Cross profile at x = %d' % ny_loc) ax[1].plot(data1[nx_loc, :], 'k', label='Reference') ax[1].plot(data2[nx_loc, :], 'b--', label='Simulation') ax[1].set_xlabel('Location along track [ncols]') ax[1].set_ylabel('Result parameter') ax[1].set_title('Long profile at y = %d' % nx_loc) ax[0].legend() ax[1].legend() fig.savefig( os.path.join(outDir, 'Profiles_%s_%s.%s' % (avaName, simName, pU.outputFormat))) log.info('Figures saved to: %s' % outDir) if cfg['FLAGS'].getboolean('showPlot'): plt.show() plotDict['plots'].append( os.path.join(outDir, 'Diff_%s_%s.%s' % (avaName, simName, pU.outputFormat))) plotDict['difference'].append(diffMax) plotDict['difference'].append(diffMean) plotDict['difference'].append(diffMin) plotDict['stats'].append(np.amax(data2)) plotDict['stats'].append(np.amin(data2)) if 'differenceZoom' in plotDict: plotDict['differenceZoom'].append(diffMaxZoom) plotDict['differenceZoom'].append(diffMeanZoom) plotDict['differenceZoom'].append(diffMinZoom) plt.close('all') return plotDict
def plotAllPeakFields(avaDir, cfg, cfgFLAGS, modName): """ Plot all peak fields and return dictionary with paths to plots Parameters ---------- avaDir : str path to avalanche directoy cfg : dict configuration used to perform simulations cfgFLAGS : str general configuration, required to define if plots saved to reports directoy modName : str name of module that has been used to produce data to be plotted Returns ------- plotDict : dict dictionary with info on plots, like path to plot """ # Load all infos on simulations inputDir = os.path.join(avaDir, 'Outputs', modName, 'peakFiles') peakFiles = fU.makeSimDict(inputDir, '', avaDir) demFile = gI.getDEMPath(avaDir) demData = IOf.readRaster(demFile) demField = demData['rasterData'] # Output directory if cfgFLAGS.getboolean('ReportDir'): outDir = os.path.join(avaDir, 'Outputs', modName, 'reports') fU.makeADir(outDir) else: outDir = os.path.join(avaDir, 'Outputs', 'out1Peak') fU.makeADir(outDir) # Initialise plot dictionary with simulation names plotDict = {} for sName in peakFiles['simName']: plotDict[sName] = {} # Loop through peakFiles and generate plot for m in range(len(peakFiles['names'])): # Load names and paths of peakFiles name = peakFiles['names'][m] fileName = peakFiles['files'][m] avaName = peakFiles['avaName'][m] log.debug('now plot %s:' % (fileName)) # Load data raster = IOf.readRaster(fileName) data = raster['rasterData'] # constrain data to where there is data cellSize = peakFiles['cellSize'][m] rowsMin, rowsMax, colsMin, colsMax = pU.constrainPlotsToData( data, cellSize) dataConstrained = data[rowsMin:rowsMax + 1, colsMin:colsMax + 1] demConstrained = demField[rowsMin:rowsMax + 1, colsMin:colsMax + 1] data = np.ma.masked_where(dataConstrained == 0.0, dataConstrained) unit = pU.cfgPlotUtils['unit%s' % peakFiles['resType'][m]] # Set extent of peak file ny = data.shape[0] nx = data.shape[1] Ly = ny * cellSize Lx = nx * cellSize # Figure shows the result parameter data fig = plt.figure(figsize=(pU.figW, pU.figH)) fig, ax = plt.subplots() # choose colormap cmap, _, _, norm, ticks = makePalette.makeColorMap( pU.cmapPres, np.amin(data), np.amax(data), continuous=pU.contCmap) cmap.set_bad(alpha=0) rowsMinPlot = rowsMin * cellSize rowsMaxPlot = (rowsMax + 1) * cellSize colsMinPlot = colsMin * cellSize colsMaxPlot = (colsMax + 1) * cellSize im0 = ax.imshow( demConstrained, cmap='Greys', extent=[colsMinPlot, colsMaxPlot, rowsMinPlot, rowsMaxPlot], origin='lower', aspect='equal') im1 = ax.imshow( data, cmap=cmap, extent=[colsMinPlot, colsMaxPlot, rowsMinPlot, rowsMaxPlot], origin='lower', aspect='equal') pU.addColorBar(im1, ax, ticks, unit) title = str('%s' % name) ax.set_title(title) ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') plotName = os.path.join(outDir, '%s.%s' % (name, pU.outputFormat)) pU.putAvaNameOnPlot(ax, avaDir) fig.savefig(plotName) if cfgFLAGS.getboolean('showPlot'): plt.show() plotPath = os.path.join(os.getcwd(), plotName) plotDict[peakFiles['simName'][m]].update( {peakFiles['resType'][m]: plotPath}) plt.close('all') return plotDict
def plotAllFields(avaDir, inputDir, outDir, cfg): """ Plot all fields within given directory and save to outDir Parameters ---------- avaDir : str path to avalanche directoy inputDir : str path to input directoy outDir : str path to directoy where plots shall be saved to cfg : dict configuration settings """ # Load all infos on simulations peakFiles = glob.glob(inputDir + os.sep + '*.asc') # create out dir if not allready existing fU.makeADir(outDir) # Loop through peakFiles and generate plot for filename in peakFiles: # Load data raster = IOf.readRaster(filename) data = raster['rasterData'] data = np.ma.masked_where(data == 0.0, data) name = os.path.splitext(os.path.basename(filename))[0] # get header info for file writing header = raster['header'] cellSize = header.cellsize # Set extent of peak file ny = data.shape[0] nx = data.shape[1] Ly = ny * cellSize Lx = nx * cellSize unit = pU.cfgPlotUtils['unit%s' % cfg['GENERAL']['peakVar']] # Figure shows the result parameter data fig = plt.figure(figsize=(pU.figW, pU.figH)) fig, ax = plt.subplots() # choose colormap cmap, _, _, norm, ticks = makePalette.makeColorMap( pU.cmapPres, np.amin(data), np.amax(data), continuous=pU.contCmap) cmap.set_bad('w') im1 = ax.imshow(data, cmap=cmap, extent=[0, Lx, 0, Ly], origin='lower', aspect=nx / ny) pU.addColorBar(im1, ax, ticks, unit) title = str('%s' % name) ax.set_title(title) ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') plotName = os.path.join(outDir, '%s.%s' % (name, pU.outputFormat)) pU.putAvaNameOnPlot(ax, avaDir) fig.savefig(plotName) plt.close('all')