def main(): prepare(earth_sun_distance * 0.55) earth = vp.sphere(pos=vp.vec(-earth_sun_distance / 2, 0, 0), size=earthR * vec1, color=green) sun = vp.sphere(pos=earth.pos + vp.vec(earth_sun_distance, 0, 0), size=sunR * vec1, color=orange) moon = vp.sphere(pos=earth.pos + vp.vec(0, 0, earth_moon_distance), size=moonR * vec1, color=gray) sunArrow = vp.arrow(pos=sun.pos + vp.vec(0, 0.09 * earth_sun_distance, 0), axis=vp.vec(0, -0.09 * earth_sun_distance + 2 * sunR, 0), shaftwidth=1000, color=orange) earthArrow = vp.arrow( pos=earth.pos + vp.vec(0, 0.09 * earth_sun_distance, 0), axis=vp.vec(0, -0.09 * earth_sun_distance + 2 * earthR, 0), shaftwidth=1000, color=green) moonArrow = vp.arrow( pos=moon.pos - vp.vec(0, 0.09 * earth_sun_distance, 0), axis=vp.vec(0, 0.09 * earth_sun_distance - 2 * moonR, 0), shaftwidth=1000, color=gray)
def plot_arrow(vec, up, color): vp.arrow(axis=vp.vec(-vec[0], -vec[1], -vec[2]), up=vp.vec(-up[0], -up[1], -up[2]), color=vp.vec(color[0], color[1], color[2])) arrow = vp.arrow(axis=vp.vec(vec[0], vec[1], vec[2]), up=vp.vec(up[0], up[1], up[2]), color=vp.vec(color[0], color[1], color[2])) return arrow
def init_small_arm(self): # cal axis 0, 1 axis_0 = self.upper_arm_axis.norm() axis_2 = self.upper_arm_subaxis.norm() axis_1 = axis_0.cross(axis_2).norm() # draw small_arm self.small_arm = cylinder(pos=self.joint_pos, axis=axis_0 * self.small_arm_len, radius=self.small_arm_rad, color=color.cyan, opacity=0.5) self.small_arm.rotate(axis=axis_1, angle=radians(self.small_arm_flex)) # draw xyz self.small_arm_x = arrow(pos=self.joint_pos, axis=axis_0 * self.note_len, color=color.red, radius=self.sketch_rad) self.small_arm_x.rotate(axis=axis_1, angle=radians(self.small_arm_flex)) self.small_arm_y = arrow(pos=self.joint_pos, axis=axis_1 * self.note_len, color=color.green, radius=self.sketch_rad) self.small_arm_z = arrow(pos=self.joint_pos, axis=axis_2 * self.note_len, color=color.blue, radius=self.sketch_rad) self.small_arm_z.rotate(axis=axis_1, angle=radians(self.small_arm_flex))
def _sort_faces(self): """ sort the vertex indices for every face such that they are listed clockwise as seen from the inside since the faces of a convex polyhedron are convex polygons, the center of a face is always inside this polygon. therefor the angles between the vectors connecting each vertex to the face center are unique """ # print(self.faces) # self.show_faces() for face_com, face_indices in zip(self.face_centers, self.faces): if len(face_indices) > 3: start_vec = self.vertices[face_indices[0]].pos - face_com face_normal = vpy.cross( start_vec, self.vertices[face_indices[1]].pos - face_com) if vpy.diff_angle(face_normal, face_com - self.pos) > vpy.pi / 2: face_normal *= -1 if self.debug: vpy.arrow(axis=face_normal / face_normal.mag * 5, pos=face_com, color=vpy.vec(0, 0.8, 0)) def sort_face(vertex_index): """ return the angle between the starting vector and 'self.vertices[vertex_index] - face_com' """ current_vec = self.vertices[vertex_index].pos - face_com angle = vpy.diff_angle(start_vec, current_vec) * \ sign(vpy.dot(vpy.cross(start_vec, current_vec), face_normal)) return angle face_indices.sort(key=sort_face) del (sort_face) # clean up the internal function
def create_scene(self, width, height, vmax): self.__scene = vp.scene self.__scene.width = width self.__scene.height = height self.__scene.range = 15 self.__scene.camera.pos = vp.vector(-30, 0, 10) self.__scene.camera.axis = vp.vector(30, 0, -10) self.__scene.camera.up = vp.vector(0, 0, 1) axis = [vp.vector(1, 0, 0), vp.vector(0, 1, 0), vp.vector(0, 0, 1)] self.__floor = [] w = 100 l = w * 1.7 N = 3 for i in range(N): for j in range(N): b = vp.box(pos=vp.vector(-w + w * i, -l + l * j, -0.5), height=1, width=l, length=w, up=vp.vector(0, 0, 1)) b.texture = 'Resources\\floor.jpg' self.__floor.append(b) for ax in axis: vp.arrow(pos=vp.vector(0, 0, 0), axis=ax, shaftwidth=0.05, color=ax) self.__dt = 0.1 self.__frame = 0 self.__vmax = vmax
def animate_traj(traj): mesh = trimesh.load_mesh('../models/ionsat.stl') bounds = np.array(mesh.bounds) mesh.apply_translation(-(bounds[0] + bounds[1]) / 2) mesh.apply_scale(2) satellite = vp.compound([ vp.triangle(vs=[ vp.vertex(pos=vp.vector(*vertex), normal=vp.vector(*mesh.face_normals[itri])) for vertex in triangle ]) for itri, triangle in enumerate(mesh.triangles) ]) satellite = vp.compound([ satellite, *[ vp.arrow( pos=vp.vector(0, 0, 0), axis=axis, shaftwidth=0.01, color=axis) for axis in (vp.vector(1, 0, 0), vp.vector(0, 1, 0), vp.vector(0, 0, 1)) ] ]) # add frame to the satellite wind = vp.arrow(pos=vp.vector(0, 0, -3), axis=vp.vector(0, 0, 1), shaftwidth=0.01, color=vp.vector(1, 1, 1)) prevQ = None for Q in traj: if prevQ is not None: satellite.rotate(angle=-prevQ.angle(), axis=vp.vector(*prevQ.axis()), origin=vp.vector(0, 0, 0)) satellite.rotate(angle=Q.angle(), axis=vp.vector(*Q.axis()), origin=vp.vector(0, 0, 0)) prevQ = Q vp.rate(25)
def _create_obj(self, entity: Entity, origin: Entity, texture: Optional[str]) -> vpython.compound: """Creates the habitat, and also a new minimap scene and habitat.""" assert texture is not None habitat = self._create_hab(entity, texture) habitat.pos = entity.screen_pos(origin) main_scene = vpython.canvas.get_selected() self._minimap_canvas = vpython.canvas(width=200, height=150, userspin=False, userzoom=False, up=common.DEFAULT_UP, forward=common.DEFAULT_FORWARD) self._minimap_canvas.append_to_caption( # The element styling will be removed at runtime. This just hides # this helptext during startup. "<span class='helptext' style='display: none'>" "This small 'minimap' shows the Habitat's orientation. The red " "arrow represents the Hab's velocity relative to the reference, " "and the gray arrow points to position of the reference." "</span>") self._small_habitat = self._create_hab(entity, texture) self._ref_arrow = vpython.arrow(color=vpython.color.gray(0.5)) self._velocity_arrow = vpython.arrow(color=vpython.color.red) main_scene.select() self._broken: bool = False return habitat
def draw_xyz_arrows(pointer_size: int): """ Draws 3 arrows along X, Y and Z axis. Args: pointer_size(int): Size of the arrowns on the scene. Returns: A list of vpython.arrow objects that represents the arrows on the scene. """ pointers = [] pointer_x = vpython.arrow(pos=vpython.vec(-(pointer_size / 2), 0, 0), axis=vpython.vec(pointer_size, 0, 0), shaftwidth=1, color=vpython.color.red, opacity=0.3) pointer_y = vpython.arrow(pos=vpython.vec(0, -(pointer_size / 2), 0), axis=vpython.vec(0, pointer_size, 0), shaftwidth=1, color=vpython.color.green, opacity=0.3) pointer_z = vpython.arrow(pos=vpython.vec(0, 0, -(pointer_size / 2)), axis=vpython.vec(0, 0, pointer_size), shaftwidth=1, color=vpython.color.yellow, opacity=0.3) pointers.append(pointer_x) pointers.append(pointer_y) pointers.append(pointer_z) return pointers
def create_bodies(): width = 3 height = 2 body1 = vp.box(pos=vp.vector(-5, 0, 0), axis=vp.vector(0, 0, 1), width=width, height=height, arrow=vp.arrow(pos=vp.vector(0, 0, 0), shaftwidth=0.5, color=vp.color.red, visible=False), radius=1/2 * math.sqrt(width**2 + height**2), mass=10, # kg moment_inertia=100, # [kg*m^2] area=10, # [m^2] vel=vp.vector(0, 0, 0), # [m/s] ang_vel=vp.vector(0, 0, 0), # [rad/s^2] theta=vp.radians(20)) # [rad] width = 2 height = 3 body2 = vp.box(pos=vp.vector(3, 0.5, 0), axis=vp.vector(0, 0, 1), width=width, height=height, arrow=vp.arrow(pos=vp.vector(0, 0, 0), shaftwidth=0.5, color=vp.color.blue, visible=False), radius=1/2 * math.sqrt(width**2 + height**2), mass=10, # [kg] moment_inertia=100, # [kg*m^2] area=10, # [m^2] vel=vp.vector(0, 0, 0), # [m/s] ang_vel=vp.vector(0, 0, 0), # [rad/s^2] theta=vp.radians(0)) # [rad] bodies = [body1, body2] for body in bodies: body.vertices = vertices(body) body.rotate(angle=body.theta) return bodies
def update(pad=None, tname=None, fixed=False, color=None): pobj = pdict[pad.name] if fixed: ccolor = vpython.color.orange else: ccolor = vpython.color.white if (color is not None): ccolor = color if (color != v(1.0, 1.0, 1.0)): # wmult = 3 # only useful for plots showing lightning wmult = 1 else: wmult = 1 else: wmult = 1 if (tname is not None) and (tname in pad.inputs): tpos = v(pad.inputs[tname][0].east, pad.inputs[tname][0].north, 0.0) cobj = vpython.arrow(pos=pobj.pos, axis=(tpos - pobj.pos), shaftwidth=ARROWWIDTH * wmult, fixedwidth=True, color=ccolor) pobj.cables[tname] = cobj else: for cable in pobj.cables.values(): cable.visible = False pobj.cables = {} for tname, tdata in pad.inputs.items(): tpos = v(tdata[0].east, tdata[0].north, 0.0) cobj = vpython.arrow(pos=pobj.pos, axis=(tpos - pobj.pos), shaftwidth=ARROWWIDTH * wmult, fixedwidth=True, color=ccolor) pobj.cables[tname] = cobj
def __init__(self, dm, pos=[0, 0, 0]): self.pos = vp.vector(*pos) if dm.dims == [[1], [1]]: self.dm = dm z = self.dm.full()[0][0] self.vsphere = vp.sphere(color=vp.color.blue, opacity=dm.norm()/2,\ pos=self.pos) self.vspin_arrow = vp.arrow(pos=self.pos, shaftwidth=0.1, color=vp.color.magenta,\ axis=vp.vector(z.real, z.imag, 0)) else: self.dm = dm.unit() self.sL, self.sV = dm.eigenstates() self.vsphere = vp.sphere(color=vp.color.blue, opacity=dm.norm()/2,\ pos=self.pos) self.colors = [ vp.vector(*np.random.rand(3)) for i in range(len(self.sV)) ] self.vstars = [[vp.sphere(radius=0.2, pos=self.vsphere.pos+vp.vector(*xyz),\ opacity=self.sL[i].real,\ color=self.colors[i]) for xyz in spin_XYZ(v)]\ for i, v in enumerate(self.sV)] self.j = (dm.shape[0] - 1) / 2 self.vspin_arrow = vp.arrow(pos=self.pos, shaftwidth=0.1, color=vp.color.magenta,\ axis=vp.vector(qt.expect(qt.jmat(self.j, 'x'), self.dm).real,\ qt.expect(qt.jmat(self.j, 'y'), self.dm).real,\ qt.expect(qt.jmat(self.j, 'z'), self.dm).real))
def init_upper_arm(self): # cal axis 0, 1, 2 axis_0 = self.upper_arm_axis.norm() axis_2 = self.upper_arm_subaxis.norm() axis_1 = axis_0.cross(axis_2).norm() # draw upper_arm self.upper_arm = cylinder(pos=self.shoulder_pos, axis=axis_0 * self.upper_arm_len, radius=self.upper_arm_rad, color=color.cyan, opacity=0.5) # draw xyz self.upper_arm_x = arrow(pos=self.shoulder_pos, axis=axis_0 * self.note_len, color=color.red, radius=self.sketch_rad) self.upper_arm_y = arrow(pos=self.shoulder_pos, axis=axis_1 * self.note_len, color=color.green, radius=self.sketch_rad) self.upper_arm_z = arrow(pos=self.shoulder_pos, axis=axis_2 * self.note_len, color=color.blue, radius=self.sketch_rad) # cal joint_pos self.joint_pos = self.shoulder_pos + axis_0 * self.upper_arm_len
def draw_axis(Figures, max_coord): Figures.append( arrow( pos=vector(0,0,0), axis=vector(0,0,max_coord), shaftwidth=0.1)) Figures.append( label( pos=vector(0,0,max_coord/2), text='Z' )) #Z axis Figures.append( arrow( pos=vector(0,0,0), axis=vector(0,max_coord,0), shaftwidth=0.1)) Figures.append( label( pos=vector(0,max_coord/2,0), text='Y' )) #Y axis Figures.append( arrow( pos=vector(0,0,0), axis=vector(max_coord,0,0), shaftwidth=0.1)) Figures.append( label( pos=vector(max_coord/2,0,0), text='X' )) #X axis
def visualInfect(src, dest): global palle palle[dest.plate].color = vp.color.red vp.arrow(pos=vp.vector(src.pos[0], src.pos[1], 0), axis=vp.vector(dest.pos[0] - src.pos[0], dest.pos[1] - src.pos[1], 0), shaftwidth=1, headwidth=2, headlength=3, color=vp.color.green)
def draw_axis(self, layer): position = self.vector_to_vec(layer.position) mArrow = arrow(angle=layer.angle, axis=self.vector_to_vec(layer.axis), color=color.orange, length=40, pos=position) rArrow = arrow(axis=vec(1,0,0), color=color.red, length=50, pos=position, shaftwidth=1) gArrow = arrow(axis=vec(0,1,0), color=color.green, length=50, pos=position, shaftwidth=1) bArrow = arrow(axis=vec(0,0,1), color=color.blue, length=50, pos=position, shaftwidth=1)
def recreate(): global n_qubits global state global energy global unitary global qubits global qubit_colors global vsphere global vstars global vbases global varrows global vfibers global vspin state = qutip.rand_ket(2**n_qubits) energy = qutip.rand_herm(2**n_qubits) unitary = qutip.Qobj( scipy.linalg.expm(-2 * math.pi * im * energy.full() * dt)) qubits = None qubit_colors = [ vpython.vector(random.random(), random.random(), random.random()) for i in range(n_qubits) ] vsphere.visible = False del vsphere vsphere = vpython.sphere(pos=vpython.vector(0,0,0),\ radius=1.0,\ color=vpython.color.blue,\ opacity=0.4) vspin.visible = False del vspin vspin = vpython.arrow(shaftwidth=0.01, headwidth=0.001, headlength=0.001) for vstar in vstars: vstar.visible = False del vstar vstars = [vpython.sphere(radius=0.05,\ color=vpython.color.white,\ opacity=0.8,\ emissive=True) for i in range((2**n_qubits)-1)] for vbase in vbases: vbase.visible = False del vbase vbases = [vpython.sphere(radius=0.1,\ color=qubit_colors[i],\ opacity=0.7,\ emissive=True,\ make_trail=False) for i in range(n_qubits)] for varrow in varrows: varrow.visible = False del varrow varrows = [vpython.arrow(color=qubit_colors[i]) for i in range(n_qubits)] for vfiber in vfibers: vfiber.visible = False del vfiber vfibers = [vpython.curve(pos=[vpython.vector(0,0,0) for i in range(n_points)],\ color=qubit_colors[i]) for i in range(n_qubits)]
def draw_reference_frame_axes(se3_pose, scene): """ Draw x, y, z axes from the given point. Each axis is represented in the objects reference frame. :param se3_pose: SE3 pose representation of the reference frame :type se3_pose: class:`spatialmath.pose3d.SE3` :param scene: Which scene to put the graphics in :type scene: class:`vpython.canvas` :return: Compound object of the 3 axis arrows. :rtype: class:`vpython.compound` """ origin = get_pose_pos(se3_pose) x_axis = get_pose_x_vec(se3_pose) y_axis = get_pose_y_vec(se3_pose) # Create Basic Frame # Draw X Axis x_arrow = arrow(canvas=scene, pos=origin, axis=x_axis_vector, length=0.25, color=color.red) # Draw Y Axis y_arrow = arrow(canvas=scene, pos=origin, axis=y_axis_vector, length=0.25, color=color.green) # Draw Z Axis z_arrow = arrow(canvas=scene, pos=origin, axis=z_axis_vector, length=0.25, color=color.blue) # Combine all to manipulate together # Set origin to where axis converge (instead of the middle of the resulting object bounding box) frame_ref = compound([x_arrow, y_arrow, z_arrow], origin=origin, canvas=scene) # Set frame axes frame_ref.axis = x_axis frame_ref.up = y_axis return frame_ref
def gettile(offsets=None, cpos=None): """Create and return a list of 3D objects making up a single MWA tile. If cpos is given, it's used as the center position for the whole tile (if you want to show multiple tiles). """ if offsets is None: offsets = TILEOFFSETS if cpos is None: cpos = v(0, 0, 0) elif type(cpos) == tuple: cpos = v(cpos) eaxis = vpython.arrow(pos=v(0, 0, 0), axis=v(3, 0, 0), color=color.blue, shaftwidth=0.1, fixedwidth=True, opacity=0.2) naxis = vpython.arrow(pos=v(0, 0, 0), axis=v(0, 3, 0), color=color.blue, shaftwidth=0.1, fixedwidth=True, opacity=0.2) eaxislabel = vpython.text(text='E', pos=v(3, 0, 0.2), height=0.5, depth=0.1, color=color.blue, opacity=0.2) naxislabel = vpython.text(text='N', pos=v(0, 3, 0.2), height=0.5, depth=0.1, color=color.blue, opacity=0.2) gp = vpython.box(pos=v(0, 0, 0) + cpos, axis=v(0, 0, 1), height=5.0, width=5.0, length=0.05, color=color.gray(0.5)) olist = [eaxis, naxis, eaxislabel, naxislabel, gp] letters = 'ABCDEFGHIJKLMNOP' for i in range(16): xy = offsets[i] p = v(xy[0], xy[1], 0) + cpos dlist = getdipole(cpos=p, dlabel=letters[i]) olist += dlist return olist
def draw_arm_anchor(p, a0, a1, radius=0.5, color_=color.white, visible=visible): # draw anchor # a0: main_axis # a1: sub_axis a = [0, 0, 0] a[0] = arrow(pos=p, radius=0.5, axis=a0.norm()*4, color=color.red, visible=visible) a[1] = arrow(pos=p, radius=0.5, axis=a1.norm()*4, color=color.green, visible=visible) a[2] = arrow(pos=p, radius=0.5, axis=a0.cross(a1).norm()*4, color=color.blue, visible=visible) if not color_ == color.white: visible = True s = sphere(pos=p, radius=radius, color=color_, visible=visible) return s, a
def __init__(self, pos=None): if pos is None: pos = vp.vector(0, 0, 0) self.x = vp.arrow(pos=pos, axis=vp.vector(1, 0, 0), shaftwidth=0.1, color=vp.color.red) self.y = vp.arrow(pos=pos, axis=vp.vector(0, 1, 0), shaftwidth=0.1, color=vp.color.green) self.z = vp.arrow(pos=pos, axis=vp.vector(0, 0, 1), shaftwidth=0.1, color=vp.color.blue)
def __init__(self, dm, LV, pos): self.dm = dm self.n = dm.shape[0] self.L, self.V = LV self.projectors = [v * v.dag() for v in self.V] self.pos = pos self.vring = vp.ring(pos=pos,\ axis=vp.vector(0,0,1),\ color=vp.color.red,\ radius=1, thickness=0.1, opacity=0.5) roots_of_unity = [ np.exp(2 * np.pi * 1j * i / self.n) for i in range(self.n) ] directions = [vp.vector(roots_of_unity[i].real,\ roots_of_unity[i].imag,\ 0) for i in range(self.n)] clock_probs = np.array([(self.dm * self.projectors[i]).tr().real for i in range(self.n)]) self.vclock_arrows = [vp.arrow(pos=self.vring.pos,\ axis=directions[i],\ opacity=clock_probs[i],\ color=vp.color.red) for i in range(self.n)] npdirections = [np.array([roots_of_unity[i].real,\ roots_of_unity[i].imag,\ 0]) for i in range(self.n)] expected_time = sum( [npdirections[i] * clock_probs[i] for i in range(self.n)]) self.vexpected_time = vp.sphere(color=vp.color.red, radius=0.1,\ pos=self.pos+vp.vector(*expected_time), opacity=0.5)
def __init__(self, state,\ center=vp.vector(0,0,0),\ radius=1,\ tag=None,\ sphere_color=vp.color.blue,\ star_color=vp.color.white,\ arrow_color=None,\ show_sphere=True,\ show_stars=True,\ show_arrow=True,\ show_tag=True,\ show_tag_on_stars=False): self.n = state.shape[0] self.state = state self.center = center self.radius = radius self.tag = tag self.sphere_color = sphere_color self.star_color = star_color self.arrow_color = self.sphere_color if arrow_color == None else arrow_color self.show_sphere = show_sphere self.show_stars = show_stars self.show_arrow = show_arrow self.show_tag = show_tag self.show_tag_on_stars = show_tag_on_stars self.vsphere = vp.sphere(visible=False) self.varrow = vp.arrow(visible=False) self.vstars = [vp.sphere(visible=False) for i in range(self.n - 1)] self.vtag = vp.text(text="e", visible=False) self.vtags = [ vp.text(text="e", visible=False) for i in range(self.n - 1) ]
def visualize(self): if self.state.value != None: if self.vsphere == None: self.vsphere = vpython.sphere() if self.vspin_axis == None: self.vspin_axis = vpython.arrow() if self.vstars == None: self.vstars = [ vpython.sphere() for i in range(len(self.xyzs.value)) ] if len(self.vstars) < len(self.xyzs.value): self.vstars.extend([ vpython.sphere() for i in range(len(self.xyzs.value) - len(self.vstars)) ]) elif len(self.vstars) > len(self.xyzs.value): while len(self.vstars) > len(self.xyzs.value): self.vstars[-1].visible = False del self.vstars[-1] vpython.rate(100) self.vsphere.pos = vpython.vector(*self.center) self.vsphere.radius = np.linalg.norm(np.array(self.spin_axis())) self.vsphere.color = vpython.color.blue self.vsphere.opacity = 0.4 self.vspin_axis.pos = vpython.vector(*self.center) self.vspin_axis.axis = vpython.vector(*self.spin_axis()) for i in range(len(self.vstars)): self.vstars[ i].pos = self.vsphere.pos + self.vsphere.radius * vpython.vector( *self.xyzs.value[i]) self.vstars[i].radius = 0.1 * self.vsphere.radius self.vstars[i].color = vpython.color.white self.vstars[i].opacity = 0.8
def plot_arrow(vec, up, color): arrow = vp.arrow(axis=vp.vec(vec[0], vec[1], vec[2]), up=vp.vec(up[0], up[1], up[2]), color=vp.vec(color[0], color[1], color[2]), make_trail=True) return arrow
def draw_electrical_field(num_charge): scene = canvas(title='electric field of a list of charges', width=800, height=600, background=color.magenta) # dx = L / num_charge Q = 1e-8 # total charges # dq = 1e-8 / 6 # define charge of electrons dq = Q / num_charge charges = [] space_between = 2 * view_space_length / ( num_charge + 1) # evenly divide space between each electrons for x in arange(-view_space_length + space_between, view_space_length, space_between): q = ElectricBall(pos=vector(x, 0, 0), radius=1, color=color.red, charge=dq) charges.append(q) # creat arrow around electric balls arrows = [] observe_points_dis = 0.5 * view_space_length for x in arange(-1.5 * view_space_length, 1.51 * view_space_length, observe_points_dis): for y in arange(-1.0 * view_space_length, 1.01 * view_space_length, observe_points_dis): for z in arange(-1.0 * view_space_length, 1.01 * view_space_length, observe_points_dis): pointer = arrow(pos=vector(x, y, z), color=color.blue, opacity=0.0) electrical_vector = vector(0, 0, 0) # infinity large arrows will be ignored infinity = False # each arrow is affected by all of the charges for q in charges: direction_vector = pointer.pos - q.pos if direction_vector.mag == 0: infinity = True break # calculate electric field affected by each electric ball E = (k * dq / direction_vector.mag**2) * direction_vector.norm() # sum electric field at the each point electrical_vector += E if infinity: continue # if arrow is not too large, display it if electrical_vector.mag < observe_points_dis: # "rate(30)" tells the program to not do the loop more than 30 times a second. rate(20 * num_charge) pointer.axis = electrical_vector pointer.shaftwidth = 0.1 pointer.opacity = 1.0 arrows.append(pointer)
def __init__(self, color=vpython.color.white, n_fiber_points=50, parent=None): self.color = color self.n_fiber_points = n_fiber_points self.parent = parent self.state = Variable() # 2x2 Density Matrix self.vector = Variable() # spacetime 4-vector self.angles = Variable() # 3 angles of 3-sphere self.state.tie(self.vector, qubit_to_vector) self.vector.tie(self.state, vector_to_qubit) self.vector.tie(self.angles, vector_to_angles) self.angles.tie(self.vector, angles_to_vector) self.vbase = vpython.sphere(color=self.color,\ radius=0.1*self.parent.radius,\ opacity=0.7,\ emissive=True) self.varrow = vpython.arrow(pos=vpython.vector(0,0,0),\ color=self.color,\ shaftwidth = 0.06) self.vfiber = vpython.curve(pos=[vpython.vector(0,0,0) for i in range(self.n_fiber_points)],\ color=self.color)
def create_viz(): global state, G, basis scene = vp.canvas(background=vp.color.white) n = len(state.dims[0]) colors = [vp.color.red, vp.color.green, vp.color.blue] if n == 3 else\ [vp.vector(*np.random.random(3)) for i in range(n)] vpts = {} for i in range(n): pov_state = take_pov(state, 0, i, G, basis=basis) vp.label(text="pov: %d" % i,\ pos=vp.vector(3*i-n,-1.5,0),\ color=colors[i]) vp.sphere(color=colors[i],\ opacity=0.1,\ pos=vp.vector(3*i-n, 0, 0)) for k in range(n): partial = pov_state.ptrace(k) xyz = np.array([qt.expect(qt.sigmax(), partial),\ qt.expect(qt.sigmay(), partial),\ qt.expect(qt.sigmaz(), partial)]) vpts[(i,k)] = vp.arrow(opacity=0.3,\ pos=vp.vector(3*i-n, 0, 0)+0.01*vp.vector(*np.random.randn(3)),\ color=colors[k],\ axis=vp.vector(*xyz),\ visible=not np.isclose(np.linalg.norm(xyz), 0)) return vpts
def __init__(self, state=None,\ center=vpython.vector(0,0,0), radius=1, color=vpython.color.blue, star_color=vpython.color.white): if state == None: self.state = qutip.rand_herm(2) else: self.state = state self.center = center self.radius = radius if color == None: self.color = vpython.vector(random.random(),\ random.random(),\ random.random()) else: self.color = color self.star_color = star_color self.vsphere = vpython.sphere(pos=self.center,\ radius=self.radius,\ color=self.color,\ opacity=0.4) self.varrow = vpython.arrow(pos=self.center,\ color=self.color,\ shaftwidth=0.05,\ emissive=True) self.vbase = vpython.sphere(color=self.star_color,\ radius=0.1*self.radius,\ opacity=0.7,\ emissive=True)
def __init__(self, n, state=None,\ center=vpython.vector(0,0,0),\ radius=1,\ color=vpython.color.blue,\ star_color=vpython.color.white): self.n = n if state == None: self.state = qutip.rand_ket(n) else: self.state = state self.center = center self.radius = radius if color == None: self.color = vpython.vector(random.random(),\ random.random(),\ random.random()) else: self.color = color self.star_color = star_color self.vsphere = vpython.sphere(pos=self.center,\ radius=self.radius,\ color=self.color,\ opacity=0.4) self.varrow = vpython.arrow(pos=self.center,\ color=self.color,\ shaftwidth=0.05,\ emissive=True) self.vstars = [vpython.sphere(radius=0.1*self.radius,\ emissive=True) for i in range(self.n-1)]
def draw_weighted_arrows(self): for col in range(self.cols): for row in range(self.rows): state = (row, col) if self.GI.max_acts.get(state, None): num_arrows = len(self.GI.max_acts[state]) arrow_width = self.arrow_base_width / num_arrows x = col * self.grid_width - self.ctr_x y = -row * self.grid_height + self.ctr_y al = self.arrow_length z = al / 2.0 + self.grid_thick + al / 2.0 for arrow in range(4): the_act = self.GI.actions[arrow] max_acts = self.GI.max_acts.get(state, []) if the_act not in max_acts: self.arrows[col][row][arrow] = '' continue self.arrows[col][row][arrow] = vp.arrow( pos=vp.vector(x, y, z), axis=vp.vector(0.0, 0.0, al), shaftwidth=arrow_width, color=vp.color.red) self.arrows[col][row][arrow].rotate( angle=np.pi / 2, axis=self.axis_list[arrow], origin=vp.vector(x, y, self.grid_thick))
def draw(lattice): lattice.logger.info("Hook6: Display water molecules with VPython.") lattice.logger.info(" Total number of atoms: {0}".format(len(lattice.atoms))) cellmat = lattice.repcell.mat offset = (cellmat[0] + cellmat[1] + cellmat[2]) / 2 # prepare the reverse dict waters = defaultdict(dict) for atom in lattice.atoms: resno, resname, atomname, position, order = atom if "O" in atomname: waters[order]["O"] = position - offset elif "H" in atomname: if "H0" not in waters[order]: waters[order]["H0"] = position - offset else: waters[order]["H1"] = position - offset for order, water in waters.items(): O = water["O"] H0 = water["H0"] H1 = water["H1"] lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.03, pos=vp.vector(*O), color=vp.vector(1,0,0))) lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.02, pos=vp.vector(*H0), color=vp.vector(0,1,1))) lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.02, pos=vp.vector(*H1), color=vp.vector(0,1,1))) lattice.vpobjects['w'].add(vp.cylinder(radius=0.015, pos=vp.vector(*O), axis=vp.vector(*(H0-O)))) lattice.vpobjects['w'].add(vp.cylinder(radius=0.015, pos=vp.vector(*O), axis=vp.vector(*(H1-O)))) lattice.vpobjects['l'].add(vp.label(pos=vp.vector(*O), xoffset=30, text="{0}".format(order), visible=False)) for i,j in lattice.spacegraph.edges(data=False): if i in waters and j in waters: # edge may connect to the dopant O = waters[j]["O"] H0 = waters[i]["H0"] H1 = waters[i]["H1"] d0 = H0 - O d1 = H1 - O rr0 = np.dot(d0,d0) rr1 = np.dot(d1,d1) if rr0 < rr1 and rr0 < 0.27**2: lattice.vpobjects['a'].add(vp.arrow(shaftwidth=0.015, pos=vp.vector(*H0), axis=vp.vector(*(O-H0)), color=vp.vector(1,1,0))) if rr1 < rr0 and rr1 < 0.245**2: lattice.vpobjects['a'].add(vp.arrow(shaftwidth=0.015, pos=vp.vector(*H1), axis=vp.vector(*(O-H1)), color=vp.vector(1,1,0))) lattice.logger.info(" Tips: use keys to draw/hide layers. [3 4 5 6 7 8 a w l]") lattice.logger.info(" Tips: Type ctrl-C twice at the terminal to stop.") lattice.logger.info("Hook6: end.")
def create_vis(self, canvas=None): """ Creates a visualisation. By default, uses a vpython canvas, so imports vpython. Subclass class and change this to change the way visualisations are made. Parameters ---------- canvas: vpython canvas display into which the visualization is drawn """ import vpython #self.scene stores the display into which the system draws if not canvas: if not self.scene: self.scene = vpython.canvas() if canvas: self.scene = canvas # Draw particles if they aren't drawn yet for particle in self.particles: if not particle._visualized: self.spheres.append(vpython.sphere(pos=vector_from(particle.pos), radius=particle.radius, color=vector_from(particle.color), opacity=particle.alpha, display=self.scene)) particle._visualized = True # Draw springs if they aren't drawn yet for spring in self.springs: if not spring._visualized: self.helices.append(vpython.helix(pos=vector_from(spring.particle_1.pos), axis=vector_from(spring.axis), radius=spring.radius, opacity=spring.alpha, color=vector_from(spring.color), display=self.scene)) spring._visualized = True # Draw pointers if they aren't drawn yet for pointer in self.pointers: if not pointer._visualized: self.arrows.append(vpython.arrow(pos=vector_from(pointer.pos), axis=vector_from(pointer.axis), shaftwidth=pointer.shaftwidth, opacity=pointer.alpha, color=vector_from(pointer.color), display=self.scene)) pointer._visualized = True