def table_graph(price, units, n_click):
    if n_click == None or n_click % 2 == 0:
        table_data = []  # empty table
        table_columns = []
        fig = go.Figure(data=[go.Mesh3d(x=[], y=[], z=[])])
        return (table_data, table_columns, fig)
    elif (n_click % 2 == 1):
        # build the table. data and styling goes here! Format() is a lifesaver.
        tbl = cost_table(price, units=units)
        table_data = tbl.to_dict('records')
        table_columns = [{
            "name": i,
            "id": i,
            "type": "numeric",
            "format": Format(precision=4)
        } for i in tbl.columns]
        # build the graph. data and styling goes here!
        fig = go.Figure(data=[
            go.Mesh3d(z=tbl['Cost'],
                      x=tbl['Number of Days'],
                      y=tbl['Total Number of Jobs'],
                      opacity=1,
                      intensity=tbl['Cost'],
                      colorscale="Inferno")
        ])
        fig.update_layout(title="Job cost over time and number of jobs",
                          scene=dict(xaxis_title="Number of Days (X)",
                                     yaxis_title="Total Number of Jobs (Y)",
                                     zaxis_title="Cost (Z)"))
    return (table_data, table_columns, fig)
Exemple #2
0
def drawtets(nodes, tets, values):
    
    try:
        nodes = np.array(nodes)
        tets = np.array(tets)
        values = np.array(values)
        
    #    assert tets.shape[1] == 4
        
        #tets helper
        t_h = np.hstack([tets,tets[:,:2]])
        tri = np.vstack([t_h[:,0:3],t_h[:,1:4],t_h[:,2:5],t_h[:,3:6]])
        tri = np.rot90(tri,-1)
        
        return go.Mesh3d(
            x=nodes[:,0].flatten(), #x=[0, 1, 2, 0],
            y=nodes[:,1].flatten(), #y=[0, 0, 1, 2],
            z=nodes[:,2].flatten(), #z=[0, 2, 0, 1],
    #        colorbar_title='values',
            colorscale=[[0, 'gold'], 
                        [0.5, 'mediumturquoise'], 
                        [1, 'magenta']],
            # Intensity of each vertex, which will be interpolated and color-coded
            intensity=np.rot90(np.vstack([values]*4),-1).flatten(), #intensity=[0, 0.33, 0.66, 1],
            # i, j and k give the vertices of triangles
            # here we represent the 4 triangles of the tetrahedron surface
            i=tri[0].flatten(),    #i=[0, 0, 0, 1],
            j=tri[1].flatten(),    #j=[1, 2, 3, 2],
            k=tri[2].flatten(),    #k=[2, 3, 1, 3],
            name='tets',
            showscale=True
        )
    except:
        return go.Mesh3d()
Exemple #3
0
def volume2plotly(x, colormap, **kwargs):
    """Convert Volumes to plotly objects."""
    trace_data = []
    for i, v in enumerate(x):
        # Skip empty data
        if isinstance(v.vertices, np.ndarray):
            if not v.vertices.any():
                continue
        elif not v.vertices:
            continue

        name = getattr(v, 'name', None)

        c = colormap[i]
        if len(c) == 3:
            c = (c[0], c[1], c[2], .5)

        rgba_str = f'rgba({c[0]:.0f},{c[1]:.0f},{c[2]:.0f},{c[3]:.1f})'
        trace_data.append(
            go.Mesh3d(x=v.vertices[:, 0],
                      y=v.vertices[:, 1],
                      z=v.vertices[:, 2],
                      i=v.faces[:, 0],
                      j=v.faces[:, 1],
                      k=v.faces[:, 2],
                      color=rgba_str,
                      name=name,
                      showlegend=kwargs.get('volume_legend', False),
                      hoverinfo='none'))

    return trace_data
def createHead(headTransform_4x4 = np.eye(4)):

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

        x = np.cos(theta) * np.sin(phi) * .15
        y = np.sin(theta) * 0.2
        z = np.cos(theta) * np.cos(phi) * .15
        w = np.ones(2500)

        x = x.flatten()
        y = y.flatten()
        z = z.flatten()

        if headTransform_4x4 is False:
            headVertices_XYZW =np.array([x,y,z,w])
        else:
            headVertices_XYZW = np.dot( headTransform_4x4,[x,y,z,w])

        headShape = go.Mesh3d({ 'x':headVertices_XYZW[0,:], 
                      'y': headVertices_XYZW[2,:], 
                      'z': headVertices_XYZW[1,:],'alphahull': 0},
                      color='rgb(20, 145, 145)',
                      )

        return headShape
Exemple #5
0
def plot_stress_meshed(mesh,stress):
    """
    Plots the stress on a real mesh using plotly
    :param mesh: The mesh
    :param stress: The stress
    """
    data = [
        go.Mesh3d(
            x=[0, 1, 2, 0],
            y=[0, 0, 1, 2],
            z=[0, 2, 0, 1],
            colorbar=go.ColorBar(
                title='z'
            ),
            colorscale=[[0, 'rgb(255, 0, 0)'],
                        [0.5, 'rgb(0, 255, 0)'],
                        [1, 'rgb(0, 0, 255)']],
            intensity=[0, 0.33, 0.66, 1],
            i=[0, 0, 0, 1],
            j=[1, 2, 3, 2],
            k=[2, 3, 1, 3],
            name='y',
            showscale=True
        )
    ]
    layout = go.Layout(
        xaxis=go.XAxis(
            title='x'
        ),
        yaxis=go.YAxis(
            title='y'
        )
    )
    fig = go.Figure(data=data, layout=layout)
    py.plot(fig, filename='/home/leon/Documents/RCI/TMA4220_NumPDE/3d-mesh-tetrahedron-python')
Exemple #6
0
def plot_box(pd, pos, quat, size):
    d = -size
    p = size
    X = np.array([[d[0], d[0], p[0], p[0], d[0], d[0], p[0], p[0]],
                  [d[1], p[1], p[1], d[1], d[1], p[1], p[1], d[1]],
                  [d[2], d[2], d[2], d[2], p[2], p[2], p[2], p[2]]])

    R = Rotation.from_quat(quat)
    X = R.apply(X.T) + pos

    pd.append(
        go.Mesh3d(
            # 8 vertices of a cube
            x=X[:, 0],
            y=X[:, 1],
            z=X[:, 2],
            flatshading=True,
            lighting=dict(facenormalsepsilon=0),
            lightposition=dict(x=2000, y=1000),
            color='yellow',
            opacity=0.2,
            # i, j and k give the vertices of triangles
            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=False))
Exemple #7
0
def work_space(robobj, limit1, limit2):

    x_range = np.linspace(limit1[0], limit2[0])
    y_range = np.linspace(limit1[1], limit2[1])
    z_range = np.linspace(limit1[2], limit2[2])

    allpts = product(x_range, y_range, z_range)
    print(allpts)
    i = 0

    mat_x = np.zeros(2**robobj.jointno)
    mat_y = np.zeros(2**robobj.jointno)
    mat_z = np.zeros(2**robobj.jointno)

    while i < 2**robobj.jointno:
        m = kin.fwd(robobj, cp[i])
        mat_x[i] = m[robobj.jointno][0]
        mat_y[i] = m[robobj.jointno][1]
        mat_z[i] = m[robobj.jointno][2]
        i = i + 1

        vol = go.Mesh3d(x=mat_x,
                        y=mat_y,
                        z=mat_z,
                        opacity=1,
                        color='rgba(244,22,100,0.6)')
    return vol
Exemple #8
0
 def mesh_plot(self,
               file_name,
               data,
               x_label,
               y_label,
               z_label,
               options_dict=None,
               title_dict=None,
               x_range=None,
               y_range=None,
               z_range=None,
               **layout_kwargs):
     self.reset_graph_object()
     if options_dict is None:
         options_dict = {}
     options_dict = {
         **dict(colorbar=go.ColorBar(title=z_label)),
         **options_dict
     }
     self.data = [
         go.Mesh3d(x=data.loc[:, x_label].values,
                   y=data.loc[:, y_label].values,
                   z=data.loc[:, z_label].values,
                   **options_dict)
     ]
     self.plot_single_graph(file_name, title_dict, x_range, y_range,
                            z_range, **layout_kwargs)
Exemple #9
0
def plotSurface(Mat,x=None,y=None):
    """
    :param Mat:
    :param x:
    """

    if x is None or y is None:
        x,y = np.meshgrid( np.arange(Mat.shape[0]), np.arange(Mat.shape[1]) )

    x,y,z = convertMeshPoint(x,y,Mat)
    trace1 = go.Mesh3d(x=x,
                   y=y,
                   z=z,
                   opacity=0.5,
                   color='#66CCFF'
                  )

    layout = go.Layout(
                        scene = dict(
                        xaxis = dict(
                            nticks=4, range = [-100,100],),
                        yaxis = dict(
                            nticks=4, range = [-50,100],),
                        zaxis = dict(
                            nticks=4, range = [-100,100],),),
                        width=700,
                        margin=dict(
                        r=20, l=10,
                        b=10, t=10)
                      )
    fig = go.Figure(data=[trace1], layout=layout)
    iplot(fig)
Exemple #10
0
def arrowhead3d(start, end, size=None, **kwargs):
    '''
    @brief plot an arrowhead on a 3d plotly plot (just 2 perpidicular planes)
    @param[in] start - iterable of (x,y,z) starting points (back of the arrow)
    @param[in] stop - iterable of (x,y,z) end points (tip of the arrow)
    '''
    arr_vec = np.asarray(end) - np.asarray(start)
    arr_vec_norm = arr_vec / np.sqrt(np.sum(arr_vec**2))
    if size is None:
        size = np.sqrt(np.sum(arr_vec**2))
    # now create the template arrow. arrow tip at the origin pointing up the z axis [[xxx],[yyy],[zzz]]
    template = np.asarray([[0, 0, 0], [0, 1, -1], [0, -1, -1]]) * size
    # now calculate our rotation
    r, theta, phi = cart2sphere(*arr_vec)  # get theta,phi
    # now calculate the positions
    meshes = []
    for rot in [0, np.pi / 2]:
        coords = (Rz(phi) @ Ry(theta) @ Rz(rot)
                  @ template) + np.asarray(end)[..., np.newaxis]
        tc = {
            'x': coords[0, :],
            'y': coords[1, :],
            'z': coords[2, :],
            'i': [0],
            'j': [1],
            'k': [2],
        }
        tc.update(**kwargs)
        meshes.append(go.Mesh3d(**tc))
    return meshes
Exemple #11
0
def get_3D_volume(path, opacity=1, color="red"):
    data = nib.load(path).get_data()
    verts, faces = measure.marching_cubes_classic(data, level=0.)
    x, y, z = zip(*verts)
    i, j, k = zip(*faces)

    lighting_effects = dict(ambient=0.6,
                            diffuse=.5,
                            roughness=0.2,
                            specular=.5,
                            fresnel=0.2)
    trace = go.Mesh3d(x=x,
                      y=y,
                      z=z,
                      i=i,
                      j=j,
                      k=k,
                      opacity=opacity,
                      color=color,
                      flatshading=None,
                      lighting=lighting_effects,
                      lightposition=dict(x=25, y=100, z=50))
    #alphahull=1, intensity=values
    #plotly.offline.iplot([trace])
    return trace
Exemple #12
0
def scatter_cubes(coords, cubesize=1, color='orange', opacity=0.8, hovertext=None, colorscale=None, **kwargs):
    """
    Produces go.Mesh3d object to be plotted in plotly
    - coords is a list of cubes coordinates (Nx3 matrix)
    """
    base_x = np.array([0, 0, 1, 1, 0, 0, 1, 1]) * cubesize
    base_y = np.array([0, 1, 1, 0, 0, 1, 1, 0]) * cubesize
    base_z = np.array([0, 0, 0, 0, 1, 1, 1, 1]) * cubesize
    trace = []
    cmin, cmax = None, None
    if not isinstance(color, str):
        cmin = min(color)
        cmax = max(color)
    for i in range(len(coords)):
        trace.append(
                go.Mesh3d(
                    x=(coords[i][0]-0.5) * cubesize + base_x,
                    y=(coords[i][1]-0.5) * cubesize + base_y,
                    z=(coords[i][2]-0.5) * cubesize + base_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],
                    opacity=opacity,
                    color=color if isinstance(color, str) else color[i],
                    colorscale=colorscale,
                    cmin=cmin,
                    cmax=cmax,
                    hoverinfo=['x','y','z'] if hovertext is None else ['x', 'y', 'z','text'],
                    hovertext=hovertext,
                    **kwargs
                    )
                )
    return trace
def plot_3d_mesh(voxels, color='#26638F', opacity=0.5):
    """
    Plots the 3d volume as mesh using Plotly.
    :param voxels: volume as voxels. can be Tensor or np.ndarray
    :param color: rba code of the color
    :param opacity: opacity value

    """
    if isinstance(voxels, torch.Tensor):
        if voxels.is_cuda:
            voxels = voxels.cpu()
        voxels = voxels.numpy()
    voxels = voxels.squeeze()
    # do padding in order to avoid surface on the sides not showing
    voxels = np.pad(voxels,
                    pad_width=((1, 1), (1, 1), (1, 1)),
                    mode='constant')
    v, f, _, _ = marching_cubes_lewiner(voxels)  #

    x = v[:, 0].tolist()
    y = v[:, 1].tolist()
    z = v[:, 2].tolist()
    i = f[:, 0].tolist()
    j = f[:, 1].tolist()
    k = f[:, 2].tolist()

    trace = go.Mesh3d(x=x,
                      y=y,
                      z=z,
                      i=i,
                      j=j,
                      k=k,
                      color=color,
                      opacity=opacity)
    iplot([trace])
def make_tri_plot(x,y,z, simplices, c=None, offset=(0,0), name='', **kwargs):
    return go.Mesh3d(x=x+d_off*offset[0],y=y,z=z+d_off*offset[1],
                     i=simplices[:,0],j=simplices[:,1],k=simplices[:,2],
                     intensity=(1.0*c)/np.max(1.0*c),
                     name=name,showscale = True,
                     colorscale='Jet',
                     **kwargs)
def calc_cost(node_type, node_count, cpu, gpu, ram, duration, units):
    # do not return anything if no user input
    if node_type == None:
        table_data = []  # empty table
        table_columns = []
        fig = go.Figure(data=[go.Mesh3d(x=[], y=[], z=[])])
        return (None, False, None)
        pass
    # adjust NTF, total RAM, total CPU by node type
    if node_type == 'std':
        node_factor = 1
        tot_cpu = 28
        tot_ram = 128
    if node_type == 'gpu':
        node_factor = 2
        tot_cpu = 28
        tot_ram = 256
    if node_type == 'fat':
        node_factor = 6
        tot_cpu = 56
        tot_ram = 1024
    max_resource = top_resource(alloc_CPU=cpu,
                                cpu_denominator=tot_cpu,
                                alloc_GPU=gpu,
                                gpu_denominator=4,
                                alloc_RAM=ram,
                                ram_denominator=tot_ram)
    su = ((node_count * (max_resource * node_factor)) * 28 * duration)
    # adjust output msg by units selected
    if units == "units_su":
        est_cost = "estimated service units: {}".format(round(su, 2))
    if units == "units_dollars":
        est_cost = "estimated cost in dollars: ${}".format(
            round(su * su_dollar, 2))
    return (est_cost, True, su)
Exemple #16
0
def plot3d(data_x, data_y, data_z, vol):
    """
    This function plots an interactive 3D plot of the determinant as a volume of a 
    parallelopiped
    """
    fig = go.Figure(
        data=[
            go.Mesh3d(
                x=data_x,
                y=data_y,
                z=data_z,
                i=[7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3,
                   2],  # These are needed, numbers from documentation
                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],
                colorscale=[[0, 'darkblue'], [0.5, 'lightskyblue'],
                            [1, 'darkblue']],
                intensity=np.linspace(0, 1, 8, endpoint=True),
                showscale=False,
                opacity=0.6)
        ],
        layout=go.Layout(title="Le volume est: " + str(vol), autosize=True))

    # This prints it
    pyo.iplot(fig, filename='Determinant-Volume')
Exemple #17
0
def mesh_cubes(vox_image: np.ndarray):
    '''Turn a 3d array into a list of plotly.go.Mesh3d objects
    Args:
        vox_image - a numpy.ndarray of binary values
    Returns:
        cubes - a list of cubes as Mesh3d objects
    '''

    # must be a 3-d array
    assert vox_image.ndim == 3

    cubes = []

    # iterate over the entire 3d array
    for i_ind in range(vox_image.shape[0]):
        for j_ind in range(vox_image.shape[1]):
            for k_ind in range(vox_image.shape[2]):
                if vox_image[i_ind, j_ind, k_ind] == 1.:
                    # convert the voxel at this position into a cube
                    cube = _to_cube((i_ind, j_ind, k_ind))
                    # append these vertices and faces as a Mesh3d object
                    cubes.append(
                        go.Mesh3d(x=cube[0],
                                  y=cube[1],
                                  z=cube[2],
                                  i=cube[3],
                                  j=cube[4],
                                  k=cube[5],
                                  hoverinfo='none',
                                  color='blue'))

    return cubes
Exemple #18
0
def add_fault(fault):
    """
    Plot faults (LBU)
    PARAMETERS:
        INPUT: NAME OF FAULT FILE
        OUTPUT: PLOTLY 3D MESH DATA TRACE FOR FAULTS
    """
    if fault:
        #fault path variable
        data = pd.read_csv(
            r'C:\Users\kwonm\PycharmProjects\Project_Texas_CRC-IT\Faults\%s' %
            fault,
            sep=' ',
            header=None,
            skiprows=20)
        x = data[data.columns[0]].values
        y = data[data.columns[1]].values
        z = data[data.columns[2]].values * -1

        trace = [
            go.Mesh3d(x=x, y=y, z=z, color='black', opacity=0.50, name=fault)
        ]
    else:
        trace = []

    return trace
def mesh2plotly(neuron, color, **kwargs):
    """Convert MeshNeuron to plotly object."""
    name = str(getattr(neuron, 'name', neuron.id))

    # Skip empty neurons
    if neuron.n_vertices == 0:
        return []

    try:
        if len(color) == 3:
            c = 'rgb{}'.format(color)
        elif len(color) == 4:
            c = 'rgba{}'.format(color)
    except BaseException:
        c = 'rgb(10,10,10)'

    trace_data = [go.Mesh3d(x=neuron.vertices[:, 0],
                            y=neuron.vertices[:, 1],
                            z=neuron.vertices[:, 2],
                            i=neuron.faces[:, 0],
                            j=neuron.faces[:, 1],
                            k=neuron.faces[:, 2],
                            color=c,
                            name=name,
                            legendgroup=name,
                            showlegend=True,
                            hoverinfo='none')]

    return trace_data
Exemple #20
0
def tri_surface_plot(result, titles, verbose = False, **kwargs):
    # triangulated surface 
    variable = titles['variable']
    results = list(result.items())
    arg0, val0 = results[0]
    arg1, val1 = results[1]
    arg2, val2 = results[2]
    
    trace = go.Mesh3d(
        x=val0,
        y=val1,
        z=val2,
        colorbar_title = variable,
        colorscale=[[0, 'gold'],
                    [0.5, 'mediumturquoise'],
                    [1, 'magenta']],
        # Intensity of each vertex, which will be interpolated and color-coded
        intensity = val2,
        # i, j and k give the vertices of triangles
        i=result[variable][:,0],
        j=result[variable][:,1],
        k=result[variable][:,2],
        name=variable,
        showscale=True)
    
    layout = go.Layout(
        title = titles['title'],
        scene = dict(
            xaxis = dict(title = arg0),
            yaxis = dict(title = arg1),
            zaxis = dict(title = arg2),))
    return [trace], '3d-surface', layout
Exemple #21
0
 def draw3D(self, spaces: List[aecSpace]) -> bool:
     """
     Accepts an aecSpaceGroup object and renders its list of aecSpaces to the plotly display.
     Returns True on success failure.
     Returns False on failure.
     """
     try:
         for space in spaces:
             mesh = space.mesh
             vertices = mesh.vertices
             indices = mesh.indices
             xGroup = [vtx[0] for vtx in vertices]
             yGroup = [vtx[1] for vtx in vertices]
             zGroup = [vtx[2] for vtx in vertices]
             iGroup = [idx[0] for idx in indices]
             jGroup = [idx[1] for idx in indices]
             kGroup = [idx[2] for idx in indices]
             trace = graph.Mesh3d(x=xGroup,
                                  y=yGroup,
                                  z=zGroup,
                                  i=iGroup,
                                  j=jGroup,
                                  k=kGroup)
         plotly.offline.plot([trace])
         return True
     except Exception:
         traceback.print_exc()
         return False
Exemple #22
0
def create_figure(surface, colorscale='Viridis'):
    vertices, faces, colors = surface
    data = go.Data([
        go.Mesh3d(
            x=vertices[:, 0],
            y=vertices[:, 1],
            z=vertices[:, 2],
            colorbar=go.ColorBar(title=colors[0]),
            colorscale=colorscale,
            reversescale=True,
            intensity=colors[1],
            i=faces[:, 0],
            j=faces[:, 1],
            k=faces[:, 2],
            name='y',
            showscale=True,
        )
    ])
    axis_kws = dict(
        title='',
        showaxeslabels=False,
        showbackground=False,
        zeroline=False,
        ticks='',
        showticklabels=False,
        showgrid=False,
    )
    layout = go.Layout(scene=dict(
        xaxis=axis_kws,
        yaxis=axis_kws,
        zaxis=axis_kws,
    ), )
    return go.Figure(data=data, layout=layout)
Exemple #23
0
def _plotly_cube_objects(x, y, z, style='line', color='#1f77b4', opacity=1.0):
    objs = list()
    for f in _plotly_cube_faces():
        xp = [pt[0] + x for pt in f]
        yp = [pt[1] + y for pt in f]
        zp = [pt[2] + z for pt in f]

        #        print(x, y, x)

        surf = Scatter3d(x=xp,
                         y=yp,
                         z=zp,
                         marker=dict(
                             size=4,
                             color='#1f77b4',
                         ),
                         line=dict(color='#1f77b4', width=3))

        objs.append(surf)
        surf = go.Mesh3d(x=xp,
                         y=yp,
                         z=zp,
                         color=color,
                         delaunayaxis='x',
                         opacity=0.5)
        objs.append(surf)
    return objs
Exemple #24
0
def main() :
    platforms = cl.get_platforms()
    devices = platforms[0].get_devices(device_type=cl.device_type.GPU)
    ctx = cl.Context(dev_type=cl.device_type.GPU, properties=[(cl.context_properties.PLATFORM, platforms[0])])
    queue = cl.CommandQueue(ctx, properties=cl.command_queue_properties.PROFILING_ENABLE)
    
    res = 64
    data = ( "dragon_vrip", (res*2, res*2, res) )
    
    mt = MarchingTet(devices[0],ctx,queue)
    mt.loadVolume("./data/{0}_FLT32_{1}_{2}_{3}.raw".format(data[0], *data[1]), data[1])
    mt.isosurface(0.0)
    #print("isosurface extraction complete")
    mt.Profile()

    if 0 : 
        mt.saveAs("./output/{0}".format(data[0]))
    else :
        vtx = mt.getVertices()
        idx = mt.getIndices()
        

        dat_mesh = go.Mesh3d(
            x = vtx[:,0], y = vtx[:,1], z = vtx[:,2],
            i = idx[:,0], j = idx[:,1], k = idx[:,2]
            )
        fig = go.Figure(data=dat_mesh)
        plotly.offline.plot(fig, filename="{0}.html".format(data[0]))
Exemple #25
0
def volcov(robobj, trajectorymat):

    l = len(trajectorymat)

    arr = np.zeros((3, (robobj.jointno - 1) * l + 1))

    arr[0][0] = trajectorymat[0][1][0]
    arr[1][0] = trajectorymat[0][1][1]
    arr[2][0] = trajectorymat[0][1][2]
    i = 0
    m = 1

    while i < l:

        k = 2
        while k < robobj.jointno + 1:
            arr[0][m] = trajectorymat[i][k][0]
            arr[1][m] = trajectorymat[i][k][1]
            arr[2][m] = trajectorymat[i][k][2]
            k = k + 1
            m = m + 1
        i = i + 1

    vol = go.Mesh3d(x=arr[0],
                    y=arr[1],
                    z=arr[2],
                    opacity=0.8,
                    color='rgba(244,22,100,0.6)')

    data = [vol]

    return data
def get_isosurface_data(interp_E, iso_value, XYZE, nb_grid_pts):

    spacing = tuple([(max(XYZE[:, 0]) - min(XYZE[:, 0])) / nb_grid_pts,
                     (max(XYZE[:, 1]) - min(XYZE[:, 1])) / nb_grid_pts,
                     (max(XYZE[:, 2]) - min(XYZE[:, 2])) / nb_grid_pts])
    print(spacing)

    vertices, faces, normals, values = measure.marching_cubes(
        interp_E, iso_value, spacing=spacing, step_size=1)
    print("marching cubes done")
    print(type(vertices))
    print(vertices)
    x, y, z = [vertices[:, i] + min(XYZE[:, i]) for i in range(3)]
    I, J, K = zip(*faces)
    for name, vect in zip(("x", "y", "z"), (x, y, z)):
        if np.isnan(np.dot(vect, vect)):
            print("{} contains NaN values\nPositions : {}".format(
                name, np.argwhere(np.isnan(vect))))

    triangles = go.Mesh3d(x=x,
                          y=y,
                          z=z,
                          i=I,
                          j=J,
                          k=K,
                          name='',
                          # alphahull=5,
                          opacity=0.4,
                          color='#00FFFF'
                          )

    return(triangles)
Exemple #27
0
    def plot_dosemap(self):
        """Plot a map of the absorbed skindose upon the patient phantom.

        This function creates and plots an offline plotly graph of the
        skin dose distribution on the phantom. The colorscale is mapped to the
        absorbed skin dose value. Only available for phantom type: "plane",
        "cylinder" or "human"

        """
        hover_text = [
            f"<b>coordinate:</b><br><b>LAT:</b> {np.around(self.r[ind, 2],2)} cm<br><b>LON:</b> {np.around(self.r[ind, 0])} cm<br><b>VER:</b> {np.around(self.r[ind, 1])} cm<br><b>skin dose: </b><br>{round(self.dose[ind],2)} mGy"
            for ind in range(len(self.r))
        ]

        # create mesh object for the phantom
        phantom_mesh = [
            go.Mesh3d(x=self.r[:, 0],
                      y=self.r[:, 1],
                      z=self.r[:, 2],
                      i=self.ijk[:, 0],
                      j=self.ijk[:, 1],
                      k=self.ijk[:, 2],
                      intensity=self.dose,
                      colorscale="Jet",
                      showscale=True,
                      hoverinfo='text',
                      text=hover_text,
                      name="Human",
                      colorbar=dict(tickfont=dict(color="white"),
                                    title="Skin dose [mGy]",
                                    titlefont=dict(family="Franklin Gothic",
                                                   color="white")))
        ]

        # Layout settings
        layout = go.Layout(
            font=dict(family='Franklin Gothic', color="white", size=18),
            hoverlabel=dict(font=dict(family="Consolas, monospace", size=16)),
            title="""<b>P</b>y<b>S</b>kin<b>D</b>ose [mode: dosemap]""",
            titlefont=dict(family='Franklin Gothic', size=35, color='white'),
            plot_bgcolor='#201f1e',
            paper_bgcolor='#201f1e',
            scene=dict(aspectmode="data",
                       xaxis=dict(title='',
                                  showgrid=False,
                                  showticklabels=False),
                       yaxis=dict(title='',
                                  showgrid=False,
                                  showticklabels=False),
                       zaxis=dict(title='',
                                  showgrid=False,
                                  showticklabels=False)))

        # create figure
        fig = go.Figure(data=phantom_mesh, layout=layout)
        # Execure plot
        ply.plot(fig, filename='dose_map.html')
Exemple #28
0
 def setup_hull(self, hull_points=[[0., 0., 0.], [0., 2.3, 0.], [1.86, 1.86, 0.],
                                   [0., 0., 9.5], [1.19339, 1.19339, 9.5], [0., 1.4757, 9.5]]):
     xp, yp, zp = zip(*hull_points)
     self.hull_mesh = go.Mesh3d(x=xp,
                                y=yp,
                                z=zp,
                                color='#FFB6C1',
                                opacity=0.50,
                                alphahull=0)
    def addTriMesh(self,
                   vertices,
                   faces,
                   alpha=None,
                   show_face=True,
                   face_color=None,
                   face_alpha=None,
                   show_edge=False,
                   edge_color=None,
                   edge_alpha=None,
                   line_width=None,
                   name=None):

        face_alpha = alpha if alpha is not None else face_alpha
        edge_alpha = alpha if alpha is not None else edge_alpha
        self.update_aabb(vertices)

        if show_face:
            obj_face = go.Mesh3d(x=vertices[:, 0],
                                 y=vertices[:, 1],
                                 z=vertices[:, 2],
                                 i=faces[:, 0],
                                 j=faces[:, 1],
                                 k=faces[:, 2])

            if face_color is not None:
                obj_face['color'] = color2string(face_color)
            if face_alpha is not None:
                obj_face['opacity'] = face_alpha

            if alpha is not None:
                obj_face['opacity'] = alpha

            if name is not None:
                obj_face['name'] = name
                obj_face['showlegend'] = True
            else:
                obj_face['showlegend'] = False
            self.graph_objs.append(obj_face)

        import common.shortfunc as sf
        if show_edge:
            e1 = faces[:, [0, 1]]
            e2 = faces[:, [0, 2]]
            e3 = faces[:, [1, 2]]
            es = np.row_stack([e1, e2, e3])
            es = np.sort(es, axis=1)
            es_unique = sf.unique_rows(es)[0]
            p1 = vertices[es_unique[:, 0]]
            p2 = vertices[es_unique[:, 1]]
            self.addLineSegments(p1,
                                 p2,
                                 color=edge_color,
                                 line_width=line_width,
                                 alpha=edge_alpha,
                                 name=name)
def ch4_7_8ex3_cube(name, color):
    return go.Mesh3d(name=name,
                     x=[-1, -1, 1, 1, -1, -1, 1, 1],
                     y=[-1, 1, 1, -1, -1, 1, 1, -1],
                     z=[-1, -1, -1, -1, 1, 1, 1, 1],
                     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],
                     color=color,
                     opacity=0.25)