コード例 #1
0
ファイル: app.py プロジェクト: yinweisu/ECS272-Winter2020
def update_clustering_figure(selectedData, value):
    print("c")
    selectedData = json.loads(selectedData)
    kmeans_val = value
    clickpoint = selectedData['selectedData']
    print(clickpoint)
    if clickpoint != 'null':
        clickpoint = json.loads(clickpoint)
        print("in here")
        clicked_type = clickpoint['points'][0]['label']
        # if prev_clicked_cluster_type != clicked_type:
        #     prev_clicked_cluster_type = clicked_type
        local_df = df[df.Type_1 == clicked_type]
        stats = local_df.iloc[:, 5:11]
        normalized_stats = stats
        for i in stats.columns:
            mini, maxi = stats[i].min(), stats[i].max()
            normalized_stats[i] = (stats[i] - mini) / (maxi - mini)
        pca = PCA(n_components=2).fit(normalized_stats)
        stats2d = pca.transform(normalized_stats)
        df_stats2d = pd.DataFrame(stats2d, index=local_df.index)

        model, z = cluster(kmeans_val, normalized_stats.iloc[:, 0:5])
        trace = go.Scatter(x=df_stats2d.iloc[:, 0],
                           y=df_stats2d.iloc[:, 1],
                           text=local_df['Name'],
                           name='',
                           mode='markers',
                           marker=go.Marker(opacity=0.5, color=z),
                           showlegend=False)
    else:
        print("error")
        stats = df.iloc[:, 5:11]
        normalized_stats = stats
        for i in stats.columns:
            mini, maxi = stats[i].min(), stats[i].max()
            normalized_stats[i] = (stats[i] - mini) / (maxi - mini)
        pca = PCA(n_components=2).fit(normalized_stats)
        stats2d = pca.transform(normalized_stats)
        model, z = cluster(kmeans_val, normalized_stats.iloc[:, 0:5])
        trace = go.Scatter(x=stats2d[:, 0],
                           y=stats2d[:, 1],
                           text=df['Name'],
                           name='',
                           mode='markers',
                           marker=go.Marker(opacity=0.5, color=z),
                           showlegend=False)
    layout = go.Layout(
        title='k-means clustering of catch_rate and total stats',
        xaxis=go.XAxis(showgrid=False, zeroline=False, showticklabels=False),
        yaxis=go.YAxis(showgrid=False, zeroline=False, showticklabels=False),
        hovermode='closest')
    data = go.Data([trace])
    fig = go.Figure(data=data, layout=layout)

    return fig
コード例 #2
0
def highlight_point(hoverData):
    xy = pd.DataFrame()
    xy['neighbourhood'] = df['id_neighbourhood'].unique()
    x = list(df[(df.year == 2019) & (
        df.variable == 'Average weight of airbnb inside the neighbourhood'
    )]['Nominal ']) - (df[(df.year == 2015) & (
        df.variable == 'Average weight of airbnb inside the neighbourhood')]
                       ['Nominal '])
    y = (list(df[(df.year == 2019) &
                 (df.variable == 'Average renting price/m2')]['Nominal ']) -
         df[(df.year == 2015) &
            (df.variable == 'Average renting price/m2')]['Nominal ']) / df[
                (df.year == 2015)
                & (df.variable == 'Average renting price/m2')]['Nominal ']
    xy['x'] = x.values
    xy['y'] = y.values
    xy['total_houses'] = total_houses['total_houses'].values
    xy['name'] = df['neighbourhood'].unique()
    if len(hoverData) == 1:
        point_highlight = (go.Scatter(
            x=xy[xy['neighbourhood'] == hoverData['points'][0]
                 ['location']]['x'],
            y=xy[xy['neighbourhood'] == hoverData['points'][0]
                 ['location']]['y'],
            mode='markers',
            showlegend=False,
            marker=go.Marker(size=14,
                             line={'width': 5},
                             color='orange',
                             symbol='circle-open')))
        if len(fig_scatter['data']) == 2:
            fig_scatter['data'][1] = point_highlight
        else:
            fig_scatter['data'].append(point_highlight)
    return fig_scatter
コード例 #3
0
def plot_LDA(data, features):
    X = data[features]
    y = data["categoria"]

    X_std = StandardScaler().fit_transform(X)
    LDA = LinearDiscriminantAnalysis()
    Y = LDA.fit_transform(X_std, y)

    results = []

    for name in (2, 3, 13):
        result = go.Scatter(x=Y[y == name, 0],
                            y=Y[y == name, 1],
                            mode="markers",
                            name=name,
                            marker=go.Marker(size=8,
                                             line=go.Line(
                                                 color="rgba(225,225,225,0.2)",
                                                 width=0.5),
                                             opacity=0.75))
        results.append(result)

    data = go.Data(results)
    layout = go.Layout(xaxis=go.XAxis(title="CP1", showline=False),
                       yaxis=go.YAxis(title="CP2", showline=False))

    fig = go.Figure(data=data, layout=layout)
    py.iplot(fig)

    return fig
コード例 #4
0
def plotly_histogram2(X, columns, target):
    colors = {
        2: 'rgb(255,127,20)',
        3: 'rgb(31, 220, 120)',
        13: 'rgb(44, 50, 180)'
    }
    traces = []
    _targets = sorted(X[target].unique().tolist())

    legend = {2: True, 3: True, 13: True}

    for col in range(2):
        for key in range(len(_targets)):
            traces.append(
                go.Histogram(x=X[X[target] == _targets[key]][columns[col]],
                             opacity=0.7,
                             xaxis="x%s" % (col + 1),
                             marker=go.Marker(color=colors[_targets[key]]),
                             name=_targets[key],
                             showlegend=legend[_targets[key]]))
        legend = {2: False, 3: False, 13: False}

    data = go.Data(traces)
    layout = go.Layout(barmode="overlay",
                       xaxis=go.XAxis(domain=[0, 0.48], title=columns[0]),
                       xaxis2=go.XAxis(domain=[0.52, 1], title=columns[1]),
                       yaxis=go.YAxis(title="Numero de Defectos"),
                       title="Histograma caracteristicas")

    fig = go.Figure(data=data, layout=layout)
    py.iplot(fig)

    return fig
コード例 #5
0
def draw(solver, t0=0, x0=13.41265629, y0=13.46430003, z0=33.46156416):
    for r in rs:
        ts, xs, ys, zs = solver(r, t0, x0, y0, z0)

        print('r = {0}'.format(r))
        plt.plot(ts, xs, 'red')
        plt.show()
        plt.plot(ts, ys, 'green')
        plt.show()
        plt.plot(ts, zs, 'blue')
        plt.show()

        fig = go.Figure(
            data=[go.Scatter3d(x=xs, y=ys, z=zs, marker=go.Marker(size=1))])
        fig.show()
コード例 #6
0
    def test_update_overwrite_data(self):
        fig = go.Figure(
            data=[go.Bar(marker_color="blue"),
                  go.Bar(marker_color="yellow")])

        fig.update(overwrite=True,
                   data=[go.Marker(y=[1, 3, 2], line_color="yellow")])

        self.assertEqual(
            fig.to_plotly_json()["data"],
            [{
                "type": "scatter",
                "y": [1, 3, 2],
                "line": {
                    "color": "yellow"
                }
            }],
        )
コード例 #7
0
    def form_show(self, **event_args):
        """This method is called when the column panel is shown on the screen"""
        self.label_2.text = Globals.rmse

        x_month = Globals.x_month
        item_lst = Globals.item_lst
        data_lst = Globals.data_lst

        colors = ['Red', 'Green', 'Blue', 'Yellow', 'Brown']
        plot_data = list()

        for i in range(len(data_lst)):
            scatter = go.Scatter(x=x_month,
                                 y=data_lst[i],
                                 name=str(item_lst[i]),
                                 marker=go.Marker(color=colors[i % 5]))
            plot_data.append(scatter)

        self.plot_2.data = plot_data

        pass
コード例 #8
0
#            array=lnyError,
#            visible=True),
#
#        error_x=dict(
#            type='data', # value of error bar given in data coordinates
#            array=lnxError,
#            visible=True)
#        )
#
#line = go.Scatter(
#                  x=x,
#                  y=line,
#                  mode='lines',
#                  marker=go.Marker(color='rgb(31, 119, 180)'),
#                  name='Linear Regression'
#                  )
line2 = go.Scatter(x=x,
                   y=line2,
                   mode='lines',
                   marker=go.Marker(color='rgb(31, 119, 180)'),
                   name='Linear Regression')

#data1 = [Parallel, line]
#fig1 = go.Figure(data=data1,layout=layout)

data2 = [Ring, line2]
fig2 = go.Figure(data=data2, layout=layout2)

#py.offline.plot(fig1, filename='Parallel')
py.offline.plot(fig2, filename='Ring')
コード例 #9
0
ファイル: 055ACP.py プロジェクト: benkhattab/MachineLearning
#                 title='Distribucion de los rasgos de las diferentes flores iris')

# fig = ir.Figure(data=data, layout=layout)
# fig.show()

# Point 1 (Estandarizar data)
X_std = StandardScaler().fit_transform(X)

traces = []
legend = {0:True, 1:True, 2:True, 3:True}

colors = {'setosa': 'rgb(255,0,0)', 'versicolor': 'rgb(0,255,0)', 'virginica': 'rgb(0,0,255)'}

for col in range(4):
    for key in colors:
        traces.append(ir.Histogram(x=X_std[y==key, col], opacity=0.7, xaxis="x%s"%(col+1), marker=ir.Marker(color=colors[key]), name=key, showlegend=legend[col]))
    legend = {0:False, 1:False, 2:False, 3:False}

data = ir.Data(traces)
layout = ir.Layout(barmode='overlay',
                xaxis=ir.layout.XAxis(domain=[0, 0.25], title='Long. Sepalos (cm)'),
                xaxis2=ir.layout.XAxis(domain=[0.3, 0.5], title='Anch. Sepalos (cm)'),
                xaxis3=ir.layout.XAxis(domain=[0.55, 0.75], title='Long. Petalos (cm)'),
                xaxis4=ir.layout.XAxis(domain=[0.8, 1], title='Anch. Petalos (cm)'),
                yaxis=ir.layout.YAxis(title='Numero de ejemplares'),
                title='Distribucion de los rasgos de las diferentes flores iris')

fig = ir.Figure(data=data, layout=layout)
fig.show()

# Point 2 (Obtener los vectores y valores propios 'matrix de covarianza')
コード例 #10
0
def visualize(df_viz, mapbox_token):

    df_viz['tp'] = df_viz['tp'] * 0.0393701 # conversion from mm to in
    # max_precip = 6 # limiting the highest daily precipitation for coloring plot
    # df_viz['tp'][df_viz['tp'] >= max_precip] = max_precip 
    # df_viz.tail(20)

    # colorscale = [[0.0, '#171c42'], [0.07692307692307693, '#263583'], [0.15384615384615385, '#1a58af'], [0.23076923076923078, '#1a7ebd'], [0.3076923076923077, '#619fbc'], [0.38461538461538464, '#9ebdc8'], [0.46153846153846156, '#d2d8dc'], [0.5384615384615384, '#e6d2cf'], [0.6153846153846154, '#daa998'], [0.6923076923076923, '#cc7b60'], [0.7692307692307693, '#b94d36'], [0.8461538461538461, '#9d2127'], [0.9230769230769231, '#6e0e24'], [1.0, '#3c0911']]

    # https://github.com/plotly/plotly.js/blob/5bc25b490702e5ed61265207833dbd58e8ab27f1/src/components/colorscale/scales.js
    colorscale = [
        [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)'], # fades out into:
        [1, 'rgba(255,255,255,0.05)'] # white nearly invisible
    ]

    val_min = df_viz['tp'].min()
    val_max = df_viz['tp'].max()
    # print(val_max, val_min)

    data = []

    # https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf?_ga=2.113218049.441476779.1587291103-1421256715.1585761166
    data.append(
        go.Scattermapbox(
            lon=df_viz['lonbin'].values,
            lat=df_viz['latbin'].values,
            mode='markers',
            text=df_viz['tp'].values,
            marker=go.Marker(
                cmax=val_max,
                cmin=val_min,
                color=df_viz['tp'].values,
                colorscale=colorscale,
                reversescale=True,
                showscale = True,
                opacity = 0.65
        
            ),
        )
    )

    layout = go.Layout(
        margin=dict(t=0,b=0,r=0,l=0),
        autosize=True,
        hovermode='closest',
        showlegend=True,
        mapbox=dict(
            accesstoken=mapbox_token,
            bearing=0,
            center=dict(
                lat=45,
                lon=-122
            ),
            pitch=0,
            zoom=4,
            style='dark'
        ),
    )

    fig = go.Figure(data=data, layout=layout)
    fig.show()

    # print out how long this script run took
    ending = datetime.now()
    print('Ending:', ending)
    print()
    print('Elapsed:', ending - starting)
コード例 #11
0
def front_page_map():
    pd.options.mode.chained_assignment = None
    # mapbox_access_token = 'pk.eyJ1IjoibWFrcy1zaCIsImEiOiJjajRnMGhyNzcxZGFzMnd1ZnZteHF1YXo3In0.5R_XD1wl8F7ffCjAN1yxLg'
    terror_data = pd.read_csv(
        'gtd_data/globalterrorismdb_0718dist.csv',
        encoding='ISO-8859-1',
        usecols=[0, 1, 2, 3, 8, 11, 12, 13, 14, 29, 35, 84, 98, 101])
    terror_data = terror_data.rename(
        columns={
            'eventid': 'id',
            'iyear': 'year',
            'imonth': 'month',
            'iday': 'day',
            'country_txt': 'country',
            'provstate': 'state',
            'city': 'city',
            'targtype1_txt': 'target',
            'weaptype1_txt': 'weapon',
            'attacktype1_txt': 'attacktype',
            'nkill': 'nkill',
            'nwound': 'nwound',
            'addnotes': 'info'
        })

    terror_data['nkill'] = terror_data['nkill'].fillna(0).astype(int)
    terror_data['nwound'] = terror_data['nwound'].fillna(0).astype(int)
    terror_data = terror_data.dropna(how='any',
                                     subset=['latitude', 'longitude'])

    terror_pak = terror_data[terror_data['country'] == 'Pakistan']
    terror_india = terror_data[terror_data['country'] == 'India']
    terror_afghan = terror_data[terror_data['country'] == 'Afghanistan']

    terror_pak_assassination = terror_pak[terror_pak['attacktype'] ==
                                          'Assassination']

    terror_pak.loc[:, 'day'] = terror_pak.apply(
        lambda row: str(row['id'])[6:8] if row['day'] == 0 else row['day'],
        axis=1)
    # terror_pak.loc[:, 'date'] = pd.to_datetime(terror_pak[['day', 'month', 'year']])

    terror_pak = terror_pak.drop_duplicates(['latitude', 'longitude', 'nkill'])
    terror_peryear = np.asarray(terror_pak.groupby('year').year.count())
    terror_years = np.arange(1970, 2016)
    terror_years = np.delete(terror_years, [1])
    trace1 = go.Scattergeo(
        geo='geo3',
        lon=terror_pak[(terror_pak['year'] == 2011)]['longitude'],
        lat=terror_pak[(terror_pak['year'] == 2011)]['latitude'],
        mode='markers',
        marker=go.Marker(
            size=3,
            opacity=0.7,
            color='#A60000',
        ),
        text=terror_pak[(terror_pak['year'] == 2011)]['country'])
    trace2 = go.Scattergeo(
        geo='geo3',
        lon=terror_india[(terror_india['year'] == 2011)]['longitude'],
        lat=terror_india[(terror_india['year'] == 2011)]['latitude'],
        mode='markers',
        marker=go.Marker(
            size=3,
            opacity=0.7,
            color='#B60000',
        ),
        text=terror_india[(terror_india['year'] == 2011)]['country'])

    # data=trace1
    data = [trace1, trace2]
    layout = go.Layout(
        title='Terrorist attacks Occurring in Pakistan & India',
        height=600,
        # width=1000,
        autosize=True,
        dragmode='zoom',
        geo3=dict(
            scope='asia',
            showlakes=True,
            showocean=True,
            # oceancolor='rgb(255, 255, 255)',
            showland=True,
            showcountries=True,
            countrywidth=2,
            countrycolor='rgb(200, 200, 200)',
        )
        # geo3=dict(projection=dict(type='orthographic', ),scope='asia', showlakes=False,showocean=True,showland=True,showcountries=True,)
    )
    fig = go.Figure(data=data, layout=layout)
    return fig
コード例 #12
0
def create_visuals(test_name, ux, uy, id):
    f = open("Sites.txt", 'r')
    temp_sites = f.read()
    temp_sites = temp_sites.split("\n")
    temp_sites.pop()
    sites = {}
    for site in temp_sites:
        site = site.split(", ")
        site[0] = int(site[0])
        site[1] = float(site[1])
        site[2] = float(site[2])
        site[3] = str(site[3])
        site[4] = str(site[4])
        site[5] = str(site[5])
        sites[site[0]] = site

    f = open("Flows.txt", 'r')
    temp_flows = f.read()
    temp_flows = temp_flows.split("\n")
    temp_flows.pop()
    flows = []
    for flow in temp_flows:
        flow = flow.split(", ")
        flow[0] = int(flow[0])
        flow[1] = int(flow[1])
        flow[2] = float(flow[2])
        flow[3] = float(flow[3])
        flow[4] = int(flow[4])
        flows.append(flow)

    if ux != -1 and uy != -1 and id != -1:
        ux = [ux]
        uy = [uy]
        user_click_trace = go.Scatter(x=ux,
                                      y=uy,
                                      mode='markers',
                                      text=[id],
                                      hoverinfo='text',
                                      marker=dict(color='green',
                                                  size=10,
                                                  line_width=2))

    real_sites = []
    for site in sites.keys():
        if sites[site][5] == "True":
            real_sites.append([sites[site][1], sites[site][2]])
    Xr = [real_sites[k][0] for k in range(len(real_sites))]
    Yr = [real_sites[k][1] for k in range(len(real_sites))]
    realSites_trace = go.Scatter(x=Xr,
                                 y=Yr,
                                 mode='markers',
                                 hoverinfo='none',
                                 marker=dict(color='red',
                                             size=10,
                                             line_width=2))

    midpoints = []
    for flow in flows:
        x0 = sites[flow[0]][1]
        y0 = sites[flow[0]][2]
        x1 = sites[flow[1]][1]
        y1 = sites[flow[1]][2]
        temp_length = flow[2]
        new_x = (x0 + x1) / 2
        new_y = (y0 + y1) / 2
        midpoints.append([temp_length, new_x, new_y])
    Xm = [midpoints[k][1] for k in range(len(midpoints))]
    Ym = [midpoints[k][2] for k in range(len(midpoints))]
    flow_lengths = [
        "This: " + str(flows[k][2]) + "\t Upstream: " + str(flows[k][3]) +
        "\t straihler: " + str(flows[k][4]) for k in range(len(flows))
    ]
    midpoint_trace = go.Scatter(x=Xm,
                                y=Ym,
                                mode='markers',
                                text=flow_lengths,
                                hoverinfo='text',
                                marker=go.Marker(opacity=0))

    G = nx.Graph()
    my_nodes = range(len(sites))
    my_edges = [(flows[k][0], flows[k][1]) for k in range(len(flows))]
    G.add_nodes_from(my_nodes)
    G.add_edges_from(my_edges)

    sL = list(sites.values())

    Xn = []
    Yn = []
    for k in range(len(sL)):
        Xn.append(sL[k][1])
        Yn.append(sL[k][2])

    labels = [sL[k][0] for k in range(len(sL))]
    node_labels = [
        "ID: " + str(sL[k][0]) + "\nAssigned ID: " + str(sL[k][3]) +
        "\nDownward Ref ID:" + sL[k][4] for k in range(len(sL))
    ]

    node_trace = go.Scatter(x=Xn,
                            y=Yn,
                            mode='markers',
                            text=node_labels,
                            hoverinfo='text',
                            marker=dict(color='white', size=7, line_width=2))

    Xe = []
    Ye = []

    Xdict = dict()
    Ydict = dict()
    for k in range(len(sL)):
        Xdict[sL[k][0]] = sL[k][1]
        Ydict[sL[k][0]] = sL[k][2]

    for e in G.edges():
        x0 = Xdict[e[0]]
        y0 = Ydict[e[0]]
        x1 = Xdict[e[1]]
        y1 = Ydict[e[1]]
        Xe.append(x0)
        Xe.append(x1)
        Xe.append(None)
        Ye.append(y0)
        Ye.append(y1)
        Ye.append(None)

    edge_trace = go.Scatter(x=Xe,
                            y=Ye,
                            line=dict(width=0.5, color='#888'),
                            mode='lines')

    axis = dict(
        showline=False,  # hide axis line, grid, ticklabels and  title
        zeroline=False,
        showgrid=False,
        showticklabels=False,
        title='')

    layout = dict(
        title=test_name,
        font=dict(family='Balto'),
        width=1500,
        height=1000,
        autosize=False,
        showlegend=False,
        xaxis=axis,
        yaxis=axis,
        hovermode='closest',
        plot_bgcolor='#bad7ff',  #set background color            
    )

    if ux != -1 and uy != -1 and id != -1:
        fig = dict(data=[
            user_click_trace, node_trace, edge_trace, midpoint_trace,
            realSites_trace
        ],
                   layout=layout)
    else:
        fig = dict(
            data=[node_trace, edge_trace, midpoint_trace, realSites_trace],
            layout=layout)
    fig['layout'].update(annotations=make_annotations(Xn, Yn, labels))
    plot(fig)
コード例 #13
0
def plot_exponential_graph_set(time, t_c, t_h, power, resistance, room_temp):
    data_dict = {
        "T_c": (t_c, "#17becf", 40, 20),
        "T_h": (t_h, "#de1738", 40, -20),
        "\dot{W}": (power, "#7851a9", 40, -20),
    }

    scatters = []
    trendlines = []
    annotations = []

    for dataname, datapair in data_dict.items():
        # Use dogleg algorithm
        popt, pcov = curve_fit(exponential, time, datapair[0], method="dogbox")

        # Prep constants for return values
        if dataname == "T_c":
            tc_coeffs = popt
        elif dataname == "T_h":
            th_coeffs = popt
        elif dataname == "\dot{W}":
            w_coeffs = popt

        # Compute R^2 value
        r_squared = round(metrics.r2_score(exponential(time, *popt), datapair[0]), 3)

        xx = np.linspace(time[0], time[-1], 2000)
        yy = exponential(xx, *popt)

        if dataname == "T_c" or dataname == "T_h":
            # Creating the dataset, and generating the plot
            scatters.append(
                go.Marker(
                    x=time,
                    y=datapair[0] + room_temp,
                    mode="markers",
                    marker=go.Marker(color=list(range(140)), colorscale="Viridis"),
                    name="",
                    showlegend=False,
                )
            )

            trendlines.append(
                go.Marker(
                    x=xx,
                    y=yy + room_temp,
                    mode="lines",
                    marker=go.Marker(color=datapair[1]),
                    name="${{{}}}$".format(dataname),
                )
            )

            annotations.append(
                go.layout.Annotation(
                    x=time[-20],
                    y=exponential(time[-20], *popt) + room_temp,
                    text="${} = {}e^{{-{}(t - 61.9)}} + {{{}}}$".format(
                        dataname, round(popt[0], 3), round(popt[1], 3), room_temp
                    ),
                    showarrow=True,
                    ax=datapair[2],
                    ay=datapair[3],
                )
            )

            annotations.append(
                go.layout.Annotation(
                    x=time[-1],
                    y=exponential(time[-1], *popt) + room_temp,
                    text="$R^2 = {}$".format(r_squared),
                    showarrow=True,
                    ax=datapair[2],
                    ay=datapair[3],
                )
            )

        elif dataname == "\dot{W}":
            scatters.append(
                go.Marker(
                    x=time,
                    y=datapair[0],
                    mode="markers",
                    marker=go.Marker(color=list(range(140)), colorscale="Viridis"),
                    name="",
                    showlegend=False,
                )
            )

            trendlines.append(
                go.Marker(
                    x=xx,
                    y=yy,
                    mode="lines",
                    marker=go.Marker(color=datapair[1]),
                    name="${{{}}}$".format(dataname),
                )
            )

            annotations.append(
                go.layout.Annotation(
                    x=time[-20],
                    y=exponential(time[-20], *popt),
                    text="${} = {}e^{{-{}(t - 61.9)}}$".format(
                        dataname, round(popt[0], 3), round(popt[1], 3)
                    ),
                    showarrow=True,
                    ax=datapair[2],
                    ay=datapair[3],
                )
            )

            annotations.append(
                go.layout.Annotation(
                    x=time[-1],
                    y=exponential(time[-1], *popt),
                    text="$R^2 = {}$".format(r_squared),
                    showarrow=True,
                    ax=datapair[2],
                    ay=datapair[3],
                )
            )

    layout = go.Layout(
        title="$\\textbf{{Graph for }} {} \\textbf{{ }} \Omega$".format(resistance),
        plot_bgcolor="rgb(229, 229, 229)",
        xaxis=go.layout.XAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$t (s)$",
        ),
        yaxis=go.layout.YAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$T (^\circ C)$",
        ),
        annotations=annotations,
    )

    scatter_trendline_pair = list(zip(scatters, trendlines))
    final_data = [item for sublist in scatter_trendline_pair for item in sublist]
    fig = go.Figure(data=final_data, layout=layout)

    # Show plot on localhost
    pio.show(fig)
    # pio.write_html(fig, file='T_c vs Time', auto_open=True)
    return tc_coeffs, th_coeffs, w_coeffs
コード例 #14
0
def output_power_graph(resistance_values, output_power_values):
    scatters = []
    trendlines = []
    annotations = []

    # Use dogleg algorithm
    popt, pcov = curve_fit(
        output, resistance_values, output_power_values, method="dogbox"
    )

    # Compute R^2 value
    r_squared = round(
        metrics.r2_score(output(resistance_values, *popt), output_power_values), 3
    )

    xx = np.linspace(resistance_values[0], resistance_values[-1], 2000)
    yy = output(xx, *popt)

    scatters.append(
        go.Marker(
            x=resistance_values,
            y=output_power_values,
            mode="markers",
            marker=go.Marker(color=list(range(10)), colorscale="Viridis"),
            name="",
            showlegend=False,
        )
    )

    trendlines.append(
        go.Marker(
            x=xx,
            y=yy,
            mode="lines",
            marker=go.Marker(color="#ff007f"),
            name="${{\dot{W}}}$",
        )
    )

    annotations.append(
        go.layout.Annotation(
            x=resistance_values[-4],
            y=output(resistance_values[-4], *popt),
            text="$\dot{{W}} = \\frac{{{}^2 R_L}}{{{{{} + R_L}}^2}}$".format(
                round(popt[1], 3), round(popt[0], 3)
            ),
            showarrow=True,
            ax=70,
            ay=-5,
        )
    )

    annotations.append(
        go.layout.Annotation(
            x=resistance_values[-1],
            y=output(resistance_values[-1], *popt),
            text="$R^2 = {}$".format(r_squared),
            showarrow=True,
            ax=70,
            ay=-5,
        )
    )

    layout = go.Layout(
        title="$\\textbf{Output Power Graph}$",
        plot_bgcolor="rgb(229, 229, 229)",
        xaxis=go.layout.XAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$R_L (\Omega)$",
        ),
        yaxis=go.layout.YAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$\dot{W} (W)$",
        ),
        annotations=annotations,
    )

    scatter_trendline_pair = list(zip(scatters, trendlines))
    final_data = [item for sublist in scatter_trendline_pair for item in sublist]
    fig = go.Figure(data=final_data, layout=layout)

    # Show plot on localhost
    pio.show(fig)
コード例 #15
0
def plot_qc_qh_and_w(time, tc_coeffs, th_coeffs, resistance, room_temp):
    # Define symbols for differentiation
    t, Tc, Th = symbols("t Tc Th")
    Tc = tc_coeffs[0] * exp(-tc_coeffs[1] * (t - 61.9)) + room_temp
    Th = th_coeffs[0] * exp(-th_coeffs[1] * (t - 61.9)) + room_temp

    dTcdt = diff(Tc, t)
    dThdt = diff(Th, t)

    # mc = 21.87 J/°C
    dQcdt = 21.87 * dTcdt
    dQhdt = 21.87 * dThdt
    dWdt = dQhdt + dQcdt
    actual_Qc = lambdify(t, dQcdt)
    actual_Qh = lambdify(t, dQhdt)
    actual_W = lambdify(t, dWdt)

    # Start plotting
    data_dict = {
        "\dot{Q_c}": (tc_coeffs[1], actual_Qc, "#17becf", dQcdt, -40, 20),
        "\dot{Q_h}": (th_coeffs[1], actual_Qh, "#de1738", dQhdt, 40, -20),
        "\dot{W}": (th_coeffs[1] + tc_coeffs[1], actual_W, "#7851a9", dWdt, 40, 20),
    }
    plots = []
    annotations = []

    for dataname, datapair in data_dict.items():
        xx = np.linspace(time[0], time[-1], 2000)
        yy = abs(datapair[1](xx))

        plots.append(
            go.Marker(
                x=xx,
                y=yy,
                mode="lines",
                marker=go.Marker(color=datapair[2]),
                name="${{{}}}$".format(dataname),
            )
        )

        if dataname == "\dot{Q_c}" or dataname == "\dot{Q_h}":
            annotations.append(
                go.layout.Annotation(
                    x=time[20],
                    y=abs(datapair[1](time[20])),
                    text="${} = {}e^{{-{}t}}$".format(
                        dataname,
                        abs(round(datapair[3].args[0], 3)),
                        round(datapair[0], 3),
                    ),
                    showarrow=True,
                    ax=datapair[4],
                    ay=datapair[5],
                )
            )

        elif dataname == "\dot{W}":
            annotations.append(
                go.layout.Annotation(
                    x=time[-20],
                    y=datapair[1](time[-20]),
                    text="${} = {}e^{{-{}t}} - {}e^{{-{}t}}$".format(
                        dataname,
                        abs(round(dQhdt.args[0], 3)),
                        round(th_coeffs[1], 3),
                        abs(round(dQcdt.args[0], 3)),
                        round(tc_coeffs[1], 3),
                    ),
                    showarrow=True,
                    ax=datapair[4],
                    ay=datapair[5],
                )
            )

    layout = go.Layout(
        title="$\\textbf{{Graph for }} {} \\textbf{{ }} \Omega$".format(resistance),
        plot_bgcolor="rgb(229, 229, 229)",
        xaxis=go.layout.XAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$t (s)$",
        ),
        yaxis=go.layout.YAxis(
            zerolinecolor="rgb(255,255,255)",
            gridcolor="rgb(255,255,255)",
            title="$\dot{Q} (J/s)$",
        ),
        annotations=annotations,
    )

    fig = go.Figure(data=plots, layout=layout)

    # Show plot on localhost
    pio.show(fig)