Ejemplo n.º 1
0
def gen_prob_series(intervals, data):
    j_data = json.loads(data)
    predicted_data = get_predicted_data(j_data['pump'])
    lastCycle = int(predicted_data['cycle'])
    query = esutils.query_last_prediction(j_data['pump'], 50)
    response = es.search(index='predictions', body=query)
    data = []
    for tag in TAG_LIST:
        results = esutils.get_source_vector_value(response,
                                                  tag.replace('_', ' '),
                                                  'cycle')
        color = COLOR_LIST[TAG_LIST.index(tag)]
        trace = Scatter(y=results[tag.replace('_', ' ')],
                        x=results['cycle'],
                        line=plotScat.Line(color=color),
                        name=tag,
                        mode='lines')

        data.append(trace)
    layout = Layout(
        autosize=True,
        yaxis=dict(range=[0, 1], fixedrange=True, title='Results'),
        xaxis=dict(
            #range=[max(0, lastCycle - 30), lastCycle],
            autorange=True,
            zeroline=False,
            title='Cycle',
            tickformat=',d'),
        margin=plotLayout.Margin(t=45, l=50, r=50),
        plot_bgcolor="#fafafa",
        paper_bgcolor="#ededed",
        title='Status evolution')

    return Figure(data=[t for t in data], layout=layout)
Ejemplo n.º 2
0
def gen_pump_card(interval, data):
    j_data = json.loads(data)
    current_pump = j_data['pump']
    current_well = j_data['well']
    logging.debug('Updating current pump: %s' % (current_pump))

    queryLastCycle = esutils.query_ts_sorted_values(pump=current_pump, size=1)
    data = es.search(index=current_well.lower(), body=queryLastCycle)
    lastCycle = esutils.get_source_value(data, 'cycle')
    if lastCycle is not None:
        logging.critical('Last Cycle of the pump: %s' % lastCycle)
        lastPos = esutils.get_source_value(data, 'position')
        lastForce = esutils.get_source_value(data, 'force')
        logging.critical('Current point (%s, %s)' % (lastPos, lastForce))

        if lastPos is not None and lastForce is not None:
            queryCycleValues = esutils.query_cycle_values(pump=current_pump,
                                                          cycle=lastCycle)
            data = es.search(index=current_well.lower(), body=queryCycleValues)
            selected_cycle_values = esutils.get_source_vector_value(
                data, 'position', 'force')
            logging.debug("Last cycle data received:")
            logging.debug("Size of vector postion = %s" %
                          len(selected_cycle_values['position']))
            logging.debug("Size of vector force = %s" %
                          len(selected_cycle_values['force']))

            if selected_cycle_values is not None:
                cycle_trace = Scatter(x=selected_cycle_values['position'],
                                      y=selected_cycle_values['force'],
                                      name='Cycle %i' % (lastCycle),
                                      mode='lines+markers')

                current_point = Scatter(x=np.array(lastPos),
                                        y=np.array(lastForce),
                                        name='Last point',
                                        mode='markers')

                layout = Layout(height=350,
                                xaxis=dict(range=[0, 1],
                                           fixedrange=True,
                                           title='Position'),
                                yaxis=dict(range=[0, 1],
                                           fixedrange=True,
                                           zeroline=False,
                                           title='Force'),
                                margin=plotLayout.Margin(t=60,
                                                         l=50,
                                                         r=40,
                                                         b=60),
                                plot_bgcolor="#fafafa",
                                paper_bgcolor="#ededed",
                                title='Current card plot')
                return Figure(data=[cycle_trace, current_point], layout=layout)
    return None
Ejemplo n.º 3
0
def gen_wind_direction(interval):
    now = dt.datetime.now()
    sec = now.second
    minute = now.minute
    hour = now.hour

    total_time = (hour * 3600) + (minute * 60) + (sec)

    con = sqlite3.connect("./Data/wind-data.db")
    df = pd.read_sql_query(
        "SELECT * from Wind where rowid = " + str(total_time) + ";", con)
    val = df['Speed'].iloc[-1]
    direction = [0, (df['Direction'][0] - 7), (df['Direction'][0] + 7), 0]

    fcolor0 = '#%2x80%2x' % (0x84 + 2 * int(val), 0x86 - 2 * int(val))
    fcolor1 = '#%2x80%2x' % (0x84 + 2 * int(val), 0x86 - 2 * int(val))
    fcolor2 = '#%2x80%2x' % (0x84 + 2 * int(val), 0x86 - 2 * int(val))

    trace0 = Scatterpolar(r=[0, val, val, 0],
                          theta=direction,
                          mode='lines',
                          fill='toself',
                          fillcolor=fcolor0,
                          line=dict(color='rgba(32, 32, 32, .6)', width=1))

    trace1 = Scatterpolar(r=[0, val * 0.65, val * 0.65, 0],
                          theta=direction,
                          mode='lines',
                          fill='toself',
                          fillcolor='#C7D9F9',
                          line=dict(color='rgba(32, 32, 32, .6)', width=1))

    trace2 = Scatterpolar(r=[0, val * 0.3, val * 0.3, 0],
                          theta=direction,
                          mode='lines',
                          fill='toself',
                          fillcolor='#DBDCFC',
                          line=dict(color='rgba(32, 32, 32, .6)', width=1))

    layout = Layout(
        autosize=True,
        width=360,
        margin=playout.Margin(t=10, b=10, r=20, l=20),
        polar=dict(bgcolor='#F2F2F2',
                   radialaxis=dict(range=[0, 60], angle=0, dtick=10),
                   angularaxis=dict(showline=False, tickcolor='white')),
        showlegend=False,
    )

    return Figure(data=[trace0, trace1, trace2], layout=layout)
Ejemplo n.º 4
0
def gen_wind_speed(interval):
    now = dt.datetime.now()
    sec = now.second
    minute = now.minute
    hour = now.hour

    total_time = (hour * 3600) + (minute * 60) + (sec)

    con = sqlite3.connect("./Data/wind-data.db")
    df = pd.read_sql_query(
        'SELECT Speed, SpeedError, Direction from Wind where\
                            rowid > "{}" AND rowid <= "{}";'.format(
            total_time - 200, total_time), con)

    trace = Scatter(y=df['Speed'],
                    line=pscatter.Line(color='#42C4F7'),
                    hoverinfo='skip',
                    error_y=pscatter.ErrorY(type='data',
                                            array=df['SpeedError'],
                                            thickness=1.5,
                                            width=2,
                                            color='#B4E8FC'),
                    mode='lines')

    layout = Layout(height=450,
                    xaxis=dict(range=[200, 0],
                               showgrid=False,
                               showline=False,
                               zeroline=False,
                               fixedrange=True,
                               tickvals=[0, 50, 100, 150, 200],
                               ticktext=['200', '150', '100', '50', '0'],
                               title='Time Elapsed (sec)'),
                    yaxis=dict(range=[
                        min(0, min(df['Speed'])),
                        max(45,
                            max(df['Speed']) + max(df['SpeedError']))
                    ],
                               showline=False,
                               fixedrange=True,
                               zeroline=False,
                               nticks=max(6,
                                          round(df['Speed'].iloc[-1] / 10))),
                    margin=playout.Margin(t=45, l=50, r=45))

    return Figure(data=[trace], layout=layout)
Ejemplo n.º 5
0
def gen_wind_speed(interval):
    now = dt.datetime.now()
    sec = now.second
    minute = now.minute
    hour = now.hour
    #microsecond = now.microsecond

    total_time = (hour * 3600) + (minute * 60) + (sec)  # + (microsecond)

    con = sqlite3.connect("./data/acceleration-data.db")
    df = pd.read_sql_query(
        'SELECT Time, X, Y, Z from acceleration where\
                            rowid > "{}" AND rowid <= "{}";'.format(
            total_time - 200, total_time), con)

    trace1 = Scatter(
        #x=df['Time'],
        y=df['X'],
        # line=scatter.Line(
        #     color='#42C4F7'
        #),
        mode='lines',
        name='X')

    trace2 = Scatter(
        #x=df['Time'],
        y=df['Y'],
        #line= scatter.Line(
        #    color='#42C4F7'
        #),
        mode='lines',
        name='Y')

    trace3 = Scatter(
        #x=df['Time'],
        y=df['Z'],
        #line= scatter.Line(
        #    color='#42C4F7'
        #),
        mode='lines',
        name='Z')

    layout = Layout(
        height=450,
        xaxis=dict(range=[0, 200],
                   showgrid=False,
                   showline=False,
                   zeroline=False,
                   fixedrange=True,
                   tickvals=[0, 50, 100, 150, 200],
                   ticktext=['200', '150', '100', '50', '0'],
                   title='Time Elapsed (sec)'),
        yaxis=dict(
            range=[min(0, min(df['X'])),
                   max(20,
                       max(df['X']) + max(df['X']))],
            showline=False,
            fixedrange=True,
            zeroline=False,
            nticks=max(6, round(df['Z'].iloc[-1] / 10))),
        margin=lo.Margin(t=45, l=50, r=50)  #,
        #transition=dict(
        #        duration=200,
        #        easing="cubic-in-out")
    )

    return Figure(data=[trace1, trace2, trace3], layout=layout)
Ejemplo n.º 6
0
def misconduct(request):
    entries = load_misconduct_data()

    import plotly.graph_objs as go
    import plotly.graph_objs.layout as go_layout
    from plotly.offline import plot

    # Break out consequences into their own list.
    consequences = sum((entry['consequences'] for entry in entries), [])
    last_consequence_year = max(cons['date_year'] for cons in consequences)

    # Make a common x-axis of decades starting with the first full year of the Congress,
    # which happens to be an even decade.
    x = [(1790 + 10 * x)
         for x in range(0, (last_consequence_year - 1790) // 10 + 1)]
    xlab = [str(year) + 's' for year in x]

    bar_chart_layout = go.Layout(barmode='stack',
                                 margin=go_layout.Margin(l=25,
                                                         r=20,
                                                         b=10,
                                                         t=0,
                                                         pad=0),
                                 legend={"orientation": "h"})

    def make_chart(title, universe, bars, year_of):
        stacks = []

        def decade_of(entry):
            return year_of(entry) - (year_of(entry) % 10)

        for tag, label in bars:
            y = [
                sum(1 for entry in universe
                    if decade_of(entry) == decade and tag in entry['tags'])
                for decade in x
            ]
            stacks.append(go.Bar(x=xlab, y=y, name=label))
        return {
            "title":
            title,
            "figure":
            plot(go.Figure(data=stacks, layout=bar_chart_layout),
                 output_type="div",
                 include_plotlyjs=False,
                 show_link=False)
        }

    charts = [
        make_chart(
            title="Types of misconduct and alleged misconduct over time",
            universe=entries,
            bars=misconduct_type_tags,
            year_of=lambda entry: entry['consequences'][0]['date_year'],
        ),
        make_chart(
            title="Consequences of misconduct and alleged misconduct over time",
            universe=consequences,
            bars=misconduct_consequence_tags,
            year_of=lambda entry: entry['date_year'],
        ),
    ]

    return {
        "entries": entries,
        "tags": misconduct_tag_filters,
        "charts": charts,
    }
Ejemplo n.º 7
0
def gen_wind_speed(interval):

    accel_x, accel_y, accel_z = sensor.accelerometer
    t = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')

    X.append(accel_x)
    Y.append(accel_y)
    Z.append(accel_z)
    Time.append(t)

    trace1 = go.Scatter(
        x=[Time],
        y=[X],
        # line=scatter.Line(
        #     color='#42C4F7'
        #),
        mode='lines',
        name='X')

    trace2 = go.Scatter(
        x=[Time],
        y=[Y],
        #line= scatter.Line(
        #    color='#42C4F7'
        #),
        mode='lines',
        name='Y')

    trace3 = go.Scatter(
        x=[Time],
        y=[Z],
        #line= scatter.Line(
        #    color='#42C4F7'
        #),
        mode='lines',
        name='Z')

    layout = go.Layout(
        height=450,
        xaxis=dict(range=[0, 200],
                   showgrid=False,
                   showline=False,
                   zeroline=False,
                   fixedrange=True,
                   tickvals=[0, 50, 100, 150, 200],
                   ticktext=['200', '150', '100', '50', '0'],
                   title='Time Elapsed (sec)'),
        yaxis=dict(range=[min(0, min(X)),
                          max(20,
                              max(X) + max(X))],
                   showline=False,
                   fixedrange=True,
                   zeroline=False,
                   nticks=6),
        margin=lo.Margin(t=45, l=50, r=50)
        #,
        #        transition=dict(
        #                duration=500,
        #                easing="cubic-in-out")
    )

    return go.Figure(data=[trace1, trace2, trace3], layout=layout)
scl = [ [0,"rgb(5, 10, 172)"],[0.35,"rgb(40, 60, 190)"],[0.5,"rgb(70, 100, 245)"],\
    [0.6,"rgb(90, 120, 245)"],[0.7,"rgb(106, 137, 247)"],[1,"rgb(220, 220, 220)"] ]

data = [ dict(
        type = 'scattergeo',
        locationmode = 'USA-states',
        lon = df['long'],
        lat = df['lat'],
        text = df['text'],
        mode = 'markers'
        )]
map_layout = dict(
            title = 'Title',
            margin=plot_layout.Margin(
            l=10,r=10, b=10, t=50, pad=4
        ),
            geo = dict(
                scope='world',
                showframe = True,
                projection = dict(type='enumerated : "equirectangular"'),
                showcountries=True,
                showsubunits=True,
                showocean=True,
                countrycolor='green',
                oceancolor='#aec6cf'
            )
)

fig = dict(data=data, layout=map_layout)
Ejemplo n.º 9
0
def show_histogram(image):
    def hg_trace(name, color, hg):
        line = go.Scatter(
            x=list(range(0, 256)),
            y=hg,
            name=name,
            line=dict(color=(color)),
            mode="lines",
            showlegend=False,
        )
        fill = go.Scatter(
            x=list(range(0, 256)),
            y=hg,
            mode="lines",
            name=name,
            line=dict(color=(color)),
            fill="tozeroy",
            hoverinfo="none",
        )

        return line, fill

    hg = image.histogram()

    if image.mode == "RGBA":
        rhg = hg[0:256]
        ghg = hg[256:512]
        bhg = hg[512:768]
        ahg = hg[768:]

        data = [
            *hg_trace("Red", "#FF4136", rhg),
            *hg_trace("Green", "#2ECC40", ghg),
            *hg_trace("Blue", "#0074D9", bhg),
            *hg_trace("Alpha", "gray", ahg),
        ]

        title = "RGBA Histogram"

    elif image.mode == "RGB":
        # Returns a 768 member array with counts of R, G, B values
        rhg = hg[0:256]
        ghg = hg[256:512]
        bhg = hg[512:768]

        data = [
            *hg_trace("Red", "#FF4136", rhg),
            *hg_trace("Green", "#2ECC40", ghg),
            *hg_trace("Blue", "#0074D9", bhg),
        ]

        title = "RGB Histogram"

    else:
        data = [*hg_trace("Gray", "gray", hg)]

        title = "Grayscale Histogram"

    layout = go.Layout(
        autosize=True,
        title=title,
        margin=go.Margin(l=50, r=30),
        legend=dict(x=0, y=1.15, orientation="h"),
        paper_bgcolor="#31343a",
        plot_bgcolor="#272a31",
        font=dict(color="darkgray"),
        xaxis=dict(gridcolor="#43454a"),
        yaxis=dict(gridcolor="#43454a"),
    )

    return go.Figure(data=data, layout=layout)
Ejemplo n.º 10
0
    enc_format="jpeg",
)

GRAPH_PLACEHOLDER = dcc.Graph(
    id="interactive-image",
    figure={
        "data": [],
        "layout": {
            "autosize":
            True,
            "paper_bgcolor":
            "#272a31",
            "plot_bgcolor":
            "#272a31",
            "margin":
            go.Margin(l=40, b=40, t=26, r=10),
            "xaxis": {
                "range": (0, 1527),
                "scaleanchor": "y",
                "scaleratio": 1,
                "color": "white",
                "gridcolor": "#43454a",
                "tickwidth": 1,
            },
            "yaxis": {
                "range": (0, 1200),
                "color": "white",
                "gridcolor": "#43454a",
                "tickwidth": 1,
            },
            "images": [{
Ejemplo n.º 11
0
def InteractiveImagePIL(image_id,
                        image,
                        enc_format="png",
                        dragmode="select",
                        verbose=False,
                        **kwargs):
    if enc_format == "jpeg":
        if image.mode == "RGBA":
            image = image.convert("RGB")
        encoded_image = pil_to_b64(image,
                                   enc_format=enc_format,
                                   verbose=verbose,
                                   quality=80)
    else:
        encoded_image = pil_to_b64(image,
                                   enc_format=enc_format,
                                   verbose=verbose)

    width, height = image.size

    return dcc.Graph(
        id=image_id,
        figure={
            "data": [],
            "layout": {
                "autosize":
                True,
                "paper_bgcolor":
                "#272a31",
                "plot_bgcolor":
                "#272a31",
                "margin":
                go.Margin(l=40, b=40, t=26, r=10),
                "xaxis": {
                    "range": (0, width),
                    "scaleanchor": "y",
                    "scaleratio": 1,
                    "color": "white",
                    "gridcolor": "#43454a",
                    "tickwidth": 1,
                },
                "yaxis": {
                    "range": (0, height),
                    "color": "white",
                    "gridcolor": "#43454a",
                    "tickwidth": 1,
                },
                "images": [{
                    "xref": "x",
                    "yref": "y",
                    "x": 0,
                    "y": 0,
                    "yanchor": "bottom",
                    "sizing": "stretch",
                    "sizex": width,
                    "sizey": height,
                    "layer": "below",
                    "source": HTML_IMG_SRC_PARAMETERS + encoded_image,
                }],
                "dragmode":
                dragmode,
            },
        },
        config={
            "modeBarButtonsToRemove": [
                "sendDataToCloud",
                "autoScale2d",
                "toggleSpikelines",
                "hoverClosestCartesian",
                "hoverCompareCartesian",
                "zoom2d",
            ]
        },
        **_omit(["style"], kwargs),
    )