def get3Dplot(fName, figName=""):
    #fName = "TruePositives.csv"
    df = pd.read_csv(fName, sep=' ')
    twoSix = df[df.GlycType == '2-6 SiaLac']
    twoThree = df[df.GlycType == '2-3 SiaLac']
    print(twoSix.shape, twoThree.shape)
    fig = go.Figure()

    fig.add_trace(
        go.Scatter3d(
            x=twoSix['PolSpace'],
            y=twoSix['Valency'],
            #z=twoSix[' GLYCAN SPACING ON POLYMER'],
            z=twoSix['MVF'],
            name="2-6 SiaLac",
            text=["Text A", "Text B", "Text C"],
            textposition="top center",
            mode="markers",
            marker=dict(
                color=twoSix['MVF'],
                colorscale='Blues',
                opacity=1.0,
                #showscale=True
            )))

    fig.add_trace(
        go.Scatter3d(
            x=twoThree['PolSpace'],
            y=twoThree['Valency'],
            #z=twoThree[' GLYCAN SPACING ON POLYMER'],
            z=twoThree['MVF'],
            name="2-3 SiaLac",
            text=["Text A", "Text B", "Text C"],
            textposition="top center",
            mode="markers",
            marker=dict(
                color=twoThree['MVF'],
                colorscale='Reds',
                opacity=1.0,
                #showscale=True
            )))

    xMin = np.min(df['PolSpace'])
    xMax = np.max(df['PolSpace'])
    x = np.linspace(xMin, xMax, 100)

    yMin = np.min(df['Valency'])
    yMax = np.max(df['Valency'])
    y = np.linspace(yMin, yMax, 100)

    xGrid, yGrid = np.meshgrid(y, x)
    z = 0.2 * np.ones(xGrid.shape)
    fig.add_trace(
        go.Surface(x=x, y=y, z=z, colorscale='Greys', showscale=False))

    fig.update_layout(scene=dict(xaxis_title='Polymer spacing',
                                 yaxis_title='Valency',
                                 zaxis_title='Mean viral fluorescence'),
                      width=700,
                      margin=dict(r=20, b=10, l=10, t=10))

    if figName == "":
        plotly.offline.plot(fig)
    else:
        plotly.offline.plot(fig, filename=figName)
    #plotly.offline.plot(fig, filename="TruePositives_Quantitative.html")
    #plotly.offline.plot(fig, filename="TruePositives_MVF.html")

    fig.show()
Ejemplo n.º 2
0
#!/usr/bin/env python3

from osgeo import gdal
import numpy as np
import plotly.graph_objects as go
import os

os.system("eio clip -o Shasta-30m-DEM.tif --bounds 19.5 48.5 21.5 50.5")

filename = "Shasta-30m-DEM.tif"
gdal_data = gdal.Open(filename)
gdal_band = gdal_data.GetRasterBand(1)
nodataval = gdal_band.GetNoDataValue()

data_array = gdal_data.ReadAsArray().astype(float)

# replace missing values if necessary
if np.any(data_array == nodataval):
    data_array[data_array == nodataval] = np.nan

# 3d generator
fig = go.Figure(data=[go.Surface(z=data_array)])
fig.update_layout(title='3D Surface of ...(bounds)', autosize=True)
fig.show()
print(data_array)

#os.system("rm -rf *.tif")
Ejemplo n.º 3
0
def Cylinder(pt1,pt2,r):
    step = 7
    data = go.Scatter3d(x=[pt1[0],pt2[0]], y=[pt1[1],pt2[1]], z=[pt1[2],pt2[2]])
    
    v = subtract(pt2,pt1)
    mag = sqrt(v[0]**2 + v[1]**2 + v[2]**2)
    unit_v = [v[0]/mag, v[1]/mag, v[2]/mag]
    unit_v=asarray(unit_v)
    dist = sqrt((pt2[0]-pt1[0])**2 + (pt2[1]-pt1[1])**2 + (pt2[2]-pt1[2])**2)
    v1 = pt1
    v2 = pt2
    pdist = dist/step
    newpts_array = []
    for i in range(0, step):
        dist_v = pdist*unit_v
        newpts = pt1 + dist_v
        newpts_array.append(newpts)
        pt1 = newpts
        newpts=list(newpts)
        theta = linspace(0,2*np.pi,100)
        phi = linspace(0,np.pi,100)

        x = newpts[0]+r*outer(cos(theta),sin(phi))
        y = newpts[1]+r*outer(sin(theta),sin(phi))    
        z = newpts[2]+r*outer(ones(100),cos(phi))

        data=go.Surface(
            x=x,
            y=y,
            z=z,
            opacity=0.3
        )
        fig.add_trace(data)

    nt = 100
    nv = 50
    mag_dist = norm(v)
    not_v=[1,0,0]
    
    if (unit_v == not_v).all():
        not_v = np.array([0, 1, 0])
    n1 = np.cross(unit_v, not_v)
    n1 /= norm(n1)
    n2 = np.cross(unit_v, n1)

    theta = np.linspace(0, 2*np.pi, nt)
    phi = linspace(0,np.pi,100)
    v = np.linspace(0, mag_dist, nv )
    rsample=np.linspace(0,r,2)
    rsample,theta = np.meshgrid(rsample,theta)
    theta1, v = np.meshgrid(theta, v)

    x,y,z = [v1[i] + unit_v[i] * v + r * np.sin(theta1) * n1[i] + r * np.cos(theta1) * n2[i] for i in [0, 1, 2]] 
    
    
    cyl1 = go.Surface(x=x, y=y, z=z,
                 showscale=False,
                 opacity=0.5)
    fig.add_trace(cyl1)

    start_end.append([v1,v2])
    radius.append(r)
    step_.append(step)
    return fig
Ejemplo n.º 4
0
def plot_surface(vals_filtered, grid_arr, meta_data, update_layout=False):
    fig = go.Figure(
        data=[
            go.Surface(
                z=vals_filtered + 0,
                x=grid_arr[0, :, 1],
                y=grid_arr[0, :, 1],
                colorscale="viridis",
                name="log(J(θ))",  # cmax=0.001, cmin=0,
                colorbar=dict(
                    thickness=130,
                    title="log(J(θ))",
                    titlefont=dict(size=80),
                    lenmode="fraction",
                    len=0.80,
                    x=0.78,
                    y=0.45,
                    tickfont=dict(size=70),
                ),
            ),
            go.Scatter3d(
                x=np.array([0]),
                y=np.array([0]),
                z=[0.0 + meta_data["center_loss"]],
                mode="markers",
                marker=dict(size=20, color=[COLOR_CENTER]),
                showlegend=False,
            ),
            go.Scatter3d(
                x=np.array([meta_data["basis_coordinates"][0][0]]),
                y=np.array([meta_data["basis_coordinates"][0][1]]),
                z=[0.0 + meta_data["basis_losses"][0]],
                mode="markers",
                marker=dict(size=20, color=[COLOR1]),
                showlegend=False,
            ),
            go.Scatter3d(
                x=np.array([meta_data["basis_coordinates"][1][0]]),
                y=np.array([meta_data["basis_coordinates"][1][1]]),
                z=[0.0 + meta_data["basis_losses"][0]],
                mode="markers",
                marker=dict(size=20, color=[COLOR2]),
                showlegend=False,
            ),
        ]
    )
    if update_layout:
        fig.update_layout(
            title=None,
            autosize=False,
            width=1280,
            height=720,
            font=dict(
                size=27,
            ),
            scene={
                "zaxis": dict(
                    title="log(J(θ))",
                    titlefont=dict(size=80),
                    range=[0, 0.001],
                    tickmode="linear",
                    tick0=0,
                    dtick=0.001,
                    tickangle=0,
                    ticks="outside",
                    tickwidth=0,
                ),
                "xaxis": dict(
                    range=[-10, 14],
                    title="c1",
                    titlefont=dict(size=80),
                    tickmode="array",
                    tickvals=[-8, 13],
                    tickangle=0,
                    ticks="outside",
                    tickwidth=0,
                ),
                "yaxis": dict(
                    range=[-14, 11],
                    title="c2",
                    titlefont=dict(size=80),
                    tickmode="array",
                    tickvals=[-13, 10],
                    tickangle=0,
                ),
            },
        )

    return fig
Ejemplo n.º 5
0
df = px.data.iris()
fig=go.Figure()

fig.add_histogram(x=df['sepal_width'])
plot(fig)

fig.add_bar(y=df['sepal_width'])
plot(fig)

# graphiques 3D

"surface"

z_data = df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
fig = go.Figure(data=[go.Surface(z=z_data, colorscale='IceFire')]) # Z1 liste de liste
fig.update_layout(title='Mountain')
plot(fig)

"nuage de points"

df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width',
              color='species', size='petal_length', size_max=18,symbol='species', opacity=0.7)
plot(fig)

"réseau de neurones"

# liens
edge_x, edge_y = [1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,1.5,3,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,3,4.5,None,],\
                 [1,0,None,1,2,None,1,4,None,3,0,None,3,2,None,3,4,None,0,1,None,0,1,None,0,3,None,2,1,None,2,3,None,4,1,None,4,3,None,]
Ejemplo n.º 6
0
    }, {
        'type': 'surface'
    }]])

c1 = np.linspace(0.5, 1.48, nd)
c2 = np.linspace(10, 20, nd)

Z1 = np.zeros((nd, nd))
Z2 = np.zeros((nd, nd))
for i in range(nd):
    for j in range(nd):
        Z1[j, i] = R1.evaluate([c1[i], c2[j]])
        Z2[j, i] = R2.evaluate([c1[i], c2[j]])

X, Y = np.meshgrid(c1, c2)
fig.add_trace(go.Surface(x=X, y=Y, z=Z1, colorscale='Viridis',
                         showscale=False),
              row=1,
              col=1)

fig.add_trace(go.Surface(x=X, y=Y, z=Z2, colorscale='Viridis',
                         showscale=False),
              row=1,
              col=2)

c1 = np.linspace(1.480001, 2.5, nd)
c2 = np.linspace(10, 20, nd)

Z1 = np.zeros((nd, nd))
Z2 = np.zeros((nd, nd))
for i in range(nd):
    for j in range(nd):
Ejemplo n.º 7
0
def gaussiannet(nn_list, plot_m, plot_s):
    # import plotly.graph_objects as gob
    #plot_m = 20
    #plot_s = .1
    m = int(plot_m / plot_s)

    # print(m)
    x = []
    y = []
    z = []
    sigma = []
    mux = []
    muy = []
    amp = []

    for i in range(0, m):
        j = i * plot_s
        x.append(j)
        y.append(j)

    for i in nn_list:
        # print(i)
        mux.append(i[0])
        muy.append(i[1])
        sigma.append(i[2])
        amp.append(i[3])

    # print('X     : ',mux)
    # print('Y     : ',muy)
    # print('sigma : ',sigma)
    # print('Ampli : ',amp)

    la = len(amp)
    mx = plot_m
    my = plot_m
    pi = math.pi
    bmax = 0

    # print(la)

    for j in range(0, m):
        a = []
        for i in range(0, m):
            b = 0
            for k in range(0, la):

                xi = x[i]
                if (mux[k] - x[i] >= mx / 2):
                    xi = x[i] + mx
                if (x[i] - mux[k] >= mx / 2):
                    xi = x[i] - mx

                yj = y[j]
                if (muy[k] - y[j] >= my / 2):
                    yj = y[j] + my
                if (y[j] - muy[k] >= my / 2):
                    yj = y[j] - my

                b = amp[k] * (1 / (2 * pi * pow(sigma[k], 2))) * math.exp(
                    -(pow((xi - mux[k]), 2) + pow(
                        (yj - muy[k]), 2)) / (2 * pow(sigma[k], 2))) + b

            bmax = max(b, bmax)
            a.append(b)
        z.append(a)

    # print(z)

    fig = pg.Figure(
        pg.Surface(
            cmin=0,
            cmax=bmax,
            contours={
                # "x": {"show": True, "start": 1.5, "end": 2, "size": 0.04, "color":"white"},
                "z": {
                    "show": True,
                    "start": 0.1,
                    "end": bmax,
                    "size": 0.1
                }
            },
            x=x,
            y=y,
            z=z))
    fig.update_layout(
        scene={
            "xaxis": {
                "nticks": 20
            },
            "zaxis": {
                "nticks": 4
            },
            'camera_eye': {
                "x": 0,
                "y": -1,
                "z": 0.5
            },
            "aspectratio": {
                "x": 1,
                "y": 1,
                "z": 0.5
            }
        })
    fig.show()
Ejemplo n.º 8
0
def show_sph_harm(l, m, real=True, N=50, use_sphere=True, plot='mpl'):
    '''
    Show the spherical harmonics on a unit sphere
    '''

    assert plot.lower() in ['mpl', 'mayavi', 'plotly']

    theta = np.linspace(0, np.pi, N)
    phi = np.linspace(0, 2 * np.pi, N)
    theta, phi = np.meshgrid(theta, phi)

    # The Cartesian coordinates of the unit sphere
    x = np.sin(theta) * np.cos(phi)
    y = np.sin(theta) * np.sin(phi)
    z = np.cos(theta)
    xyz = np.c_[x.ravel(), y.ravel(), z.ravel()]

    # from time import time
    # t0 = time()
    if real:
        ylm = sph_r(xyz, l, m).reshape(N, N)
    else:
        ylm = sph_c(xyz, l, m).reshape(N, N).real
    # t1 = time()
    # print(t1 - t0)

    # Calculate the spherical harmonic Y(l,m) and normalize to [0,1]
    fcolors = ylm
    fmax, fmin = fcolors.max(), fcolors.min()
    fcolors = (fcolors - fmin) / (fmax - fmin)
    if not use_sphere:
        r0 = np.abs(ylm)

    if plot.lower() == 'mpl':
        import matplotlib.pyplot as plt
        from matplotlib import cm, colors
        from mpl_toolkits.mplot3d import Axes3D

        # Set the aspect ratio to 1 so our sphere looks spherical
        fig = plt.figure(figsize=plt.figaspect(1.))
        ax = fig.add_subplot(111, projection='3d')

        if use_sphere:
            ax.plot_surface(x,
                            y,
                            z,
                            rstride=1,
                            cstride=1,
                            facecolors=cm.seismic(fcolors))
            xmax = ymax = zmax = np.max([x, y, z])
            xmin = ymin = zmin = np.min([x, y, z])
        else:
            ax.plot_surface(x * r0,
                            y * r0,
                            z * r0,
                            rstride=1,
                            cstride=1,
                            facecolors=cm.seismic(fcolors))
            xmax = ymax = zmax = np.max([r0 * x, r0 * y, r0 * z])
            xmin = ymin = zmin = np.min([r0 * x, r0 * y, r0 * z])

        # Turn off the axis planes
        # ax.set_axis_off()
        ax.set_xlim(xmin, xmax)
        ax.set_ylim(ymin, ymax)
        ax.set_zlim(zmin, zmax)
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_zticks([])

        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('z')
        plt.show()

    elif plot == 'mayavi':
        from mayavi import mlab
        fig = mlab.figure(size=(800, 800), bgcolor=(1, 1, 1))

        if use_sphere:
            mlab.mesh(x, y, z, colormap='seismic', scalars=fcolors)
        else:
            mlab.mesh(x * r0,
                      y * r0,
                      z * r0,
                      colormap='seismic',
                      scalars=fcolors)

        mlab.orientation_axes()
        mlab.show()

    else:
        import plotly.graph_objects as go

        if use_sphere:
            fig = go.Figure(data=[
                go.Surface(z=z,
                           x=x,
                           y=y,
                           surfacecolor=fcolors,
                           colorscale='balance',
                           showscale=False,
                           opacity=1.0,
                           hoverinfo='none')
            ], )
        else:
            fig = go.Figure(data=[
                go.Surface(z=r0 * z,
                           x=r0 * x,
                           y=r0 * y,
                           surfacecolor=fcolors,
                           colorscale='balance',
                           showscale=False,
                           opacity=1.0,
                           hoverinfo='none')
            ], )

        fig.update_layout(
            width=800,
            height=800,
        )
        fig.show()
Ejemplo n.º 9
0
from sklearn.linear_model import LogisticRegression
import numpy as np
from sklearn.cluster import KMeans
import plotly.graph_objects as go

n = 50
x = np.random.randint(0, 100, n)
y = np.random.randint(0, 100, n)
z = np.random.randint(0, 100, n)

points = [([x[i], y[i], z[i]]) for i in range(n)]
clusters = KMeans(n_clusters=2).fit(points).labels_
colors = ['red' if l == 0 else 'blue' for l in clusters]

clf = LogisticRegression()
clf.fit(points, clusters)
w = clf.coef_[0]
temp = np.linspace(0, 100, 100)
xx, yx = np.meshgrid(temp, temp)
zz = -(clf.intercept_[0] + w[0] * xx + w[1] * yx) / w[2]

figure = go.Figure()
figure.add_trace(go.Scatter3d(x=x, y=y, z=z, mode='markers', marker=dict(color=colors)))
figure.add_trace(go.Surface(x=xx, y=yx, z=zz))
figure.show()
Ejemplo n.º 10
0
xStart = -10
yStart = -10

xEnd = 10
yEnd = 10

z1 = a3d.getZSurface("x^3+y^3", xStart, yStart, xEnd, yEnd)
z1_mesh = a3d.getZMesh("x^3+y^3", -10, 10)
z2 = a3d.getZSurface("20", xStart, yStart, xEnd, yEnd)

xVals = np.arange(xStart, xEnd + 1)
yVals = np.arange(yStart, yEnd + 1)

fig = go.Figure(data=[
    go.Surface(x=xVals, y=yVals, z=z1, opacity=0.8),
    go.Scatter3d(x=xVals,
                 y=yVals,
                 z=z1,
                 mode="markers",
                 marker=dict(color='rgb(0, 0, 0)', size=2, opacity=0.6)),
    go.Surface(x=xVals,
               y=yVals,
               z=z2,
               showscale=False,
               opacity=0.8,
               colorscale='YlGnBu')
])

fig.show()
Ejemplo n.º 11
0
import time
import numpy as np

from skimage import io

vol = io.imread("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/attention-mri.tif")
volume = vol.T
r, c = volume[0].shape

# Define frames
import plotly.graph_objects as go
nb_frames = 68

fig = go.Figure(frames=[go.Frame(data=go.Surface(
    z=(6.7 - k * 0.1) * np.ones((r, c)),
    surfacecolor=np.flipud(volume[67 - k]),
    cmin=0, cmax=200
),
    name=str(k) # you need to name the frame for the animation to behave properly
)
    for k in range(nb_frames)])

# Add data to be displayed before animation starts
fig.add_trace(go.Surface(
    z=6.7 * np.ones((r, c)),
    surfacecolor=np.flipud(volume[67]),
    colorscale='Gray',
    cmin=0, cmax=200,
    colorbar=dict(thickness=20, ticklen=4)
))
Ejemplo n.º 12
0
z = load('model/z.joblib')

race_breakdown = pd.read_excel('assets/racebreakdown.xlsx')

fig2 = go.Figure(data=[
    go.Bar(name='Percent of Total Served',
           x=race_breakdown['Race'],
           y=race_breakdown['Percent of Total Served']),
    go.Bar(name='% with Perm Exit',
           x=race_breakdown['Race'],
           y=race_breakdown['Percent that had Exit to Perm'])
])
# Change the bar mode
fig2.update_layout(barmode='group')

data = [go.Surface(z=z, x=x, y=y)]
layout = go.Layout(title='Partial Dependence Plot',
                   scene={
                       'xaxis': {
                           'title': 'Income at Entry',
                           'showticklabels': False
                       },
                       'yaxis': {
                           'title': 'Length of Time Homeless',
                           'showticklabels': False
                       },
                       'zaxis': {
                           'title': 'Probability of Exit to Permanent Housing',
                           'showticklabels': False
                       }
                   },
Ejemplo n.º 13
0
def RobotBaseStructure():

    thetas = [0, -np.pi / 2, np.pi / 2, 0, np.pi / 2, np.pi]
    temp_joint_locations = thetas
    sl = JointLocations(temp_joint_locations)
    x_p, y_p, z_p = SepPoints(sl)

    x_p.insert(1, 0)
    x_p.insert(2, -2.602374e-17)

    y_p.insert(1, -0.1333)
    y_p.insert(2, -0.1333)

    z_p.insert(1, 0.1625)
    z_p.insert(2, 0.5875)

    x_p = list(np.asarray(x_p) * 1000)
    y_p = list(np.asarray(y_p) * 1000)
    z_p = list(np.asarray(z_p) * 1000)

    data = go.Scatter3d(
        x=x_p,
        y=y_p,
        z=z_p,
        marker=dict(
            size=[58, 58, 48, 48, 37.5, 37.5, 37.5, 37.5],
            opacity=0,
            color=('rgb(22, 96, 167)'),
            colorscale='Viridis',
        ),
        line=dict(
            colorscale="Viridis",
            width=50,
        ),
    )
    fig = go.Figure(data=data)
    fig.update_layout(
        scene=dict(zaxis=dict(range=[-925, 925], autorange=False),
                   yaxis=dict(range=[-925, 925], autorange=False),
                   xaxis=dict(range=[-925, 925], autorange=False)))
    fig.update_layout(scene_aspectratio=dict(x=1.4, y=1, z=1.4))

    fig.add_trace(data)
    Data = go.Mesh3d(x=[400, 400, 0, 0, 400, 400, 0, 0],
                     y=[400, -450, -450, 400, 400, -450, -450, 400],
                     z=[0, 0, 0, 0, -700, -700, -700, -700],
                     colorbar_title='z',
                     i=[7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],
                     j=[3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],
                     k=[0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],
                     name='y',
                     showscale=True)
    fig.add_trace(Data)

    #Base cylinder
    r1 = 45
    a1 = 0
    h1 = 150
    x1, y1, z1 = RobotBaseCylinder(r1, h1, a=a1)
    colorscale = [[0, 'red'], [1, 'red']]
    cyl1 = go.Surface(
        x=x1,
        y=y1,
        z=z1,
        colorscale=colorscale,
        showscale=False,
    )
    #############auto -925 925

    fig.add_trace(cyl1)

    #Plane data:

    height = 0
    Pp1 = [-800, -750, height]
    Pp2 = [-250, -750, height]
    Pp3 = [-800, 750, height]
    Pp4 = [-250, 750, height]

    fig = plane(fig, Pp1, Pp2, Pp3, Pp4)

    return fig
Ejemplo n.º 14
0
import plotly.graph_objects as go

# configure surface contours levels

fig = go.Figure(
    go.Surface(contours={
        "x": {
            "show": True,
            "start": 1.5,
            "end": 2,
            "size": 0.04,
            "color": "white"
        },
        "y": {
            "show": True,
            "start": 0.5,
            "end": 0.8,
            "size": 0.05
        }
    },
               x=[1, 2, 3, 4, 5],
               y=[1, 2, 3, 4, 5],
               z=[[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0],
                  [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]))

fig.update_layout(
    scene={
        "xaxis": {
            "nticks": 20
        },
        "zaxis": {
Ejemplo n.º 15
0
def plot_surface_3d(
    w: np.ndarray,
    X_train: np.ndarray,
    y_train: np.ndarray,
    X_test: Optional[np.ndarray] = None,
    y_test: Optional[np.ndarray] = None,
    feature_names: Tuple[str, str] = ("x1", "x2"),
    label_name: str = "y",
) -> None:
    """Plots the 2-Dimensional data

    Args:
        w: Weights of shape (3,)
        X_train: Training data (including constant) of shape (N, 3)
        y_train: Training labels of shape (N, )
        X_test: Test data (including constant) of shape (M, 3)
        y_test: Test labels of shape (M, )
        feature_names: names of features
        label_name: name of label

    """

    # Remove constant term
    X_train = X_train[:, 1:]
    X_test = X_test[:, 1:]

    eps = 1e-6

    if (X_test is not None) and (y_test is not None):
        X = np.concatenate((X_train, X_test))

    else:
        X = X_train

    x0_min, x0_max = X[:, 0].min(), X[:, 0].max()
    x1_min, x1_max = X[:, 1].min(), X[:, 1].max()
    x0_diff = x0_max - x0_min
    x1_diff = x1_max - x1_min

    xrange = np.arange(x0_min - x0_diff / 10, x0_max + x0_diff / 10 + eps,
                       x0_diff / 50)
    yrange = np.arange(x1_min - x1_diff / 10, x1_max + x1_diff / 10 + eps,
                       x1_diff / 50)

    xx, yy = np.meshgrid(xrange, yrange)
    grid = np.c_[xx.ravel(), yy.ravel()]
    preds = (grid @ w[1:] + w[0]).reshape(xx.shape)

    fig = go.Figure(data=[
        go.Scatter3d(
            x=X_train[:, 0],
            y=X_train[:, 1],
            z=y_train,
            mode="markers",
            name="train",
            marker=dict(size=5, opacity=1.0),
        )
    ])

    if (X_test is not None) and (y_test is not None):
        fig.add_trace(
            go.Scatter3d(
                x=X_test[:, 0],
                y=X_test[:, 1],
                z=y_test,
                mode="markers",
                name="test",
                marker=dict(size=5, color="green", opacity=1.0),
            ))

    fig.add_trace(
        go.Surface(x=xrange,
                   y=yrange,
                   z=preds,
                   name="pred_surface",
                   opacity=0.7))

    fig.update_layout(
        autosize=True,
        width=500,
        height=500,
        margin=dict(l=0, r=0, b=0, t=0),
        scene=dict(
            xaxis_title=feature_names[0],
            yaxis_title=feature_names[1],
            zaxis_title=label_name,
        ),
    )

    fig.update_layout(
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01))

    fig.show()
    def plot_it(self, controller):
        if controller.filename=='':
            messagebox.showerror('Error', 'No sdt file loaded!')
        else:
            #Takes main file with all pixels#
            sdt_file=SdtFile(controller.filename)
            image_size_x=sdt_file.data[0].shape[0]
            image_size_y=sdt_file.data[0].shape[1]
            #Pulls the TAC paramters from the sdt file. For some reason the 'times' array from the sdt file is not the correct times - poss software not updated for new card.
            adc_re=sdt_file.measure_info[0].adc_re
            tac_r=sdt_file.measure_info[0].tac_r
            tac_g=sdt_file.measure_info[0].tac_g
            dt=tac_r/tac_g/adc_re
            times=range(0,int(sdt_file.measure_info[0].adc_re))*dt

            #sets end point to end if gating not required
            if controller.end_gate.get()=='0':
                end_point=len(sdt_file.data[0][0][0])
                start_point=0
            else:
                start_point=round(int((int(controller.start_gate.get())*1e-12)/dt)) #converts back from ps to bins
                end_point=round(int((int(controller.end_gate.get())*1e-12)/dt))

            #If removing the BR/Noise this takes a seperate sdt file#
            if controller.SBR_var.get() == 1:
                if controller.end_gate.get() != '0':
                    messagebox.showerror('Error', 'Cannot use noise removal with gating')
                    controller.SBR_var.set('0')
                else:
                    controller.noise_file = askopenfilename(title="Choose a noise file")
                    noise_file_sdt = SdtFile(controller.noise_file)
                    noise_data=noise_file_sdt.data[0][0][start_point:end_point]

            #Processes the max counts - also finds brightest pixel for IRF if desired#
            #Also notes any pixels with no real counts in it and notes the ID's for post px-ing
            max_arr = np.zeros((image_size_y, image_size_x))
            max_count_all=0
            pixel=(0,0)
            for i in range(image_size_y):
                for j in range(image_size_x):
                    if controller.SBR_var.get() == 1:
                        sdt_file.data[0][i][j]=sdt_file.data[0][i][j]-noise_data
                    max_count=np.amax(sdt_file.data[0][i][j][start_point:end_point])
                    max_arr[i][j]=max_count
                    if max_count > max_count_all:
                        max_count_all=max_count
                        pixel=(i,j)
            empty_pixels=np.transpose(np.nonzero(max_arr < 2))
            #plots the brightest and fits it to see where we're at
            centre, scale = fit_exp_mod_gauss(times[start_point:end_point], sdt_file.data[0][pixel[0]][pixel[1]][start_point:end_point], dt, plotting=True)
            #Checks if you're happy with gating?
            MsgBox = tk.messagebox.askquestion ('Proceed?','Are you happy with the gating?',icon = 'warning')
            if MsgBox == 'yes':
                #Takes brightest pixel as IRF or takes external sdt file#
                if controller.IRF_var.get() == 1:
                    IRF_pix = sdt_file.data[0][pixel[0]][pixel[1]][start_point:end_point]
                elif controller.fit_var.get() == 1:
                    pass
                else:
                    controller.IRF_file = askopenfilename(title="Choose IRF sdt file")
                    IRF_file_sdt = SdtFile(controller.IRF_file)
                    max_irf = np.argmax(IRF_file_sdt.data[0][0])
                    half_gate = ((int(controller.end_gate.get())-int(controller.start_gate.get()))/2)
                    start_irf = int(max_irf-half_gate)
                    stop_irf = int(max_irf+half_gate)
                    IRF_pix = IRF_file_sdt.data[0][0][start_irf:stop_irf] 
                    plt.plot(IRF_pix)
                    plt.show()    

                #prepare an empty 2d arr
                img_arr = np.zeros((image_size_y, image_size_x))    

                #either fit or X-corr
                if controller.fit_var.get() == 1:
                    for i in range(image_size_y):
                        for j in range(image_size_x):
                            try:
                                centre, scale = fit_exp_mod_gauss(times[start_point:end_point], sdt_file.data[0][i][j][start_point:end_point], dt)
                                img_arr[i,j]=centre
                            except TypeError:
                                img_arr[i,j]=float('nan')
                            except RuntimeError:
                                img_arr[i,j]=float('nan')                
                else:
                    #cross correlates the data#
                    for i in range(image_size_y):
                        for j in range(image_size_x):
                            corr = cross_correlate(sdt_file.data[0][i][j][start_point:end_point] , IRF_pix)
                            max_val = np.argmax(corr)
                            img_arr[i,j]=max_val       
                
                #Scale and convert to mm
                img_arr= -img_arr - np.nanmean(-img_arr)
                img_arr=img_arr*1e-6*3e8*0.5*0.5
                #Bit of data manipulation for any pixels that are huge
                if controller.cut_off_max.get() != '0':
                    super_threshold_indices = img_arr > float(controller.cut_off_max.get())
                    img_arr[super_threshold_indices] = np.mean(img_arr) 

                #If pixels have no counts (or just noise) then leave them out.
                for i in empty_pixels:
                    img_arr[i[0], i[1]] = np.nan


                ####PLOTS####
                #3d#
               # fig1=plt.figure()
               # f1_ax=fig1.gca(projection='3d')
               # x_data=np.arange(image_size_x)
               # y_data=np.arange(image_size_y)
               # x_data, y_data=np.meshgrid(x_data, y_data)
               # surf=f1_ax.plot_surface(x_data, y_data, img_arr, cmap=cm.jet)
               # fig1.colorbar(surf, shrink=0.5, aspect=5)
               # fig1.suptitle('3D')
                
                #2d#
               # fig2=plt.figure()
               # flat_plot=plt.imshow(img_arr, cmap=cm.jet)
               # fig2.colorbar(flat_plot, shrink=0.5, aspect=5)
               # fig2.suptitle('2D')
                
                #counts#
                fig3=plt.figure()            
                cnt_map=plt.imshow(max_arr, cmap=cm.jet)
                fig3.colorbar(cnt_map, shrink=0.5, aspect=5)
                fig3.suptitle('Counts Map')    

                fig5=go.Figure(data=[go.Heatmap(z=img_arr, colorscale='Jet', colorbar=dict(thickness=80,
                               ticklen=3, tickcolor='black',
                               tickfont=dict(size=36, color='black')))])
                fig5.update_layout(width = 1500, height = 1500, font=dict(family="Arial",size=36,color="black"))
                fig5.show()    

                if controller.aspect_togg.get() == 1:
                    if controller.scene_size.get() == '':
                        messagebox.showerror('Error', 'You have not entered a scene size!')
                        aspect_dict=dict(x=1,y=1,z=1)
                    else:
                        scene_size=int(controller.scene_size.get()) #mm
                        aspect_dict=dict(x=1, y=1, z=np.nanmax(img_arr)/(scene_size*1e3))
                else:
                    aspect_dict=dict(x=1,y=1,z=1)
            
                fig6=go.Figure(data=[go.Surface(z=img_arr, colorscale='Jet', colorbar=dict(thickness=40,
                               ticklen=3, tickcolor='black',
                               tickfont=dict(size=9, color='black')))])
                fig6.update_layout(font=dict(family="Arial",size=9,color="black"), scene=dict(aspectmode='manual',
                               aspectratio=aspect_dict))
                fig6.show()
                
                #plots one histogram from a bright pixel to check for gating errors etc and check fit
                #fig4=plt.figure()
                #plt.plot(times[start_point:end_point], sdt_file.data[0][pixel[0]][pixel[1]][start_point:end_point],'o')
                #fig4.suptitle('Brightest histogram')
                
                plt.show()
            else:
                pass
Ejemplo n.º 17
0
# ## Plotting
#
# We use `plotly` to produce an interactive 3D surface plot, and add arrows to represent the vector field at a given radial distance.

# In[10]:

Rout = 1.1
sizeref = 0.8
step = 1

fig = go.Figure()

fig.add_trace(
    go.Surface(x=xx,
               y=yy,
               z=zz,
               surfacecolor=Ylm[:, :, rhalf],
               showscale=False,
               colorscale='RdBu'))

fig.add_trace(
    go.Cone(x=Rout * np.concatenate(xx[::step, ::step]),
            y=Rout * np.concatenate(yy[::step, ::step]),
            z=Rout * np.concatenate(zz[::step, ::step]),
            u=np.concatenate(u[::step, ::step]),
            v=np.concatenate(v[::step, ::step]),
            w=np.concatenate(w[::step, ::step]),
            showlegend=False,
            showscale=False,
            colorscale=[(0, "orange"), (0.5, "orange"), (1, "orange")],
            sizemode="absolute",
            sizeref=sizeref))
Ejemplo n.º 18
0
def vol_plot(x):
    import os  #TO control directories
    import nibabel as nib  # read and save medical images
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import plotly
    import plotly.express as px
    from ipywidgets import interact, interactive, fixed, interact_manual
    import ipywidgets as widgets
    from skimage import io  #用于读取保存或显示图片或者视频

    import timeit  #compute time, useage: timeit.timeit()
    import math
    import time
    import warnings
    import numpy as np

    import nipype.interfaces.fsl as fsl  #topup
    from nipype.interfaces.fsl import TOPUP
    from nipype.interfaces.fsl import ApplyTOPUP
    from nipype.interfaces.fsl import Eddy
    from nipype.testing import anatfile

    from dipy.denoise.localpca import mppca  #denoising
    from dipy.io import read_bvals_bvecs
    from dipy.core.gradients import gradient_table
    from dipy.reconst.dti import TensorModel
    from dipy.reconst.dti import fractional_anisotropy
    from dipy.reconst.dti import color_fa
    import dipy.reconst.dki as dki
    "to create 3D  MRI figure with slider"
    vol = x
    colormax = vol.max()  #获取最大array中的最大值,最后代表cmax
    volume = vol.T
    len(volume)
    r, c = volume[math.floor(len(volume) / 2)].shape
    # Define frames
    import plotly.graph_objects as go
    nb_frames = len(volume) - 1
    fig = go.Figure(frames=[
        go.Frame(
            data=go.Surface(z=(len(volume) - 1 - k) * np.ones((r, c)),
                            surfacecolor=volume[len(volume) - 1 - k],
                            cmin=0,
                            cmax=colormax),
            name=str(k)  # name the frame for the animation to behave properly
        ) for k in range(nb_frames)
    ])
    # Add data to be displayed before animation starts
    fig.add_trace(
        go.Surface(
            z=(len(volume) - 1) * np.ones((r, c)),
            surfacecolor=volume[len(volume) - 1],  #np.flipud(volume[30]),
            colorscale='gray',
            cmin=0,
            cmax=colormax,
            colorbar=dict(thickness=20, ticklen=4)))

    def frame_args(duration):
        return {
            "frame": {
                "duration": 500
            },  # Duration can be used to change animate speed
            "mode": "immediate",
            "fromcurrent": True,
            "transition": {
                "duration": 500,
                "easing": "linear"
            },
        }
        sliders = [{
            "pad": {
                "b": 10,
                "t": 60
            },
            "len":
            0.9,
            "x":
            0.1,
            "y":
            0,
            "steps": [{
                "args": [[f.name], frame_args(0)],
                "label": str(k),
                "method": "animate",
            } for k, f in enumerate(fig.frames)],
        }]
        # Layout
        fig.update_layout(
            title='Slices in volumetric data',
            width=600,
            height=600,
            scene=dict(
                zaxis=dict(range=[-1, len(volume) - 1], autorange=False),
                aspectratio=dict(x=1, y=1, z=1),
            ),
            updatemenus=[{
                "buttons": [
                    {
                        "args": [None, frame_args(50)],
                        "label": "&#9654;",  # play symbol
                        "method": "animate",
                    },
                    {
                        "args": [[None], frame_args(0)],
                        "label": "&#9724;",  # pause symbol
                        "method": "animate",
                    },
                ],
                "direction":
                "left",
                "pad": {
                    "r": 10,
                    "t": 70
                },
                "type":
                "buttons",
                "x":
                0.1,
                "y":
                0,
            }],
            sliders=sliders)

    fig.show()
Ejemplo n.º 19
0
# In[14]:

import plotly.graph_objects as go

num_points = 50  # increase for better resolution, but it will run more slowly.

if (num_points <= 100):

    uvalues = np.linspace(-0.3, 0.3, num_points)
    vvalues = np.linspace(-20, 20, num_points)
    (u, v) = np.meshgrid(uvalues, vvalues)
    thetas = np.vstack((u.flatten(), v.flatten()))

    MSE = np.array([mse_for_model_on_NBA_data(t) for t in thetas.T])

    loss_surface = go.Surface(x=u, y=v, z=np.reshape(MSE, u.shape))

    fig = go.Figure(data=[loss_surface])
    fig.update_layout(scene=dict(
        xaxis_title="theta0", yaxis_title="theta1", zaxis_title="MSE"))
    fig.show()
else:
    print("Too many points. Choose smaller number of points so code can run.")

# ### Minimizing MSE

# In[15]:

from scipy.optimize import minimize

optimal_theta = minimize(mse_for_model_on_NBA_data, [0, 0])
Ejemplo n.º 20
0
# dest.write(crop_dsm_img)

# Show cropped tiff
#show(rasterio.open(f"{crop_tif}"), cmap ='pink')
# Show tiff file
#show(rasterio.open(f"{data_dsm_path + item.name}"), cmap="cividis")
#show(crop_dsm_img)
'''fig = make_subplots(
    rows=1, cols=2,
    specs=[[{'type': 'surface'}, {'type': 'surface'}]])


fig.add_trace(
    go.Surface(z=np.flip(crop_chm_img, axis=1), colorscale='YlOrRd', showscale=False),
    row=1, col=1)

fig.add_trace(
    go.Surface(z=np.flip(crop_chm_img1, axis=1), colorscale='RdBu', showscale=False),
    row=1, col=2)
'''
#print(crop_chm_img)
print(crop_dsm_img)
fig = go.Figure(
    data=go.Surface(z=np.flip(crop_chm_img1, axis=1), colorscale='blackbody'))
fig.update_layout(scene_aspectmode='manual',
                  scene_aspectratio=dict(x=1, y=1, z=0.5))
fig.show()

print(type(crop_chm_img))
print("Done")
Ejemplo n.º 21
0
import plotly.graph_objects as go
import numpy as np

# Mutiple 3D surface plot
z1 = np.array([[8.83, 8.89, 8.81, 8.87, 8.9, 8.87],
               [8.89, 8.94, 8.85, 8.94, 8.96, 8.92],
               [8.84, 8.9, 8.82, 8.92, 8.93, 8.91],
               [8.79, 8.85, 8.79, 8.9, 8.94, 8.92],
               [8.79, 8.88, 8.81, 8.9, 8.95, 8.92],
               [8.8, 8.82, 8.78, 8.91, 8.94, 8.92],
               [8.75, 8.78, 8.77, 8.91, 8.95, 8.92],
               [8.8, 8.8, 8.77, 8.91, 8.95, 8.94],
               [8.74, 8.81, 8.76, 8.93, 8.98, 8.99],
               [8.89, 8.99, 8.92, 9.1, 9.13, 9.11],
               [8.97, 8.97, 8.91, 9.09, 9.11, 9.11],
               [9.04, 9.08, 9.05, 9.25, 9.28, 9.27],
               [9, 9.01, 9, 9.2, 9.23, 9.2],
               [8.99, 8.99, 8.98, 9.18, 9.2, 9.19],
               [8.93, 8.97, 8.97, 9.18, 9.2, 9.18]])

z2 = z1 + 1
z3 = z1 - 1

fig = go.Figure(data=[
    go.Surface(z=z1),
    go.Surface(z=z2, showscale=False, opacity=0.9),
    go.Surface(z=z3, showscale=False, opacity=0.9)
])

fig.show()
Ejemplo n.º 22
0
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

river_height_data = read_data("braided-river")
sh_0, sh_1 = river_height_data.shape[1:]

fig = go.Figure(data=[
    go.Surface(z=river_height_data[500],
               contours={
                   "x": {
                       "show": False
                   },
                   "y": {
                       "show": False
                   },
                   "z": {
                       "show": True,
                       "start": 5000000,
                       "end": 14000000,
                       "size": 1500000,
                       "color": 'white'
                   }
               })
], )
fig.update_layout(title='River',
                  autosize=False,
                  scene=dict(aspectmode='manual',
                             aspectratio=dict(x=10, y=1, z=0.5)),
                  width=1500,
                  height=750,
                  margin=dict(r=20, l=10, b=10, t=10))
Ejemplo n.º 23
0
        bytess = file.read(4)
        if not bytess:
            break
        floats.append(struct.unpack('<f', bytearray(bytess)))

matrixZ = np.zeros((data.Len.Y, data.Len.X), 'float32')
index = 0
for y in range(data.Len.Y):
    for x in range(data.Len.X):
        matrixZ[y][x] = data.Level + floats[index][0]
        index += 1

go.Figure(
    go.Surface(contours={
        "x": {
            "show": True,
            "start": data.Start.X,
            "end": data.Last.X,
            "size": data.Step.X,
            "color": "white"
        },
        "z": {
            "show": True,
            "start": data.Start.Y,
            "end": data.Last.Y,
            "size": data.Step.Y
        }
    },
               x=np.arange(data.Len.X),
               y=np.arange(data.Len.Y),
               z=matrixZ)).show()
def animate_3d(image, nb_frames=100, plot=False):
    if nb_frames > image.shape[2]:
        nb_frames = image.shape[2]

    vol = image
    volume = vol.T
    r, c = volume[0].shape

    # Define frames
    fig = go.Figure(frames=[
        go.Frame(
            data=go.Surface(z=((nb_frames - 1) / 10 - k * 0.1) *
                            np.ones((r, c)),
                            surfacecolor=np.flipud(volume[nb_frames - 1 - k]),
                            cmin=image.min(),
                            cmax=image.max()),
            name=str(k)  # you need to name the frame
        ) for k in range(nb_frames)
    ])

    # Add data to be displayed before animation starts
    fig.add_trace(
        go.Surface(z=(nb_frames - 1) / 10 * np.ones((r, c)),
                   surfacecolor=np.flipud(volume[nb_frames - 1]),
                   colorscale='Gray',
                   cmin=image.min(),
                   cmax=image.max(),
                   colorbar=dict(thickness=20, ticklen=4)))

    def frame_args(duration):
        return {
            "frame": {
                "duration": duration
            },
            "mode": "immediate",
            "fromcurrent": True,
            "transition": {
                "duration": duration,
                "easing": "linear"
            },
        }

    sliders = [{
        "pad": {
            "b": 10,
            "t": 60
        },
        "len":
        0.9,
        "x":
        0.1,
        "y":
        0,
        "steps": [{
            "args": [[f.name], frame_args(0)],
            "label": str(k),
            "method": "animate",
        } for k, f in enumerate(fig.frames)],
    }]

    # Layout
    fig.update_layout(
        title='Slices in volumetric data',
        width=600,
        height=600,
        scene=dict(
            zaxis=dict(range=[-0.1, nb_frames / 10], autorange=False),
            aspectratio=dict(x=1, y=1, z=1),
        ),
        updatemenus=[{
            "buttons": [
                {
                    "args": [None, frame_args(50)],
                    "label": "&#9654;",  # play symbol
                    "method": "animate",
                },
                {
                    "args": [[None], frame_args(0)],
                    "label": "&#9724;",  # pause symbol
                    "method": "animate",
                },
            ],
            "direction":
            "left",
            "pad": {
                "r": 10,
                "t": 70
            },
            "type":
            "buttons",
            "x":
            0.1,
            "y":
            0,
        }],
        sliders=sliders)

    if plot:
        fig.show()
        offline_plot(fig)

    return fig
Ejemplo n.º 25
0
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np


def f(x, y):
    return np.sin(x) * np.cos(y)


x = np.linspace(-6, 6, 60)
y = np.linspace(-6, 6, 60)

X, Y = np.meshgrid(x, y)

Z = f(X, Y)
fig = make_subplots(
    rows=1,
    cols=1,
    specs=[[{
        'is_3d': True
    }]],
    subplot_titles=['Lab3'],
)
fig.layout.autosize = True

fig.add_trace(go.Surface(x=X, y=Y, z=Z, opacity=0.7, surfacecolor=Z))
fig.update_layout(title_text="Lab3")
fig.show()
Ejemplo n.º 26
0
w1 = w(r, z, dp)
#z2 = z.reshape(1, 100)
#print(w(0.75, 2, 0.3))

z = np.repeat(z.reshape(1, 100), repeats=100, axis=0)

fig = go.Figure(
    go.Surface(contours={
        "x": {
            "show": True,
            "start": 1.5,
            "end": 2,
            "size": 0.04,
            "color": "white"
        },
        "z": {
            "show": True,
            "start": 0.5,
            "end": 0.8,
            "size": 0.05
        }
    },
               x=r,
               y=z[0],
               z=w1))
fig.update_layout(
    scene={
        "xaxis_title": "Radius r",
        "yaxis_title": "Axial Z",
        "zaxis_title": "Axial velocity w",
        "xaxis": {
            "nticks": 10
Ejemplo n.º 27
0
#import cylinder as c


##################### for plane
def plane(height):

    x = 80 + np.linspace(-1, 100, 75)
    y = np.linspace(0, 100, 100)
    z = height * np.ones((100, 75))
    return x, y, z


x1, y1, z1 = plane(1)
mycolorscale = [[0, '#aa9ce2'], [1, '#aa9ce2']]
surf = go.Surface(x=x1, y=y1, z=z1, colorscale=mycolorscale, showscale=False)
layout = go.Layout(
    width=1800,
    scene_camera_eye_z=0.75,
    title="Start Title",
    updatemenus=[
        dict(type="buttons",
             buttons=[dict(label="Play", method="animate", args=[None])])
    ])
fig = go.Figure(data=[surf], layout=layout)

############################# for cuboids

data = go.Mesh3d(
    # 8 vertices of a cube
    x=[50, 50, 70, 70, 50, 50, 70, 70],
Ejemplo n.º 28
0
x1 = np.arange(-5, 5, 0.5)
x2 = np.arange(-5, 5, 0.5)
x1, x2 = np.meshgrid(x1, x2)
fig = go.Figure(
    go.Surface(contours={
        "x": {
            "show": True,
            "start": -4,
            "end": 4,
            "size": 0.4,
            "color": "white"
        },
        "y": {
            "show": True,
            "start": -4,
            "end": 4,
            "size": 0.4,
            "color": "white"
        },
        "z": {
            "show": True,
            "start": 0.5,
            "end": 800,
            "size": 5
        }
    },
               x=x1,
               y=x2,
               z=rosenbrock(x1, x2)))

fig.show()
Ejemplo n.º 29
0
                                             value=r'\\filepath\example')

gcr_config = st.sidebar.slider(label="Ground Coverage Ratio Range Selection")

sr_config = st.sidebar.slider(label='Sizing Ratio Range Selection',
                              min_value=1.0,
                              max_value=2.0,
                              step=0.1,
                              value=(1.0, 1.5))

run_button = st.sidebar.button(label='Run Optimization')

progress_bar = st.sidebar.progress(0)

st.title(project_title)

z_data = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv'
)
z = z_data.values
sh_0, sh_1 = z.shape
x, y = np.linspace(0, 1, sh_0), np.linspace(0, 1, sh_1)
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])

fig.update_layout(title='IRR',
                  autosize=False,
                  width=800,
                  margin=dict(l=40, r=40, b=40, t=40))

st.plotly_chart(fig)
Ejemplo n.º 30
0
    for index_column, (column_x, column_y) in enumerate(zip(row_x, row_y)):
        mse_value = Find_MSE(per=column_x, sft=column_y)
        #print ("Index_Row = {}".format(index_row))
        #print ("Index_Col = {}".format(index_column))
        Z[index_row][index_column] = mse_value

# Make pd.dataframe from multilayered list:
df = pd.DataFrame(Z,
                  index=list(np.linspace(12.0, 24.0, 121)),
                  columns=list(np.linspace(6.0, 42.0, 361)))
print(df)
print(df.shape)

fig = go.Figure(data=[
    go.Surface(x=list(np.linspace(6.0, 42.0, 361)),
               y=list(np.linspace(12.0, 24.0, 121)),
               z=df,
               opacity=0.8)
])

fig.update_layout(scene=dict(
    xaxis=dict(nticks=7, range=[6.0, 42.0]),
    yaxis=dict(nticks=7, range=[12.0, 24.0]),
    xaxis_title='X-axis: PERIOD [6.0-42.0]\n0.5 increments',
    yaxis_title='Y-axis: SHIFT_V [12.0-24.0]\n0.5 increments',
    zaxis_title='Z-axis: MSE sum for ~420\n2-gen families'),
                  title='Locked Amplitude = {}'.format(amplitude),
                  autosize=False,
                  width=700,
                  height=700,
                  margin=dict(l=65, r=50, b=65, t=90))