Ejemplo n.º 1
0
 def test_graph(self):
     start_date = datetime.datetime(2010, 7, 1)
     end_date = datetime.datetime(2010, 10, 1)
     today = datetime.datetime(2010, 9, 8)
     graph = Graph(start_date, end_date, today=today)
     graph.add_today()
     graph.suptitle('hallo')
     graph.legend()
     self.assertTrue(graph.http_png())
Ejemplo n.º 2
0
    def image(self, identifiers, start_date, end_date,
              width=380.0, height=250.0, layout_extra=None):

        if self.selected_date:
            today = self.selected_date
        else:
            today = datetime.datetime.now()
        graph = Graph(start_date, end_date,
                      width=width, height=height, today=today)

        line_styles = self.line_styles(identifiers)

        for identifier in identifiers:
            logger.debug('identifier: %s' % identifier)
            area = WaterbalanceArea.objects.get(pk=identifier['area_id'])

            # Try to fetch day timeseries.
            ts = self._timeseries(area, WaterbalanceTimeserie.TIMESTEP_DAY)
            if ts is None:
                # Revert to default: month.
                ts = self._timeseries(area)

            if ts:
                dates = []
                values = []
                for ts_event in ts.timeseries_events.filter(
                    time__gte=start_date, time__lte=end_date).order_by(
                    'time'):

                    dates.append(ts_event.time)
                    values.append(ts_event.value)
                graph.axes.plot(dates, values,
                                lw=1,
                                color=line_styles[str(identifier)]['color'],
                                label=ts.name)

            # graph.axes.fill_between(
            #     dates, values, [value-10 for value in values],
            #     color='b', alpha=0.5)

        graph.add_today()
        return graph.http_png()
Ejemplo n.º 3
0
    def image(self, identifiers, start_date, end_date,
              width=380.0, height=250.0, layout_extra=None):
        """
        Displays timeseries graph.
        """

        line_styles = self.line_styles(identifiers)

        today = datetime.datetime.now()
        graph = Graph(start_date, end_date,
                      width=width, height=height, today=today)
        graph.axes.grid(True)

        # his = His.objects.all()[0]  # Test: take first object.
        if self.shape_id is not None:
            shape = Shape.objects.get(pk=self.shape_id)
        if self.shape_id is None or shape.his is None:
            logger.debug(
                'Shapefile %s does not have associated his file.'
                % shape)
            graph.suptitle('No data.')
            graph.add_today()
            return graph.http_png()

        hf = shape.his.hisfile()
        # parameter = hf.parameters()[2]  # Test: take first parameter.
        parameters = hf.parameters()
        locations = hf.locations()
        parameter = shape.his_parameter

        # We want the unit. The parameter often has the unit in it and
        # it is the closest we can get to unit.
        graph.axes.set_ylabel(parameter)

        # Convert dates to datetimes
        start_datetime = datetime.datetime.combine(start_date, datetime.time())
        end_datetime = datetime.datetime.combine(end_date, datetime.time())
        location_count = 0
        for identifier in identifiers:
            location = identifier['id']

            if location not in locations:
                # Skip location if not available in his file.
                logger.debug('Location "%s" not in his file "%s".' % (
                        location, shape.his))
                continue
            location_count += 1

            # parameter = parameters[index % len(parameters)]
            try:
                # u'Discharge max (m\xb3/s)' -> 'Discharge max (m\xb3/s)'
                # TODO: make better.
                weird_repr = ('%r' % parameter)[2:-1].replace("\\xb3", "\xb3")
                timeseries = hf.get_timeseries(
                    location, weird_repr, start_datetime, end_datetime, list)
            except KeyError:
                logger.error('Parameter %r not in his file. Choices are: %r' %
                             (weird_repr, parameters))
                continue

            # Plot data.
            dates = [row[0] for row in timeseries]
            values = [row[1] for row in timeseries]
            graph.axes.plot(dates, values,
                            lw=1,
                            color=line_styles[str(identifier)]['color'],
                            label=parameter)

        title = '%s (%d locations)' % (parameter, location_count)
        graph.suptitle(title)
        # if legend:
        #     graph.legend()

        graph.add_today()
        return graph.http_png()
Ejemplo n.º 4
0
    def image(self, identifiers=None, start_date=None, end_date=None,
              width=None, height=None, layout_extra=None):
        """
        Create graph of given parameters
        for first identifier in identifiers object.
        Plots lines and bar charts depends on layout_extra['type'].
        Draws bar charts only for equidistant timeseries.
        """
        if layout_extra == None or len(layout_extra) <= 0:
            layout_extra = {
                "lines": [{"style": "-", "y-position": 1.97,
                           "color": "red", "width": 3, "name": "L1"},
                          {"style": "--", "y-position": 2.12,
                           "color": "green", "width": 3, "name": "L2"}],
                "type": "line",
                "style": '-',
                "width": 1}

        today = datetime.datetime.now()
        graph = Graph(start_date, end_date,
                      width=width, height=height, today=today)
        graph.axes.grid(True)
        graph.add_today()
        # Draw graph lines with extra's
        #title = None
        y_min, y_max = None, None
        #legend = None
        for identifier in identifiers:
            fewsnorm_source = self._fewsnorm_source(identifier['ident'])
            events = self.values(
                identifier, start_date, end_date,
                fewsnorm_source=fewsnorm_source)

            dates = []
            values = []
            for event in events:
                dates.append(event['datetime'])
                values.append(event['value'])
            if layout_extra.get('type') == "line":
                graph.axes.plot(dates,
                                values,
                                ls=layout_extra.get('style'),
                                lw=layout_extra.get('width'),
                                label=identifier['ident'])
            elif layout_extra.get('type') == "bar":
                time_delta = (end_date - start_date).days
                timestep = self._timestep(identifier, fewsnorm_source)
                if time_delta > 0 and timestep != None:
                    bar_width = (float(timestep) / 60 / 24) / float(time_delta)
                    graph.axes.bar(dates, values,
                                   edgecolor='Red',
                                   width=bar_width, label=identifier['ident'])
                for line in layout_extra.get('lines'):
                    graph.axes.axhline(y=line.get('y-position'),
                                       ls=line.get('style'),
                                       color=line.get('color'),
                                       lw=line.get('width'),
                                       label=line.get('name'))
            break

        graph.axes.set_ylabel(
            AdapterFewsNorm._unit(fewsnorm_source, self.parameter_id))

        graph.legend()
        graph.axes.legend_.draw_frame(False)

        return graph.http_png()