Example #1
0
def paramPerPage(config, dssFilePath):
    """
    Plot timeseries, 1 location per plot, 1 parameter per page.

    Also adds specified thresholds.
    """

    plotted = 0  # Number of plots exported
    messages = []

    outputFolder = tbu.relativeFolder(config['output_folder'],
                                      config['config_file'])

    minDate = HecTime(config['period']['start'])
    maxDate = HecTime(config['period']['end'])

    dssFile = HecDss.open(dssFilePath, str(minDate), str(maxDate))

    for param, paramConfig in config['params'].iteritems():
        plots = []
        dataPaths = [
            '/{}/{}/{}//{}/{}/'.format(config['site'].upper(),
                                       loc.upper(),
                                       param.upper(),
                                       config['interval'].upper(),
                                       config['version'].upper())
            for loc in config['locations']
        ]
        datasets = [dssFile.get(dp) for dp in dataPaths]
        datasets = [d for d in datasets if d.numberValues > 0]
        if not datasets:
            messages.append("No data for parameter '{}'.".format(param))
            continue

        for dataset in datasets:
            plot = Plot.newPlot(param)
            layout = Plot.newPlotLayout()
            layout.setHasLegend(0)
            vp = layout.addViewport()
            vp.addCurve('Y1', dataset)
            plot.configurePlotLayout(layout)
            plots.append(plot)

        # Format normal data curves
        ymin, ymax = float('+inf'), float('-inf')
        for dataset, plot in zip(datasets, plots):
            plot.setPlotTitleText("{0.parameter} at {0.location}".format(dataset))
            plot.setPlotTitleVisible(1)
            plot.setLocation(-10000, -10000)
            plot.setSize(config['width'], config['height'])
            plot.setLegendLabelText(dataset, dataset.location)
            panelProp = plot.getPlotpanel().getProperties()
            panelProp.setViewportSpaceSize(0)

            curve = plot.getCurve(dataset)
            curve.setLineColor('{}, {}, {}'.format(*config['line']['colour']))
            curve.setLineWidth(config['line']['width'])
            if config['line']['markers']:
                curve.setSymbolsVisible(1)
                curve.setSymbolType('Circle')
                curve.setSymbolLineColor('{}, {}, {}'.format(*config['line']['colour']))
                curve.setSymbolFillColor('{}, {}, {}'.format(*config['line']['colour']))
            vp = plot.getViewport(dataset.fullName)
            vp.setMinorGridXVisible(1)
            vp.getAxis('Y1').setLabel(dataset.units)
            if _paramScale(param, config) == 'log':
                vp.setLogarithmic('Y1')  # This throws a warning message if y-values <= 0. We can't catch this as an exception.
            # Horizontal lines
            thresholds = _get_thresholds(dataset, dssFilePath, config)
            for marker in _thresholdMarkers(thresholds):
                vp.addAxisMarker(marker)
            # Vertical lines
            if _baselinePeriod(dataset.location, config):
                vp.addAxisMarker(_baselineMarker(dataset.location, config))
            ymin = min(ymin, vp.getAxis('Y1').getScaleMin())
            ymax = max(ymax, vp.getAxis('Y1').getScaleMax())

        for dataset, plot in zip(datasets, plots):
            plot.showPlot()
            plot.setSize(config['width'], config['height'])
            # Set all y-axes same limits
            vp = plot.getViewports()[0]
            vp.getAxis('Y1').setScaleLimits(ymin, ymax)
            vp.getAxis('X1').setScaleLimits(minDate.value(), maxDate.value())

            plot.saveToJpeg(os.path.join(outputFolder,
                            "TH plot-{0.parameter}-{0.version}-{0.location}"
                            .format(dataset)), 95)
            plot.close()
            plotted += 1

    dssFile.done()
    return plotted, messages
#  Open the file and get the data
try:  
  dssFile = HecDss.open("C:/temp/sample.dss", "10MAR2006 2400, 09APR2006 2400")
  precip = dssFile.get("/AMERICAN/FOLSOM/PRECIP-BASIN/01JAN2006/1DAY/OBS/")
  stor = dssFile.get("/AMERICAN/FOLSOM/ STOR-RES EOP/01JAN2006/1DAY/OBS/")
  topcon = dssFile.get("/AMERICAN/FOLSOM/TOP CON STOR/01JAN2006/1DAY/OBS/")
  sagca = dssFile.get("/AMERICAN/FOLSOM-SAGCA/TOP CON STOR/01JAN2006/1DAY/OBS/")
  inflow = dssFile.get("/AMERICAN/FOLSOM/FLOW-RES IN/01JAN2006/1DAY/OBS/")
  outflow = dssFile.get("/AMERICAN/FOLSOM/FLOW-RES OUT/01JAN2006/1DAY/OBS/")
except java.lang.Exception, e :
  #  Take care of any missing data or errors
   MessageBox.showError(e.getMessage(), "Error reading data")

#  Initialize the plot and set viewport size in precent
plot = Plot.newPlot("Folsom - American River Basin")
layout = Plot.newPlotLayout()
topView = layout.addViewport(10.)
middleView = layout.addViewport(60.)
bottomView = layout.addViewport(30.)

#  Add Data in specific viewports
topView.addCurve("Y1", precip)
middleView.addCurve("Y2", stor)
middleView.addCurve("Y2", topcon)
middleView.addCurve("Y2", sagca)
bottomView.addCurve("Y1", inflow)
bottomView.addCurve("Y1", outflow)

panel = plot.getPlotpanel()
prop = panel.getProperties()
prop.setViewportSpaceSize(0)