def make_mesh(cls, mesh: Mesh, offset: Optional[Vec3f] = None, heatmap=False, intensity=None, **kwargs): if heatmap and mesh.is_fourth_dimension(): x, y, z = np.array(mesh.vertices.T) if offset is not None: x += offset[0] y += offset[1] z += offset[2] vx, vy, vz, vv4 = mesh.faces.T intensity = intensity or np.linalg.norm(mesh.vertices[vv4], axis=1) return go.Mesh3d(x=x, y=y, z=z, i=vx, j=vy, k=vz, intensity=intensity, intensitymode="cell", **kwargs) else: mesh = mesh.to_third_dimension(copy=False) x, y, z = np.array(mesh.vertices.T) if offset is not None: x += offset[0] y += offset[1] z += offset[2] vx, vy, vz = mesh.faces.T return go.Mesh3d(x=x, y=y, z=z, i=vx, j=vy, k=vz, **kwargs)
def update_segmentation_slices(selected, annotations): ctx = dash.callback_context # When shape annotations are changed, reset segmentation visualization if (ctx.triggered[0]["prop_id"] == "annotations.data" or annotations is None or annotations.get("x") is None or annotations.get("z") is None): mask = np.zeros_like(med_img) overlay1 = slicer1.create_overlay_data(mask) overlay2 = slicer2.create_overlay_data(mask) return go.Mesh3d(), overlay1, overlay2 elif selected is not None and "range" in selected: if len(selected["points"]) == 0: return dash.no_update v_min, v_max = selected["range"]["x"] t_start = time() # Horizontal mask path = path_to_coords(annotations["z"]["path"]) rr, cc = draw.polygon(path[:, 1] / spacing[1], path[:, 0] / spacing[2]) mask = np.zeros(img.shape[1:]) mask[rr, cc] = 1 mask = ndimage.binary_fill_holes(mask) # top and bottom, the top is a lower number than the bottom because y values # increase moving down the figure top, bottom = sorted( [int(annotations["x"][c] / spacing[0]) for c in ["y0", "y1"]]) img_mask = np.logical_and(med_img > v_min, med_img <= v_max) img_mask[:top] = False img_mask[bottom:] = False img_mask[top:bottom, np.logical_not(mask)] = False img_mask = largest_connected_component(img_mask) # img_mask_color = mask_to_color(img_mask) t_end = time() print("build the mask", t_end - t_start) t_start = time() # Update 3d viz verts, faces, _, _ = measure.marching_cubes(filters.median( img_mask, selem=np.ones((1, 7, 7))), 0.5, step_size=3) t_end = time() print("marching cubes", t_end - t_start) x, y, z = verts.T i, j, k = faces.T trace = go.Mesh3d(x=z, y=y, z=x, color="red", opacity=0.8, i=k, j=j, k=i) overlay1 = slicer1.create_overlay_data(img_mask) overlay2 = slicer2.create_overlay_data(img_mask) # todo: do we need an output to trigger an update? return trace, overlay1, overlay2 else: return (dash.no_update, ) * 3
def getBoxPlotDef(start, dimensions, color): # 8 vertices of a cube x = [ start["x"], start["x"], start["x"] + dimensions["width"], start["x"] + dimensions["width"], start["x"], start["x"], start["x"] + dimensions["width"], start["x"] + dimensions["width"] ] y = [ start["y"], start["y"] + dimensions["height"], start["y"] + dimensions["height"], start["y"], start["y"], start["y"] + dimensions["height"], start["y"] + dimensions["height"], start["y"] ] z = [ start["z"], start["z"], start["z"], start["z"], start["z"] + dimensions["length"], start["z"] + dimensions["length"], start["z"] + dimensions["length"], start["z"] + dimensions["length"] ] boxDef = go.Mesh3d( x=x, y=y, z=z, color=color, colorbar_title='z', # 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], showscale=True) return boxDef
def __init__(self, polyhedron, size=6): self.frames = [] self.size = size vx, vy, vz = np.rot90(polyhedron.vertices)[::-1] i, j, k = [], [], [] for face in polyhedron.faces: for a in range(1, len(face) - 1): i.append(face[0]) j.append(face[a]) k.append(face[a + 1]) self.poly = go.Mesh3d( x=vx, y=vy, z=vz, colorbar_title='z', colorscale=((0, 'grey'), (0.5, 'mediumturquoise'), (1, 'magenta')), intensity=np.random.rand(len(polyhedron.vertices)), i=i, j=j, k=k, opacity=0.4, name='y', showscale=True)
def ecran_refEcran(ecran, rgb_ecran, L, S=50): # Points de départ des flèches oEcran = np.array([0, 0, 0]) # Vecteurs unitaires dirEcran = np.array([0, 0, 1]) coin1 = ecran.pixelToSpace(np.array([0, 0, 1])) coin2 = ecran.pixelToSpace(np.array([ecran.w[0], 0, 1])) coin3 = ecran.pixelToSpace(np.array([0, ecran.w[1], 1])) coin4 = ecran.pixelToSpace(np.array([ecran.w[0], ecran.w[1], 1])) ecran = go.Mesh3d(x=[coin1[0], coin2[0], coin3[0], coin4[0]], y=[coin1[1], coin2[1], coin3[1], coin4[1]], z=[coin1[2], coin2[2], coin3[2], coin4[2]], color='rgb({},{},{})'.format(rgb_ecran[0], rgb_ecran[1], rgb_ecran[2]), opacity=0.1) data = [ecran] data += fleche(oEcran, np.array([1, 0, 0]), rgb=(0, 100, 100), s=1 / S, l=L, name='x') data += fleche(oEcran, np.array([0, 1, 0]), rgb=(0, 200, 200), s=1 / S, l=L, name='y') data += fleche(oEcran, dirEcran, rgb=rgb_ecran, s=1 / S, l=L, name='Ecran') return data
def generate_vertices(self): """Generates vertices from STL file Returns: dict: Dictionary of rendering properties for plotly """ # return super().generate_vertices() p, q, r = self.mesh_vectors.shape # (p, 3, 3) # the array stl_mesh.vectors.reshape(p*q, r) can contain multiple copies of the same vertex; # extract unique vertices from all mesh triangles vertices, ixr = _np.unique(self.mesh_vectors.reshape(p * q, r), return_inverse=True, axis=0) I = _np.take(ixr, [3 * k for k in range(p)]) J = _np.take(ixr, [3 * k + 1 for k in range(p)]) K = _np.take(ixr, [3 * k + 2 for k in range(p)]) x, y, z = vertices.T trace = _go.Mesh3d(x=x, y=y, z=z, i=I, j=J, k=K, color=self.color) # optional parameters to make it look nicer trace.update(flatshading=True, lighting_facenormalsepsilon=0, lighting_ambient=0.7) return trace
def plotly_block_faces( origin, sizes, color=None, colorscale_value=None, colorscale="Cividis", cmin=0, cmax=16.0, ): # 8 vertices of a block x = origin[0] + np.array([0, 0, 1, 1, 0, 0, 1, 1]) * sizes[0] y = origin[1] + np.array([0, 1, 1, 0, 0, 1, 1, 0]) * sizes[1] z = origin[2] + np.array([0, 0, 0, 0, 1, 1, 1, 1]) * sizes[2] color_args = {} if colorscale_value: color_args = { "colorscale": colorscale, "intensity": np.ones((8)) * colorscale_value, "cmin": cmin, "cmax": cmax, } if color: color_args = {"color": color} return go.Mesh3d( x=x, y=z, z=y, # i, j and k give the vertices of the mesh 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], opacity=0.3, **color_args, )
def to_mesh_3d(vertices, faces, colorscale=None): """Convert a list of vertices and faces to plotly mesh.""" # Use the default colorscale if none is specified if colorscale == None: colorscale = [ (0.0, 'rgb(0, 0, 55)'), (1.0, 'rgb(255, 255, 0)'), ] return go.Mesh3d( # 8 vertices of a cube x=vertices[:, 0], y=vertices[:, 1], z=vertices[:, 2], colorbar_title='z', # The intensity is based on the distance intensity=np.linalg.norm(vertices, axis=1), colorscale=colorscale, # i, j and k give the vertices of triangles i=faces[:, 0], j=faces[:, 1], k=faces[:, 2], name='y', showscale=False, flatshading=True, )
def draw_3D(self, backend_info, **kwargs): for isosurf in backend_info["isosurfaces"]: x, y, z = isosurf["vertices"].T I, J, K = isosurf["faces"].T self.add_trace( go.Mesh3d(x=x, y=y, z=z, i=I, j=J, k=K, color=isosurf["color"], opacity=isosurf["opacity"], name=isosurf["name"], showlegend=True, **kwargs)) self.layout.scene = {'aspectmode': 'data'} self.update_layout(**{ f"scene_{k}_title": v for k, v in backend_info["axes_titles"].items() })
def plot_metric(points, tris, data, cmap=None): """ Plot metric data onto surface defined by points, tris arrays. Uses plotly.Mesh3d, see that documentation for more information. Default color map: [ 0 -> gold, 0.5 -> mediumtuquoise, 1-> magenta ] Args: points: px3 array of surface nodes tris: tx3 array of triangle indices into points matrix data: px1 array of data to plot cmap: colour spec for plotly (see default example above) Returns: plotly.Figure object """ assert data.size == points.shape[0], 'data does not match surface size' x, y, z = points.T i, j, k = tris.T if cmap is None: cmap = [[0, 'gold'],[0.5, 'mediumturquoise'],[1, 'magenta']] fig = go.Figure(data=[ go.Mesh3d( x=x,y=y,z=z,i=i,j=j,k=k, colorscale=cmap, # Intensity of each vertex, which will be interpolated and color-coded intensity=data, showscale=True ) ]) return fig
def cube_trace(self, index, opacity=0.4, color=None, colorbar=False): # For a small number of cubes index = np.asarray(index, dtype=int) xyz = self.voxel_positions.at_corner(*index) x = np.array([0, 0, 1, 1, 0, 0, 1, 1]) * self._voxel_sizes[0] y = np.array([0, 1, 1, 0, 0, 1, 1, 0]) * self._voxel_sizes[1] z = np.array([0, 0, 0, 0, 1, 1, 1, 1]) * self._voxel_sizes[2] i = np.array([7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2]) j = np.array([3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3]) k = np.array([0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6]) cube = dict(x=x + xyz[0], y=y + xyz[1], z=z + xyz[2], i=i, j=j, k=k, opacity=opacity, color=color) if colorbar: cmap = matplotlib.cm.get_cmap("magma") c = cmap(self._voxel_data[tuple(index)] / (self._voxel_data.max() or 1)) cube.update(color="rgb({},{},{})".format(c[0], c[1], c[2])) return go.Mesh3d(cube)
def draw_solution(pieces): positions = [] sizes = [] colors = [] sorted_size = [] for each in pieces: positions.append(each[0:3]) sizes.append(each[3:]) sorted_size.append(set(each[3:])) colors = pallete[:len(positions)] color_index = [sorted_size, colors] vertices, I, J, K = triangulate_cube_faces(positions, sizes=sizes) X, Y, Z = vertices.T colors2 = [val for val in colors for _ in range(12)] mesh3d = go.Mesh3d(x=X, y=Y, z=Z, i=I, j=J, k=K, facecolor=colors2, flatshading=True) layout = go.Layout(width=650, height=700, title_text='Truck Loading True Solution', title_x=0.5, scene=dict( camera_eye_x=-1.25, camera_eye_y=1.25, camera_eye_z=1.25) ) fig = go.Figure(data=[mesh3d], layout=layout) fig.show() return color_index
def plot_example(face, pos, color=None, export_flag = False, fig_name = None): """ :param face: array of shape (3, n_face) (face index) :param pos: array coordinates of shape (n_pts, 3) :return: """ assert face.shape[0] == pos.shape[1] == 3 import plotly.graph_objects as go n_face = face.shape[1] fig = go.Figure(data=[ go.Mesh3d( x=pos[:,0].T, y=pos[:,1].T, z=pos[:,2].T, # i, j and k give the vertices of triangles # here we represent the 4 triangles of the tetrahedron surface i=face[0,:], j=face[1,:], k=face[2,:], colorbar_title='z', name='y', colorscale='algae', # facecolor = [(252.0, 141.0, 89.0)] * 3000 + [(255.0, 255.0, 191.0)]*3000 + [(145.0, 191.0, 219.0)]*(n_face - 6000), # np.random.randint(1, 3, size=int(face.shape[1])),# ['b'] * 3000 + ['r']*3000 + ['y']*(n_face - 6000), # np.random.randint(1, 256, size=int(face.shape[1])), facecolor = color, #['blue'] * 3000 + ['green'] * 3000 + ['red']*(n_face-6000) if showscale=True ) ]) fig.show() if export_flag: dir = os.path.join('/home/cai.507/Documents/DeepLearning/local-persistence-with-UF/images_2/') fig.write_image(dir + fig_name )
def plot_escape_locations_cuboid(escp_locs, scale, dist, A=1, B=1, C=1, pos=(0, 0, 0)): XYZ = points_on_cuboid([A, B, C], vol=scale, npts=530) x, y, z = XYZ[:, 0], XYZ[:, 1], XYZ[:, 2] intens = [] for x1, y1, z1 in zip(x, y, z): loc = np.array([x1, y1, z1]) res = np.linalg.norm(escp_locs - loc, axis=1) N = len(res[res < dist]) intens.append(N) intens = np.array(intens) fig = go.Figure(data=[ go.Mesh3d( x=x, y=y, z=z, intensity=intens, alphahull=2, opacity=1, cmin=0) ]) border = np.max([np.max(x), np.max(y), np.max(z)]) * 1.1 fig.update_layout( scene=dict(xaxis=dict( nticks=10, range=[-border, border], ), yaxis=dict(nticks=4, range=[-border, border]), zaxis=dict(nticks=4, range=[-border, border]))) return fig
def add_soi(figure, bd, time, pos=None): if pos is None: pos = bd.orb.get_state_vector(time)[0] fadedColor = fade_color(bd.color) size = 10 phi = np.linspace(0, 2*math.pi, size) theta = np.linspace(-math.pi/2, math.pi/2, size) phi, theta = np.meshgrid(phi, theta) x = bd.soi * np.cos(theta) * np.sin(phi) + pos[0] y = bd.soi * np.cos(theta) * np.cos(phi) + pos[1] z = bd.soi * np.sin(theta) + pos[2] figure.add_trace(go.Mesh3d( x = np.ndarray.flatten(x), y = np.ndarray.flatten(y), z = np.ndarray.flatten(z), alphahull = 0, color = 'rgb'+str(fadedColor), opacity = 0.1, showlegend = False, hoverinfo = 'skip' ))
def get_surface(grid, spacing, origin): x = np.array(grid[0]) y = np.array(grid[1]) z = np.array(grid[2]) x = x * spacing + origin[0] y = y * spacing + origin[1] z = z * spacing + origin[2] mesh = go.Mesh3d({ 'x': x, 'y': y, 'z': z, 'alphahull': 0, 'color' : 'turquoise', 'opacity' : 0.20, 'visible' : False, 'flatshading' : False, "lighting" : surface_materials["glass"], "lightposition" : {"x":100, "y":200, "z":0} }) return mesh
def plot_3d_json( file: str = "data/json/objects.example.json", objects: Optional[dict] = None, ) -> None: if objects is None: with open(file, "r") as f: data = json.load(f) else: data = objects cubes: list = [] for layer_index, layer_value in enumerate(data["layers"]): cubes += [[]] for i, v in enumerate(layer_value["points"]): cubes[layer_index] += [(v["x"], v["y"], 0.0)] cubes[layer_index] += [(v["x"], v["y"], float(layer_value["height"]))] cubes[layer_index].sort(key=lambda _x: (_x[2], _x[1], _x[0])) # fixed list, do not change or cubes will look weird i = [0, 3, 4, 7, 0, 6, 1, 7, 0, 5, 2, 7] j = [1, 2, 5, 6, 2, 4, 3, 5, 4, 1, 6, 3] k = [3, 0, 7, 4, 6, 0, 7, 1, 5, 0, 7, 2] meshes: list = [] for index, cube in enumerate(cubes): x = [i_[0] for i_ in cube] y = [i_[1] for i_ in cube] z = [i_[2] for i_ in cube] meshes += [ go.Mesh3d( # 8 vertices of a cube x=x, y=y, z=z, # color="rgb(255,0,0)", # colorbar_title='z', colorscale=[[0, "gold"], [0.5, "mediumturquoise"], [1, "magenta"]], # Intensity of each vertex, which will be interpolated and color-coded intensity=np.linspace(0, 1, 8, endpoint=True), # i, j and k give the vertices of triangles i=i, j=j, k=k, name="y", showscale=True, ) ] fig = go.Figure(data=meshes) # tight layout fig.update_layout(margin=dict(l=0, r=0, b=0, t=0)) # proportional aspect ratio with data, alternatively cube or manual (see below) fig.update_layout(scene_aspectmode="data") fig.show()
def plot_cont(array): # X Y Z as 1D-array fig = go.Figure(data=[go.Mesh3d(x=array[0], y=array[1], z=array[2], opacity=0.5, color='rgba(186,26,26,1)' )]) # Set axis range fig.update_layout( scene=dict( xaxis=dict(nticks=1, range=[Cycle.lower, Cycle.upper], ticks='outside', tick0=Cycle.lower, dtick=1, tickwidth=0.01), yaxis=dict(nticks=1, range=[duration.lower, duration.upper], ticks='outside', tick0=duration.lower, dtick=1, tickwidth=0.01), zaxis=dict(nticks=1, range=[0, 0.07], ticks='outside', tick0=0, dtick=0.01, tickwidth=0.01), ), ), # Custom name fig.update_layout(scene=dict( xaxis_title='Cycle', yaxis_title='Duration', zaxis_title='Probability'), width=1980, margin=dict(r=20, b=10, l=10, t=10)) fig.show()
def ribbon(scale, seq, enu2ned): left = Point(0, -scale / 2, 0) right = Point(0, scale / 2, 0) # transform origin and wingtips to world frame curPose = seq.get_state_from_index(0).transform ctr = seq.get_state_from_index(0).pos curLeft = curPose.point(left) curRight = curPose.point(right) # init vertex and face lists x = [ctr.x, curLeft.x, curRight.x] y = [ctr.y, curLeft.y, curRight.y] z = [ctr.z, curLeft.z, curRight.z] faces = [] facecolors = [] ctrIndex = 0 for i in range(1, seq.data.shape[0]): # transform origin and wingtips to world frame nextPose = seq.get_state_from_index(i).transform nextctr = seq.get_state_from_index(i).pos nextLeft = nextPose.point(left) nextRight = nextPose.point(right) # update vertex and face lists x.extend([nextctr.x, nextLeft.x, nextRight.x]) y.extend([nextctr.y, nextLeft.y, nextRight.y]) z.extend([nextctr.z, nextLeft.z, nextRight.z]) [roll, pitch, wca, wca_axis] = maneuverRPY(0, seq.get_state_from_index(i), enu2ned) # [roll, pitch, wca, wca_axis] = maneuverRPY(0, enu2ned.quat(seq.get_state_from_index(i))) facecolor = rollColor(roll) # clockwise winding direction faces.append([ctrIndex, ctrIndex + 1, ctrIndex + 4]) facecolors.append(facecolor) faces.append([ctrIndex, ctrIndex + 5, ctrIndex + 2]) facecolors.append(facecolor) faces.append([ctrIndex, ctrIndex + 4, ctrIndex + 5]) facecolors.append(facecolor) ctrIndex += 3 I, J, K = np.array(faces).T return [ go.Mesh3d(name='ribbon', x=x, y=y, z=z, i=I, j=J, k=K, intensitymode="cell", facecolor=facecolors, showlegend=True, hoverinfo="none") ]
def get_geometric_object(v, f, color, color_min, color_max, offset, is_first=False): template_obj = go.Mesh3d(x=v[:, 0] + offset[0], y=v[:, 1] + offset[1], z=v[:, 2] + offset[2], colorbar_title='z', colorscale=[[0, "rgb(255,255,255)"], [0.3, "rgb(255,210,0)"], [0.6, "rgb(200,0,0)"], [1, "rgb(100,0,0)"]], intensity=color, cmin=color_min, cmax=color_max, i=f[0, :], j=f[1, :], k=f[2, :], showscale=is_first, lighting=dict(ambient=0.45, diffuse=0.5, specular=0.5, roughness=0.4), lightposition=dict(x=2, y=2, z=2)) return template_obj
def plot_3d_mesh(mesh): x = mesh.vertices[:, 0] y = mesh.vertices[:, 1] z = mesh.vertices[:, 2] i = mesh.faces[:, 0] j = mesh.faces[:, 1] k = mesh.faces[:, 2] fig = go.Figure(data=[ go.Mesh3d(x=x, y=y, z=z, colorbar_title='z', colorscale=[[0, 'gold'], [0.5, 'mediumturquoise'], [1, 'magenta']], intensity=[0, 0.33, 0.66, 1], i=i, j=j, k=k, name='y', showscale=True) ]) fig.show()
def _surface_plot_meshfunc(meshfunc, colorscale, **kwargs): assert meshfunc.dim() == 2 mesh = meshfunc.mesh() array = meshfunc.array() coord = mesh.coordinates() if len(coord[0, :]) == 2: coord = np.c_[coord, np.zeros(len(coord[:, 0]))] triangle = _get_triangles(mesh) hoverinfo = ["val:" + "%d" % item for item in array] surface = go.Mesh3d( x=coord[:, 0], y=coord[:, 1], z=coord[:, 2], i=triangle[0, :], j=triangle[1, :], k=triangle[2, :], flatshading=True, intensity=array, colorscale=colorscale, lighting=dict(ambient=1), name="", hoverinfo="all", text=hoverinfo, intensitymode="cell", ) return surface
def polydata_mesh_plot(surface, fig, opacity=0.2, color='grey'): """ plot surface mesh from polydata using plotly Input: surface polydata, figure instance """ X = extract_polydata_coords(surface) num_polys = surface.GetNumberOfCells() I = np.zeros(num_polys) J = np.zeros(num_polys) K = np.zeros(num_polys) for i in range(num_polys): cell = surface.GetCell(i) I[i] = cell.GetPointId(0) J[i] = cell.GetPointId(1) K[i] = cell.GetPointId(2) fig.add_trace( go.Mesh3d(x=X[0, :], y=X[1, :], z=X[2, :], i=I, j=J, k=K, opacity=opacity, color=color)) return
def voxels_to_mesh( tensor, color="blue", opacity=0.50, format="Mesh3d", progress_callback=lambda x: None): #xaxis_range, yaxis_range= x, y, z, i, j, k = voxels_to_raw_mesh(tensor, progress_callback) if format == "Mesh3d": data = [ go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, color=color, opacity=opacity) ] return data elif format == "json": data = {} data["color"] = color data["opcacity"] = opacity data["type"] = "mesh3d" data["x"] = list(x.astype("float64")) data["y"] = list(y.astype("float64")) data["z"] = list(z.astype("float64")) data["i"] = list(i.astype("float64")) data["j"] = list(j.astype("float64")) data["k"] = list(k.astype("float64")) data = json.dumps(data, separators=(',', ':')) return data else: raise Exception( "Format not supported. Supported formats are Mesh3d and json")
def make_cylinder_mesh(radius, height, sections=32, position=(0, 0, 0), direction=(1, 0, 0), **kwargs): new_normal = direction / np.linalg.norm(direction) cosx, cosy = new_normal[:2] sinx = np.sqrt(1 - cosx**2) siny = np.sqrt(1 - cosy**2) yaw = [[cosx, -sinx, 0, 0], [sinx, cosx, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] pitch = [[cosy, 0, siny, 0], [0, 1, 0, 0], [-siny, 0, cosy, 0], [0, 0, 0, 1]] transform = np.dot(yaw, pitch) transform[:3, 3] = position cylinder = trimesh.primitives.Cylinder(radius=radius, height=height, sections=sections, transform=transform) x, y, z = cylinder.vertices.T i, j, k = cylinder.faces.T return go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, **kwargs)
def bar3d(x, y, z): layout = go.Layout(scene=dict( camera=dict(up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=-1, y=1.5, z=0.5)), xaxis=dict(ticktext=x, tickvals=0.5 + np.arange(len(x))), yaxis=dict(ticktext=y, tickvals=0.5 + np.arange(len(y))), )) fig = go.Figure(layout=layout) colors = px.colors.qualitative.Plotly for idx in range(len(x)): zi = np.zeros_like(z) zi[idx, :] = z[idx, :] X, Y, Z, I, J, K = __get_plotly_mesh3d(x, y, zi, bargap=0.2) mesh3d = go.Mesh3d(x=X, y=Y, z=Z, i=I, j=J, k=K, color=colors[idx], flatshading=True, hoverinfo='skip') fig.add_trace(mesh3d) return fig
def populate_3d_graph( dummy2_children, show_hide_seg_3d, drawn_shapes_data, last_3d_scene, last_render_id, image_display_top_figure, image_display_side_figure, ): # extract which graph shown and the current render id graph_shown, current_render_id = dummy2_children.split(",") current_render_id = int(current_render_id) start_time = time.time() cbcontext = [p["prop_id"] for p in dash.callback_context.triggered][0] # check that we're not toggling the display of the 3D annotation if cbcontext != "show-hide-seg-3d.children": PRINT("might render 3D, current_id: %d, last_id: %d" % (current_render_id, last_render_id)) if graph_shown != "3d shown" or current_render_id == last_render_id: if current_render_id == last_render_id: PRINT("not rendering 3D because it is up to date") return dash.no_update PRINT("rendering 3D") segs_ndarray = shapes_to_segs( drawn_shapes_data, image_display_top_figure, image_display_side_figure, ).transpose((1, 2, 0)) # image, color images = [ (img.transpose((1, 2, 0))[:, :, ::-1], "grey"), ] if show_hide_seg_3d == "show": images.append((segs_ndarray[:, :, ::-1], "purple")) data = [] for im, color in images: im = image_utils.combine_last_dim(im) try: verts, faces, normals, values = measure.marching_cubes(im, 0, step_size=3) x, y, z = verts.T i, j, k = faces.T data.append( go.Mesh3d(x=x, y=y, z=z, color=color, opacity=0.5, i=i, j=j, k=k)) except RuntimeError: continue fig = go.Figure(data=data) fig.update_layout(**last_3d_scene) end_time = time.time() PRINT("serverside 3D generation took: %f seconds" % (end_time - start_time, )) return (fig, current_render_id)
def figure(self): data = [] color_cycle = cycle(px.colors.qualitative.Dark24) for comp, vertex_coords in self.info.comp_vertices.items(): color = next(color_cycle) vertex_coords = sort_coords(np.array(vertex_coords)) # add surface d = make_triangles(vertex_coords) data.append(go.Mesh3d(**d, alphahull=-1, opacity=0.3, hoverinfo='skip', color=color)) x_ave = sum(d["x"]) / len(vertex_coords) y_ave = sum(d["y"]) / len(vertex_coords) z_ave = sum(d["z"]) / len(vertex_coords) # add formula data.append(go.Scatter3d(x=[x_ave], y=[y_ave], z=[z_ave], text=[clean_formula(comp)], mode="text", textposition="middle center", textfont=dict(color=color, size=24), hoverinfo='skip')) if self.info.cpd.target: x, y, z, text = [], [], [], [] for label, cp in self.info.cpd.target_vertices.items(): x.append(cp[0]) y.append(cp[1]) z.append(cp[2]) text.append(label) data.append(go.Scatter3d(x=x, y=y, z=z, text=text, mode='markers+text', textfont=dict(size=24), hovertemplate="<b>label %{text}</b><br>" "energy (%{x:.2f}, %{y:.2f})")) fig = go.Figure(data=data) # fig.update_traces(marker_size=15) _range = [self.info.min_range * 1.001, -self.info.min_range * 0.1] vertex_elements = self.info.cpd.vertex_elements elements_str = [str(elem) for elem in self.info.cpd.vertex_elements] fig.update_layout( title=f"Chemical potential diagram of {'-'.join(elements_str)}", scene=dict( xaxis_title=f"{vertex_elements[0]} (eV)", yaxis_title=f"{vertex_elements[1]} (eV)", zaxis_title=f"{vertex_elements[2]} (eV)", xaxis_range=_range, yaxis_range=_range, zaxis_range=_range, ), width=700, height=700, font_size=15, title_font_size=30, showlegend=False) return fig
def read_sigma_accuracy(path): X, Y, Z = [], [], [] with open(path, 'r') as file: f_lines = file.readlines() for x in f_lines: X.append(float(x.strip().split(',')[0])) Y.append(float(x.strip().split(',')[1])) Z.append(float(x.strip().split(',')[2])) trace_surface = go.Mesh3d( x=X, y=Y, z=Z, name='X-to-Sigma-Ratio and Y-to-Sigma-Ratio to Accuracy', opacity=0.5) fig = go.Figure(data=trace_surface) fig.update_layout( title='X-to-Sigma-Ratio and Y-to-Sigma-Ratio to Accuracy', autosize=True, scene=dict(xaxis_title='Sigma to X', yaxis_title='Sigma to Y', zaxis_title='Accuracy'), width=700, height=700, showlegend=True, margin=dict(l=50, r=50, b=65, t=90)) py.offline.plot( fig, filename= '11-03-2019-X-to-Sigma-Ratio and Y-to-Sigma-Ratio to Accuracy-0-3-sigma.html' )
def makeBox(mag=(0, 0, 1), dim=(10, 10, 10), pos=(0, 0, 0), angle=0, axis=(0, 0, 1), cst=0.1, showlegend=True, **kwargs): box = go.Mesh3d(i=np.array([7, 0, 0, 0, 4, 4, 2, 6, 4, 0, 3, 7]), j=np.array([3, 4, 1, 2, 5, 6, 5, 5, 0, 1, 2, 2]), k=np.array([0, 7, 2, 3, 6, 7, 1, 2, 5, 5, 7, 6]), showscale=False, showlegend=showlegend, name=f'''box ({dim[0]:.1f}x{dim[1]:.1f}x{dim[2]:.1f}mm)''') x = np.array([-1, -1, 1, 1, -1, -1, 1, 1]) * 0.5 * dim[0] + pos[0] y = np.array([-1, 1, 1, -1, -1, 1, 1, -1]) * 0.5 * dim[1] + pos[1] z = np.array([-1, -1, -1, -1, 1, 1, 1, 1]) * 0.5 * dim[2] + pos[2] points = np.array([x, y, z]) if cst is not False: box.colorscale = _getColorscale(cst) box.intensity = _getIntensity(points=(x, y, z), mag=mag, pos=pos) if angle != 0: points = np.array([ angleAxisRotation(p, angle, axis, anchor=pos) for p in points.T ]).T box.x, box.y, box.z = points box.update(**kwargs) return box