Esempio n. 1
0
def main():
    Sne = 50
    leg_x = 190
    leg_y = 140
    leg_radius = 130

    center = Point(0, 0)
    circle = Circle(center, Sne)

    center_f = Point(leg_x, leg_y)
    center_r = Point(-leg_x, leg_y)
    center_ff = Point(leg_x, -leg_y)
    center_rr = Point(-leg_x, -leg_y)

    a = 100
    b = 60
    ellipse_f = Ellipse(center_f, a, b)
    ellipse_r = Ellipse(center_r, a, b)
    ellipse_ff = Ellipse(center_ff, a, b)
    ellipse_rr = Ellipse(center_rr, a, b)

    rx = leg_x * 2 + leg_radius
    ry = leg_y * 2 + leg_radius
    fig = plot.Figure(((-rx, rx), (-ry, ry)))

    fig.drawCircle(circle, color='black')
    fig.drawEllipse(ellipse_f, color='black')
    fig.drawEllipse(ellipse_r, color='black')
    fig.drawEllipse(ellipse_ff, color='black')
    fig.drawEllipse(ellipse_rr, color='black')

    # draw robot
    fig.drawLineP(Point(leg_x, leg_y), Point(-leg_x, leg_y), color='orange')
    fig.drawLineP(Point(-leg_x, leg_y), Point(-leg_x, -leg_y), color='orange')
    fig.drawLineP(Point(-leg_x, -leg_y), Point(leg_x, -leg_y), color='orange')
    fig.drawLineP(Point(leg_x, -leg_y), Point(leg_x, leg_y), color='orange')

    EPPSL1, EPPSL2 = [], []
    for angle in np.arange(0, 180,
                           3.0):  # from 0 to 180 degree by step 3.0 degree
        if angle == 0.0:
            continue
        theta1 = radian(angle)
        theta2 = radian(angle) + np.pi
        tangent_line1 = tangent(circle, theta1)
        tangent_line2 = tangent(circle, theta2)
        if touch(ellipse_f,
                 tangent_line1) and touch(ellipse_rr, tangent_line1) and touch(
                     ellipse_f, tangent_line2) and touch(
                         ellipse_rr, tangent_line2):
            ls_r = tangent_line1
            ls_ff = tangent_line2
            EPPSL1.append((ls_r, ls_ff))
        if touch(ellipse_r,
                 tangent_line1) and touch(ellipse_ff, tangent_line1) and touch(
                     ellipse_r, tangent_line2) and touch(
                         ellipse_ff, tangent_line2):
            ls_f = tangent_line1
            ls_rr = tangent_line2
            EPPSL2.append((ls_f, ls_rr))

    common_leg_V = None
    common_leg_len = 0.0
    for ls_r, ls_ff in EPPSL1:
        for ls_f, ls_rr in EPPSL2:
            # f leg
            best_Qf, best_Uf, best_Rf = None, None, None
            best_dist = 0.0
            ret = intersectionPointEllipseLine(ellipse_f, ls_r)
            if len(ret) == 2:
                p1, p2 = ret
                for Q in generate_q(ls_r, p1, p2):
                    U = calc_u(ellipse_f, Q)[0]
                    dist = distance(Q, U)
                    if dist > best_dist:
                        best_Qf = Q
                        best_Uf = U
                        best_dist = dist
                dist = best_Uf.y - ls_f(best_Uf.x)
                l = drift(ls_rr, dist)
                best_Rf = intersectionPointLineLine(l, ls_ff)
                Vf = V(best_Qf, best_Rf, best_Uf)
            # rr leg
            best_Qrr, best_Urr, best_Rrr = None, None, None
            best_dist = 0.0
            ret = intersectionPointEllipseLine(ellipse_rr, ls_ff)
            if len(ret) == 2:
                p1, p2 = ret
                for Q in generate_q(ls_ff, p1, p2):
                    U = calc_u(ellipse_rr, Q)[1]
                    dist = distance(Q, U)
                    if dist > best_dist:
                        best_Qrr = Q
                        best_Urr = U
                        best_dist = dist
                dist = best_Urr.y - ls_rr(best_Urr.x)
                l = drift(ls_f, dist)
                best_Rrr = intersectionPointLineLine(l, ls_r)
                Vrr = V(best_Qrr, best_Rrr, best_Urr)
            # ff leg
            best_Qff, best_Uff, best_Rff = None, None, None
            best_dist = 0.0
            ret = intersectionPointEllipseLine(ellipse_ff, ls_rr)
            if len(ret) == 2:
                p1, p2 = ret
                for U in generate_q(ls_rr, p1, p2):
                    Q = calc_u(ellipse_ff, U)[0]
                    dist = distance(Q, U)
                    if dist > best_dist:
                        best_Qff = Q
                        best_Uff = U
                        best_dist = dist
                dist = best_Qff.y - ls_ff(best_Qff.x)
                l = drift(ls_r, dist)
                best_Rff = intersectionPointLineLine(l, ls_f)
                Vff = V(best_Qff, best_Rff, best_Uff)
            # r leg
            best_Qr, best_Ur, best_Rr = None, None, None
            best_dist = 0.0
            ret = intersectionPointEllipseLine(ellipse_r, ls_f)
            if len(ret) == 2:
                p1, p2 = ret
                for U in generate_q(ls_f, p1, p2):
                    Q = calc_u(ellipse_r, U)[1]
                    dist = distance(Q, U)
                    if dist > best_dist:
                        best_Qr = Q
                        best_Ur = U
                        best_dist = dist
                dist = best_Qr.y - ls_r(best_Qr.x)
                l = drift(ls_ff, dist)
                best_Rr = intersectionPointLineLine(l, ls_rr)
                Vr = V(best_Qr, best_Rr, best_Ur)
            # common leg trajectry
            len_f = Vf.get_length()
            len_rr = Vrr.get_length()
            len_ff = Vff.get_length()
            len_r = Vr.get_length()
            best_len = min(len_f, len_rr, len_ff, len_r)
            if best_len == len_f:
                ref = reflect(Vf, orig_U, reflection=False)
                in_r, _Vr = inside(ellipse_r, ls_f, ref, orig_U)
                ref = reflect(Vf, orig_U)
                in_ff, _Vff = inside(ellipse_ff, ls_rr, ref, orig_U)
                ref = reflect(Vf, orig_Q)
                in_rr, _Vrr = inside(ellipse_rr, ls_ff, ref, orig_Q)
                if in_r and in_ff and in_rr:
                    if best_len > common_leg_len:
                        common_leg_V = (_Vf, _Vr, _Vff, Vrr, ls_f, ls_r, ls_ff,
                                        ls_rr)
                        common_leg_len = best_len
            elif best_len == len_ff:
                ref = reflect(Vf, orig_Q)
                in_f, _Vf = inside(ellipse_f, ls_r, ref, orig_Q)
                ref = reflect(Vf, orig_U)
                in_r, _Vr = inside(ellipse_r, ls_f, ref, orig_U)
                ref = reflect(Vf, orig_Q, reflection=False)
                in_rr, _Vrr = inside(ellipse_rr, ls_ff, ref, orig_Q)
                if in_f and in_r and in_rr:
                    if best_len > common_leg_len:
                        common_leg_V = (_Vf, _Vr, Vff, _Vrr, ls_f, ls_r, ls_ff,
                                        ls_rr)
                        common_leg_len = best_len
            elif best_len == len_rr:
                ref = reflect(Vf, orig_Q)
                in_f, _Vf = inside(ellipse_f, ls_r, ref, orig_Q)
                ref = reflect(Vf, orig_U, reflection=False)
                in_ff, _Vr = inside(ellipse_ff, ls_rr, ref, orig_U)
                ref = reflect(Vf, orig_Q)
                in_r, _Vrr = inside(ellipse_r, ls_f, ref, orig_Q)
                if in_f and in_r and in_ff:
                    if best_len > common_leg_len:
                        common_leg_V = (_Vf, _Vr, _Vff, Vrr, ls_f, ls_r, ls_ff,
                                        ls_rr)
                        common_leg_len = best_len
            else:
                ref = reflect(Vr, orig_Q, reflection=False)
                in_f, _Vf = inside(ellipse_f, ls_r, ref, orig_Q)
                ref = reflect(Vr, orig_U)
                in_ff, _Vff = inside(ellipse_ff, ls_rr, ref, orig_U)
                ref = reflect(Vr, orig_Q)
                in_rr, _Vrr = inside(ellipse_rr, ls_ff, ref, orig_Q)
                if in_f and in_ff and in_rr:
                    if best_len > common_leg_len:
                        common_leg_V = (_Vf, Vr, _Vff, _Vrr, ls_f, ls_r, ls_ff,
                                        ls_rr)
                        common_leg_len = best_len

    if not common_leg_V:
        print("No leg tragectry generated!")
        fig.show()
        return

    Vf, Vr, Vff, Vrr, ls_f, ls_r, ls_ff, ls_rr = common_leg_V
    print(Vf.dump())
    print(Vr.dump())
    print(Vff.dump())
    print(Vrr.dump())

    fig.drawV(Vf)
    fig.drawV(Vr)
    fig.drawV(Vff)
    fig.drawV(Vrr)
    fig.drawLine(ls_f, color='green')
    fig.drawLine(ls_r, color='green')
    fig.drawLine(ls_ff, color='green')
    fig.drawLine(ls_rr, color='green')

    fig.set_title("Sne: {}".format(Sne))
    fig.show()
Esempio n. 2
0
def sensor(sensorid):
    s = hp.find_sensor(sensorid)

    if s is None:
        abort(404)

    path = c.get('backend', 'figures')

    analyses = []
    units = dict(electricity="Watt", gas="Watt", water="liter/min")

    # create timeseries plot
    filename = 'TimeSeries_{}.html'.format(s.key)
    analyses.append(
        plot.Html(
            title='Timeseries',
            content=safe_join(path, filename),
            description=
            u"This interactive graph  shows the measurement of {sensordescription} over the last 7 days.\
                                 The unit of the data is {unit}, and the graph contains minute values.\
                                 The graph is interactive: use the bottom ruler to zoom in/out and to change the period. \
                                 The graph is in local time (for Belgium).".
            format(sensordescription=s.description, unit=units.get(s.type))))

    if s.type == 'electricity' and not s.system == 'solar':
        # create standby horizontal
        filename = 'standby_horizontal_{}.png'.format(s.key)
        analyses.append(
            plot.Figure(
                title='Standby 10 days',
                content=filename,
                description=
                u"This figure shows the electric standby power of {sensordescription} (in {unit}). \
                             The left plot shows your standby power over the last 10 days (red diamonds). The distribution\
                             of the standby power of other opengrid families is shown as a boxplot. The red line is the median,\
                             the box limits are the 25th and 75th percentiles. By comparing your standby power to this box,\
                             you get an idea of your position in the opengrid community.\
                             The right plot shows your measured power consumption of {sensordescription} for the last night.\
                             This may give you an idea of what's going on in the night. Try to switch something off tonight and\
                             come back tomorrow to this graph to see the effect!"
                .format(sensordescription=s.description,
                        unit=units.get(s.type))))
        # create standby vertical
        filename = 'standby_vertical_{}.png'.format(s.key)
        analyses.append(
            plot.Figure(
                title='Standby 40 days',
                content=filename,
                description=
                u"This figure also shows the electric standby power of {sensordescription} (in {unit}). \
                             The left plot shows your standby power over the last 40 days (red diamonds).\
                             The standby power of other opengrid families is indicated by the 10th, 50th and 90th percentile.\
                             Again, this allows you to get an idea of your standby power in comparison to the opengrid community.\
                             The right plot shows your measured power consumption of {sensordescription} for the last night.\
                             This may give you an idea of what's going on in the night. Try to switch something off tonight and\
                             come back tomorrow to this graph to see the effect!<br><br>\
                             Which of these two graphs do you prefer? Let us know in the\
                             <a href=\"https://groups.google.com/d/forum/opengrid-private\">forum</a>."
                .format(sensordescription=s.description,
                        unit=units.get(s.type))))

    # create carpet plot
    filename = 'carpet_{}_{}.png'.format(s.type, s.key)
    analyses.append(
        plot.Figure(
            title='Carpet plot',
            content=filename,
            description=
            u"This plot shows the measurement of {sensordescription} over the last 3 weeks in a 'raster'. \
                         Each day is a single row in the 'raster', the horizontal axis is time (0-24h).\
                         The intensity of the measurement is plotted as a color: blue is low, red is high.  <br><br> \
                         The plot shows when the consumption typically takes place. \
                         This is useful discover trends or patterns over a day or week.\
                         This allows to check if systems are correctly scheduled (night set-back for heating, clock for\
                         an electrical boiler, etc. )<br><br>\
                         Do you think this is useful? Let us know in the\
                         <a href=\"https://groups.google.com/d/forum/opengrid-private\">forum</a>."
            .format(sensordescription=s.description)))

    analyses = [analysis for analysis in analyses if analysis.has_content()]

    return render_template('sensor.html', sensor=s, analyses=analyses)
Esempio n. 3
0
    def generate(self,
                 result,
                 outputpath,
                 templatepath,
                 columncount=2,
                 callback=None):
        xmldocument = xml.dom.minidom.parse(
            os.path.join(templatepath, 'index.xml'))
        scenario = result.scenario

        # Get report settings
        figuresize = (self.store.getProperty(['Figures', 'Width'],
                                             usedefault=True),
                      self.store.getProperty(['Figures', 'Height'],
                                             usedefault=True))
        dpi = self.store.getProperty(['Figures', 'Resolution'],
                                     usedefault=True)
        fontscaling = self.store.getProperty(['Figures', 'FontScaling'],
                                             usedefault=True)

        # Get list of variables to plot
        selroot = self.store.root.getLocation(['Figures', 'Selection'])
        plotvariables = [node.getValue() for node in selroot.children]

        steps = float(2 + len(plotvariables))
        istep = 0

        # Create output directory if it does not exist yet.
        if not os.path.isdir(outputpath): os.mkdir(outputpath)

        for f in os.listdir(templatepath):
            fullpath = os.path.join(templatepath, f)
            if f.lower() != 'index.xml' and os.path.isfile(fullpath):
                shutil.copy(fullpath, os.path.join(outputpath, f))

        for node in xmldocument.getElementsByTagName('gotm:scenarioproperty'):
            variablepath = node.getAttribute('variable')
            assert variablepath != '', 'gotm:scenarioproperty node in report template lacks "variable" attribute pointing to a location in the scenario.'
            variablenode = scenario.root.getLocation(variablepath.split('/'))
            assert variablenode != None, 'Unable to locate "%s" in the scenario.' % variablepath
            val = variablenode.getValueAsString()
            node.parentNode.replaceChild(
                xmldocument.createTextNode(unicode(val)), node)
            node.unlink()

        scenarionodes = xmldocument.getElementsByTagName('gotm:scenario')
        assert len(
            scenarionodes
        ) <= 1, 'Found more than one "gotm:scenario" node in the report template.'
        if len(scenarionodes) > 0:
            if callback != None:
                callback(istep / steps, 'Creating scenario description...')
            scenarionode = scenarionodes[0]

            sceninterface = xmlstore.TypedStoreInterface(scenario,
                                                         showhidden=False,
                                                         omitgroupers=True)

            scentable = xmldocument.createElement('table')
            scentable.setAttribute('id', 'tableScenario')

            totaldepth = sceninterface.getDepth(scenario.root)

            # Create columns.
            for i in range(totaldepth - 2):
                col = xmldocument.createElement('col')
                col.setAttribute('width', '25')
                scentable.appendChild(col)
            col = xmldocument.createElement('col')
            scentable.appendChild(col)
            col = xmldocument.createElement('col')
            scentable.appendChild(col)

            # Create rows
            for tr in sceninterface.toHtml(scenario.root,
                                           xmldocument,
                                           totaldepth - 1,
                                           level=-1,
                                           hidedefaults=True):
                scentable.appendChild(tr)

            scenarionode.parentNode.replaceChild(scentable, scenarionode)

        istep += 1

        figuresnodes = xmldocument.getElementsByTagName('gotm:figures')
        assert len(
            figuresnodes
        ) <= 1, 'Found more than one "gotm:figures" node in the report template.'
        if len(figuresnodes) > 0:
            figuresnode = figuresnodes[0]
        else:
            figuresnode = None
        if len(plotvariables) > 0 and figuresnode != None:
            mplfigure = matplotlib.figure.Figure(figsize=(figuresize[0] / 2.54,
                                                          figuresize[1] /
                                                          2.54))
            canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(mplfigure)
            fig = plot.Figure(mplfigure)
            fig.addDataSource('result', result)
            figurestable = xmldocument.createElement('table')
            icurvar = 0
            tr = None
            for varpath in plotvariables:
                varid = varpath.split('/')[-1]

                longname = result.getVariable(varid).getLongName()
                if callback != None:
                    callback(istep / steps,
                             'Creating figure for %s...' % longname)

                if icurvar % columncount == 0:
                    tr = xmldocument.createElement('tr')
                    figurestable.appendChild(tr)
                fig.setUpdating(False)
                if not result.getFigure('result/' + varpath, fig.properties):
                    fig.clearProperties()
                    fig.addVariable(varid)
                fig.properties.setProperty(['FontScaling'], fontscaling)
                fig.setUpdating(True)
                filename = varid + '.png'
                outputfile = os.path.join(outputpath, filename)
                canvas.print_figure(outputfile, dpi=dpi)

                img = xmldocument.createElement('img')
                img.setAttribute('src', filename)
                img.setAttribute('alt', longname)
                img.setAttribute('style', 'width:%.2fcm' % figuresize[0])
                td = xmldocument.createElement('td')
                td.appendChild(img)
                tr.appendChild(td)

                icurvar = icurvar + 1
                istep += 1
            for i in range(columncount - len(tr.childNodes)):
                tr.appendChild(xmldocument.createElement('td'))
            figuresnode.parentNode.replaceChild(figurestable, figuresnode)
        elif figuresnode != None:
            figuresnode.parentNode.removeChild(figuresnode)

        if callback != None: callback(istep / steps, 'Writing HTML...')

        if outputpath != '':
            import codecs
            f = codecs.open(os.path.join(outputpath, 'index.html'), 'w',
                            'utf-8')
            xmldocument.writexml(f, encoding='utf-8')
            f.close()
        else:
            print xmldocument.toxml('utf-8')
        istep += 1

        if callback != None: callback(istep / steps, 'Done.')