Ejemplo n.º 1
0
    def Plot(self, Source=True, Axes=True, Show=True):

        Figure0 = mlab.figure(figure='EPhi',
                             size=(600,300),
                             bgcolor=(1,1,1),
                             fgcolor=(0.,0.,0.))

        visual.set_viewer(Figure0)
        self.EPhi._Plot(Figure=Figure0, Source=Source, Axes=Axes, label='EPhi')
        if Source:
            self.Parent.Source._Plot(Figure=Figure0, Origin=(0,+3,-4))
            self.Parent.Source._Plot(Figure=Figure0, Origin=(0,-3,-4))

        ConfigScene(Figure0)


        Figure1 = mlab.figure(figure='ETheta',
                             size=(600,300),
                             bgcolor=(1,1,1),
                             fgcolor=(0.,0.,0.))

        visual.set_viewer(Figure1)
        self.ETheta._Plot(Figure=Figure1, Source=Source, Axes=Axes, label='ETheta')
        if Source:
            self.Parent.Source._Plot(Figure=Figure1, Origin=(0,+3,-4))
            self.Parent.Source._Plot(Figure=Figure1, Origin=(0,-3,-4))

        ConfigScene(Figure1)


        if Show:
            mlab.show()
        else:
            return Figure0, Figure1
Ejemplo n.º 2
0
 def init_scene(self):
     # init wind field object, mayavi
     self.func_wind_field_obj_init()
     # init odor source pos object, visual
     visual.set_viewer(
         self.scene)  # tell visual to use this scene as the viewer
     op = Config.get_odor_source_pos()  # get init odor source pos
     self.odor_source = visual.box(pos=(op[0], op[1], op[2]/2.0), length = 0.1, \
             height = 0.1, width = op[2], color = (0x05/255.0, 0x5f/255.0,0x58/255.0), )
     # init robot drawing obj, visual
     rp = Config.get_robot_init_pos()
     self.func_init_robot_shape(rp)
     # init wind vane obj, visual, indicating mean wind vector
     self.func_init_wind_vane()
     # axes and outlines
     self.func_init_axes_outline()
     # camera view
     self.scene.mlab.view(*Config.get_camera_view())
     # check if TCP/IP address/port is successfully bind
     if self.objs_comm_process['sim_state'][1] == 1:
         if self.enum_comm_mode == 'local':
             self.textbox_sim_state_display = 'Listenting to localhost:60000'
         elif self.enum_comm_mode == 'distributed':
             self.textbox_sim_state_display = 'Listenting to ' \
                     + self.text_comm_address + ':' + self.text_comm_port
         else:
             self.textbox_sim_state_display = "Listenting to what? I don't know"
     elif self.objs_comm_process['sim_state'][1] == -1:
         if self.enum_comm_mode == 'local':
             self.textbox_sim_state_display = 'Error: Cannot bind localhost:60000'
         elif self.enum_comm_mode == 'distributed':
             self.textbox_sim_state_display = 'Error: Cannot bind ' \
                     + self.text_comm_address + ':' + self.text_comm_port
         else:
             self.textbox_sim_state_display = "Error: Can't bind what? I forgot"
Ejemplo n.º 3
0
    def Plot(self, Source=True, Axes=True, Show=True):
        Figure = mlab.figure(figure='Stokes parameter', size=(600,300), bgcolor=(1,1,1), fgcolor=(0.,0.,0.))
        visual.set_viewer(Figure)

        self.I._Plot( Source=Source, Axes=Axes, Figure=Figure, Origin=(0,0,0),  ColorBar=True, label='I', ColorMap='seismic' )
        self.Parent.Source._Plot(Figure=Figure, Origin=(0,0,-4))

        self.Q._Plot( Source=Source, Axes=Axes, Figure=Figure, Origin=(0,4,0),  ColorBar=True, label='Q', ColorMap='seismic' )
        self.Parent.Source._Plot(Figure=Figure, Origin=(0,4,-4))

        self.U._Plot( Source=Source, Axes=Axes, Figure=Figure, Origin=(0,8,0),  ColorBar=True, label='U', ColorMap='seismic' )
        self.Parent.Source._Plot(Figure=Figure, Origin=(0,8,-4))

        self.V._Plot( Source=Source, Axes=Axes, Figure=Figure, Origin=(0,12,0), ColorBar=True, label='V', ColorMap='seismic' )
        self.Parent.Source._Plot(Figure=Figure, Origin=(0,12,-4))

        self.I.Image.module_manager.scalar_lut_manager.data_range = (-1, 1)
        self.Q.Image.module_manager.scalar_lut_manager.data_range = (-1, 1)
        self.U.Image.module_manager.scalar_lut_manager.data_range = (-1, 1)
        self.V.Image.module_manager.scalar_lut_manager.data_range = (-1, 1)

        if Show:
            mlab.show()
        else:
            return Figure
Ejemplo n.º 4
0
    def __init__(self,
                 Ellipsity,
                 Figure,
                 Num=100,
                 Origin=(0, 0, 0),
                 Rotation=None,
                 Label='E'):
        self.Num = Num
        self.Label = Label
        angle = np.linspace(0, 2 * np.pi, self.Num)

        self.x = (np.cos(angle)).squeeze()
        self.y = (np.sin(angle) * sin(Ellipsity) * np.sqrt(2)).squeeze()
        self.z = 0 * self.x

        self.axis0 = [0, +1, 0]
        self.axis1 = [0, -1, 0]

        self.Figure = Figure
        visual.set_viewer(Figure)

        if Rotation is not None:
            self.Rotate(Rotation)

        self.x += Origin[0]
        self.y += Origin[1]
        self.z += Origin[2]

        self.Idx = np.argmax(self.x)
Ejemplo n.º 5
0
def UnstructuredAbs(Mesh, Scalar=None, Name='', Figure=None):

    Figure = mlab.figure(figure=None, size=(600, 300))
    visual.set_viewer(Figure)

    if Scalar is None: Scalar = Mesh.Phi.Radian * 0 + 1

    x, y, z = Sp2Cart(Scalar.flatten(), Mesh.Phi.Radian.flatten(),
                      Mesh.Theta.Radian.flatten())

    AddUnitAxes(Figure=Figure, Scale=1., Origin=(0, 0, -1.5))

    AddUnitSphere(Num=50, Radius=1, Origin=(0, 0, 0), Figure=Figure)

    im0 = mlab.points3d(x,
                        y,
                        z,
                        abs(Scalar),
                        mode='sphere',
                        scale_mode='none',
                        colormap=CMAP)

    mlab.colorbar(object=im0,
                  label_fmt="%.0e",
                  nb_labels=5,
                  title='Real part',
                  orientation='horizontal')
Ejemplo n.º 6
0
	def _draw(self):
		"""Update the Mayavi objects with new particle information.
		This is called periodically in the GUI thread"""
		if self.data is None:
			return
		
		assert isinstance(threading.current_thread(), threading._MainThread)

		f = mlab.gcf()
		visual.set_viewer(f)

		coords, types, radii, N_changed, bonds, Nbonds_changed, boxl, box_changed = self.data
		self.data = None

		if box_changed or not self.running:
			self.box.set(bounds=(0,boxl[0], 0,boxl[1], 0,boxl[2]))

		if not N_changed:
			self.points.mlab_source.set(x=coords[:,0]%boxl[0], y=coords[:,1]%boxl[1], z=coords[:,2]%boxl[2], u=radii, v=radii, w=radii, scalars=types)
		else:
			self.points.mlab_source.reset(x=coords[:,0]%boxl[0], y=coords[:,1]%boxl[1], z=coords[:,2]%boxl[2], u=radii, v=radii, w=radii, scalars=types)
		if not self.running:
			f.scene.reset_zoom()
			self.running = True

		if not Nbonds_changed:
			if bonds.shape[0] > 0:
				self.arrows.mlab_source.set  (x=bonds[:,0], y=bonds[:,1], z=bonds[:,2], u=bonds[:,3], v=bonds[:,4], w=bonds[:,5])
		else:
			self.arrows.mlab_source.reset(x=bonds[:,0], y=bonds[:,1], z=bonds[:,2], u=bonds[:,3], v=bonds[:,4], w=bonds[:,5], scalars=bonds[:,6])
Ejemplo n.º 7
0
    def Plot(self, Source=True, Axes=True, Figure=None, Origin=(0,0,0), ColorBar=True, label=''):

        visual.set_viewer(Figure)

        self._Plot(Source=Source, Axes=Axes, Figure=Figure, Origin=Origin, ColorBar=ColorBar, label=label)

        mlab.show()
Ejemplo n.º 8
0
def UnstructuredAmplitude(Mesh, Scalar = None, Name = '', Source=True, Axes=True):
    Figure = mlab.figure(figure=None, size=(600,300), bgcolor=(1,1,1), fgcolor=(0,0,0))

    visual.set_viewer(Figure)
    UnstructuredMesh(Scalar, Mesh.X, Mesh.Y, Mesh.Z, Source, Axes, (0,2,0), Figure, Name='Etheta', Orientation='vertical')

    mlab.show()
Ejemplo n.º 9
0
    def Plot(self, Figure=None, Origin=(0, 0, -2)):

        Figure = self._Plot(Figure=Figure)

        visual.set_viewer(Figure)

        ConfigScene(Figure)

        mlab.show()
Ejemplo n.º 10
0
    def __init__(self,
                 wp_list,
                 np_file='/tmp/magnetic_ground_truth.np',
                 width=800,
                 height=600):
        self.debug = True

        self.width = width
        self.height = height

        self.wp_list = wp_list

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        v = mlab.view(135, 180)

        self.balls = []
        self.trajectories = []

        colors = list(RoiSimulator.color_codes)
        color_black = colors.pop(0)
        color_red = colors.pop(0)

        wp_curve = visual.curve(color=color_red,
                                radius=RoiSimulator.curve_radius)
        hist_pos = []

        for i in xrange(len(self.wp_list)):
            ball = visual.sphere(color=color_black,
                                 radius=RoiSimulator.ball_radius)
            wp = self.wp_list[i]

            ball.x = wp[1]
            ball.y = wp[0]
            ball.z = wp[2]

            self.balls.append(ball)

            arr = visual.vector(float(wp[1]), float(wp[0]), float(wp[2]))
            hist_pos.append(arr)

        wp_curve.extend(hist_pos)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        z = np.loadtxt(np_file)
        z *= 255.0 / z.max()

        # HARDCODED
        # Todo: REMOVE THIS CODE ON THE FINAL RELEASE
        for xx in xrange(0, 200):
            for yy in xrange(400, 600):
                z[yy][xx] = 0
        mlab.surf(x, y, z)
Ejemplo n.º 11
0
    def __init__(self,
                 hex_list,
                 np_file='/tmp/magnetic_ground_truth.np',
                 robot_height=40,
                 width=800,
                 height=600,
                 start_point=(0, 0, 0)):
        self.debug = False
        self.animator = None
        self.movement_mode = 0
        self.start_point = start_point
        self.robot_height = robot_height

        self.width = width
        self.height = height

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        v = mlab.view(270, 180)
        #print v

        engine = mlab.get_engine()
        s = engine.current_scene
        s.scene.interactor.add_observer('KeyPressEvent',
                                        self.keypress_callback)

        self.robots = []

        colors = list(PathRobustSimulator.color_codes)

        for key, local_hex_list in sorted(hex_list['internal_routes'].items()):
            color = colors.pop(0)

            ball = visual.sphere(color=color,
                                 radius=PathRobustSimulator.ball_radius)
            ball.x = self.start_point[0]
            ball.y = self.start_point[1]
            ball.z = self.start_point[2]

            curve = visual.curve(color=color,
                                 radius=PathRobustSimulator.curve_radius)

            r_ball = RobotBall(key, local_hex_list,
                               hex_list['external_routes'][key], ball, curve)
            self.robots.append(r_ball)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        z = np.loadtxt(np_file)
        z *= 255.0 / z.max()
        mlab.surf(x, y, z)

        self.master_cmd = MasterCommand(self.robots)
    def __init__(self, hex_list, np_file='/tmp/magnetic_ground_truth.np', robot_height=40, width=800, height=600,
                 start_point=(0, 0, 0), message='experiment default message...'):
        self.debug = False
        self.animator = None
        self.movement_mode = 0
        self.start_point = start_point
        self.robot_height = robot_height
        self.message = message

        self.start_time = int(time.time() * 1000)

        self.width = width
        self.height = height

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        v = mlab.view(270, 180)
        #print v

        engine = mlab.get_engine()
        self.s = engine.current_scene
        self.s.scene.interactor.add_observer('KeyPressEvent', self.keypress_callback)

        self.robots = []

        colors = list(PathBatterySimulator.color_codes)

        for key, local_hex_list in sorted(hex_list['internal_routes'].items()):
            color = colors.pop(0)

            ball = visual.sphere(color=color, radius=PathBatterySimulator.ball_radius)
            ball.x = self.start_point[0]
            ball.y = self.start_point[1]
            ball.z = self.start_point[2]

            r, g, b = color
            rt = r + (0.25 * (1 - r))
            gt = g + (0.25 * (1 - g))
            bt = b + (0.25 * (1 - b))
            curve_color = (rt, gt, bt)

            curve = visual.curve(color=curve_color, radius=PathBatterySimulator.curve_radius)

            r_ball = RobotBall(key, local_hex_list, hex_list['external_routes'][key], ball, curve)
            self.robots.append(r_ball)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        z = np.loadtxt(np_file)
        z *= 255.0/z.max()
        mlab.surf(x, y, z)

        self.master_cmd = MasterCommand(self.robots)
Ejemplo n.º 13
0
    def __init__(self, width, height, bgcolor=None):
        figure = mlab.figure(size=(width, height), bgcolor=bgcolor)
        visual.set_viewer(figure)

        self.width = width
        self.height = height

        self.camera = Camera()

        self.frame_callbacks = [self.on_frame]
        self.obj_animations = dict()
Ejemplo n.º 14
0
def PlotConfiguration(Detector, Scatterer):
    """Still experimental"""
    from tvtk.tools import visual
    from tvtk.api import tvtk
    from numpy import sqrt

    Figure = mlab.figure(figure='Optical configuration', size=(600, 300))
    visual.set_viewer(Figure)

    Origin = [0, 0, 0]

    AddUnitSphere(Num=50, Radius=0.1, Origin=(0, 0, 0), Figure=Figure)

    AddUnitAxes(Scale=3, Origin=(0, 0, 0), Figure=Figure)

    AddUnitAxes(Scale=0.8,
                Origin=(0, 0, -2),
                Figure=Figure,
                Label=False,
                ScaleTube=0.5)

    ElectricFieldArrow(Figure=Figure, Origin=(0, 0, -2), Pol=0, Scale=1)

    Ydir = np.sin(Detector.PhiOffset)
    Xdir = np.sin(Detector.GammaOffset)

    Direction = np.array([Xdir, Ydir, -1])

    dist = sqrt(Direction[0]**2 + Direction[1]**2 + Direction[2]**2)

    Height = 2.0

    Origin = Origin - Direction / dist * Height / 2.5

    SPF = Scatterer.SPF(100)
    SPF['SPF'] = SPF['SPF'] / np.max(SPF['SPF']) * 2

    x, y, z = Sp2Cart(SPF['SPF'], SPF['Phi'], SPF['Theta'])

    im = mlab.mesh(x, y, z, colormap='viridis', figure=Figure)

    PlotCone(Origin=Origin,
             Radius=Detector.NA * Height,
             Height=Height,
             Resolution=100,
             Figure=fig,
             Direction=Direction)

    mlab.view(azimuth=0, elevation=180, distance=None)
Ejemplo n.º 15
0
    def __init__(self,
                 wp_list,
                 hex_list,
                 robot_height=40,
                 np_file='/tmp/magnetic_ground_truth.np',
                 width=800,
                 height=600,
                 start_point=(0, 0, 0)):
        self.debug = True
        self.movement_mode = 0
        self.start_point = start_point
        self.robot_height = robot_height

        self.width = width
        self.height = height

        self.wp_list = wp_list
        self.index_list = []
        self.history = []
        self.last_positions = []

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        self.balls = []
        self.trajectories = []

        colors = list(PathSimulator.color_codes)

        for i in xrange(len(self.wp_list)):
            color = colors.pop(0)
            ball = visual.sphere(color=color, radius=PathSimulator.ball_radius)
            ball.x = self.start_point[0]
            ball.y = self.start_point[1]
            ball.z = self.start_point[2]

            self.balls.append(ball)
            self.trajectories.append(
                visual.curve(color=color, radius=PathSimulator.curve_radius))
            self.index_list.append(0)
            self.history.append([])
            self.last_positions.append(self.start_point)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        self.z = np.loadtxt(np_file)
        self.z *= 255.0 / self.z.max()
        mlab.surf(x, y, self.z)
Ejemplo n.º 16
0
 def _plot_mayavi(self, viewer=None):
     from tvtk.tools import visual
     visual.set_viewer(viewer)
     trans, rot, zoom, shear = decompose44(self.pos4d)
     # turn into valid color tuple
     self.display['color'] = get_color(self.display)
     # setting color here is more global than in the next line
     # because this automatically changes the diffuse, ambient, etc. color, too.
     b = visual.box(pos=trans, size=tuple(np.abs(zoom) * 2), axis=np.dot([1.,0.,0.], rot),
                    color=self.display['color'], viewer=viewer)
     # No safety net here like for color converting to a tuple.
     # If the advnaced properties are set you are on your own.
     for n in b.property.trait_names():
         if n in self.display:
             setattr(b.property, n, self.display[n])
Ejemplo n.º 17
0
    def Plot(self, Source=True, Axes=True, Show=True):
        Figure = mlab.figure(figure='Scattering phase function',
                             size=(600,300),
                             bgcolor=(1,1,1),
                             fgcolor=(0.,0.,0.))

        visual.set_viewer(Figure)

        self.SPF._Plot(Figure=Figure, Source=Source, Axes=Axes)

        if Source:
            self.Parent.Source._Plot(Figure=Figure)

        if Show:
            mlab.show()
        else:
            return Figure
    def create_unicycle(self):
        visual.set_viewer(self.scene)
        self.wheel_top = visual.box(color = (0.2, 0.5, 0.5), pos = (0, 1.0, 0), length = 1.6, width = 1.6, height = 0.04)
        self.spring = visual.helix(coils = 8, axis = (0.0, 1.0, 0.0), color = (0.8, 0.2, 0.8), pos = (0.14, 1.0, 0), radius = 0.1, length = 0.5)
        self.car = visual.box(color = (0.2, 0.2, 0.8), pos = (0.0, 1.7, 0.0), length = 0.6, height = 0.4, width = 0.6)
        self.dash_top = visual.cylinder(axis = (0.0, -1.0, 0.0), color = (0.8, 0.8, 0.2), pos = (-0.14, 1.7, 0.0), radius = 0.1, length = 0.3)
        self.dash_bottom = visual.cylinder(axis = (0.0, 1.0, 0.0), color = (0.8, 0.8, 0.2), pos = (-0.14, 1.0, 0.0), radius = 0.05, length = 0.6)

        self.scene.camera.azimuth(45)
        self.scene.camera.elevation(20)
 
        self.recompute_char_eq()
        self.update_chq_data()
        
        self.tdata = self.state_buf[:,0]
        self.ydata = self.state_buf[:,1]

        self._run_fired()
Ejemplo n.º 19
0
 def _plot_mayavi(self, viewer=None):
     from tvtk.tools import visual
     visual.set_viewer(viewer)
     trans, rot, zoom, shear = decompose44(self.pos4d)
     # turn into valid color tuple
     self.display['color'] = get_color(self.display)
     # setting color here is more global than in the next line
     # because this automatically changes the diffuse, ambient, etc. color, too.
     b = visual.box(pos=trans,
                    size=tuple(np.abs(zoom) * 2),
                    axis=np.dot([1., 0., 0.], rot),
                    color=self.display['color'],
                    viewer=viewer)
     # No safety net here like for color converting to a tuple.
     # If the advnaced properties are set you are on your own.
     for n in b.property.trait_names():
         if n in self.display:
             setattr(b.property, n, self.display[n])
Ejemplo n.º 20
0
def CircularFieldArrow(Figure, Origin, Polarization, Scale=0.5):
    Vec = [sin(Polarization.Radian), -cos(Polarization.Radian), 1]

    visual.set_viewer(Figure)

    ar0 = visual.ring(color=RED, thickness=0.03)
    ar0.pos = np.asarray(Origin) / Scale

    ar0.actor.scale = Vec
    ar0.axis = [0, 0, 1]

    mlab.text3d(x=Vec[0] + Origin[0],
                y=Vec[1] + Origin[1],
                z=Vec[2] + Origin[2] - 1,
                text='E',
                line_width=0.1,
                figure=Figure,
                scale=0.25,
                color=BLACK)
Ejemplo n.º 21
0
def StructuredAmplitude(Scalar,
                        Phi,
                        Theta,
                        Name='',
                        Polarization=None,
                        Source=None):

    Figure = mlab.figure(figure=None, size=(600, 300))
    visual.set_viewer(Figure)

    x, y, z = Sp2Cart(Phi * 0 + 1, Phi, Theta)

    dic = {
        'Real': (-3, np.real, 'horizontal'),
        'Imaginary': (+3, np.imag, 'vertical')
    }

    for keys, (val, func, ax) in dic.items():
        Origin = (val, 0, 0)

        AddUnitAxes(Figure=Figure, Origin=Origin, Scale=2)

        mlab.text3d(Origin[0], Origin[1], 5, keys, scale=0.5)

        AddSource(Figure, (val, 0, -3), Polarization, Scale=1.1)

        im0 = mlab.points3d(x + val,
                            y,
                            z,
                            func(Scalar),
                            mode='sphere',
                            scale_mode='none',
                            colormap=CMAP,
                            opacity=1)

        mlab.colorbar(object=im0,
                      label_fmt="%.0e",
                      nb_labels=5,
                      title=f'{keys} part',
                      orientation=ax)

    return Figure
    def __init__(self, wp_list, np_file='/tmp/magnetic_ground_truth.np', width=800, height=600):
        self.debug = True

        self.width = width
        self.height = height

        self.wp_list = wp_list

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        self.balls = []
        self.trajectories = []

        colors = list(RoiSimulator.color_codes)
        color_black = colors.pop(0)
        color_red = colors.pop(0)

        wp_curve = visual.curve(color=color_red, radius=RoiSimulator.curve_radius)
        hist_pos = []

        for i in xrange(len(self.wp_list)):
            ball = visual.sphere(color=color_black, radius=RoiSimulator.ball_radius)
            wp = self.wp_list[i]

            ball.x = wp[1]
            ball.y = wp[0]
            ball.z = wp[2]

            self.balls.append(ball)

            arr = visual.vector(float(wp[1]), float(wp[0]), float(wp[2]))
            hist_pos.append(arr)

        wp_curve.extend(hist_pos)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        z = np.loadtxt(np_file)
        z *= 255.0/z.max()
        mlab.surf(x, y, z)
Ejemplo n.º 23
0
def UnstructuredAmplitude(Mesh, Scalar=None, Name=''):
    Figure = mlab.figure(figure=None, size=(600, 300))

    visual.set_viewer(Figure)

    if Scalar is None: Scalar = Mesh.Phi.Radian.flatten() * 0 + 1

    x, y, z = Sp2Cart(Scalar, Mesh.Phi.Radian.flatten(),
                      Mesh.Theta.Radian.flatten())

    dic = {
        'Real': (-3, np.real, 'horizontal'),
        'Imaginary': (+3, np.imag, 'vertical')
    }

    for keys, (val, func, ax) in dic.items():
        Origin = (val, 0, 0)

        AddUnitAxes(Figure=Figure, Scale=2., Origin=Origin)

        mlab.text3d(val, Origin[1], 3, keys, scale=0.5)

        AddUnitSphere(Num=50, Radius=1., Origin=Origin, Figure=Figure)

        im0 = mlab.points3d(Mesh.CartCoord[0] + Origin[0],
                            Mesh.CartCoord[1] + Origin[1],
                            Mesh.CartCoord[2] + Origin[2],
                            func(Scalar),
                            mode='sphere',
                            scale_mode='none',
                            colormap=CMAP)

        mlab.colorbar(object=im0,
                      label_fmt="%.0e",
                      nb_labels=5,
                      title=f'{keys} part',
                      orientation=ax)

        WavenumberArrow(Figure, Origin=(val, 0, -3), Scale=1)

    return Figure
Ejemplo n.º 24
0
    def _Plot(self, Figure=None, Origin=(0, 0, -2)):

        if Figure is None:
            Figure = mlab.figure(figure=None,
                                 size=(600, 300),
                                 bgcolor=(1, 1, 1),
                                 fgcolor=(0., 0., 0.))

        visual.set_viewer(Figure)

        AddUnitSphere(Num=100,
                      Radius=1,
                      Origin=Origin,
                      Figure=Figure,
                      Opacity=0.1)

        self.Polarization._Plot(Figure=Figure, Origin=Origin)

        WavenumberArrow(Figure=Figure, Origin=Origin, Scale=1)

        return Figure
Ejemplo n.º 25
0
def StokesPlot(I,
               Q,
               U,
               V,
               Phi,
               Theta,
               Name='',
               Polarization=None,
               Figure=None):

    Figure = mlab.figure(figure=Name, size=(600, 300))
    visual.set_viewer(Figure)

    dic = {'I': (I, -6), 'Q': (Q, -2), 'U': (U, +2), 'V': (V, +6)}

    for keys, (stokes, val) in dic.items():
        Origin = (val, 0, -3)

        x, y, z = Sp2Cart(Phi * 0 + 1, Phi, Theta)
        im = mlab.points3d(x.flatten() + Origin[0],
                           y.flatten(),
                           z.flatten(),
                           stokes.flatten() / np.max(I),
                           colormap=CMAP,
                           figure=Figure,
                           mode='sphere',
                           scale_mode='none')

        mlab.text3d(Origin[0], Origin[1], 3, keys, scale=0.5)

        lut_manager = mlab.colorbar(object=im,
                                    label_fmt="%.0e",
                                    nb_labels=5,
                                    title='Normalized scale',
                                    orientation='horizontal')

        lut_manager.data_range = (0, 1)

        if Polarization is not None:
            AddSource(Figure, Origin, Polarization, Scale=1)
Ejemplo n.º 26
0
	def run(self,vis=False):
		''' Domyslnie vizualizacje sa wylaczone - vis = True uruchamia vizualizacje '''
		#zabezpieczenie przed overloadingiem , zero division itp
		np.seterr(all="raise") # w razie przekroczenia zakresu wyrzuci yjatek
		if vis: 
			f = mlab.figure(size=(600,600))
			visual.set_viewer(f)
			self.visdata = VisData(self.dlist)# lista punktow do wyswietlenia - jesli vis = True bedzie aktualizowana i wyswietlana

		if not self.fname == None:
			self.fobj = open(self.fname,'w')

		while self.time<self.t:
			try:
				self.__step(vis) # jesli koniec rzuci wyjatek
				self.time+=self.dt
			except: 
				print("Jeden z dipoli opuscil swiat - koniec symulacji")
				return 1

		if self.fobj:
			self.fobj.close()
Ejemplo n.º 27
0
    def _Plot(self, Figure=None, Num=100, Color=(1, 0, 0), Origin=(0, 0, 0)):
        if Figure is None:
            Figure = Figure = mlab.figure(figure=None,
                                          size=(600, 300),
                                          bgcolor=(1, 1, 1),
                                          fgcolor=(0., 0., 0.))

        visual.set_viewer(Figure)
        scale = 0.3
        a = Ellipse(Ellipsity=self.Ellipsity.Radian,
                    Figure=Figure,
                    Origin=Origin,
                    Rotation=self.Azimuth.Radian + np.pi / 2,
                    Label='E')
        b = Ellipse(Ellipsity=self.Ellipsity.Radian,
                    Figure=Figure,
                    Origin=Origin,
                    Rotation=self.Azimuth.Radian,
                    Label='B')
        a._Plot(Color=RED)
        b._Plot(Color=BLUE)

        return Figure
Ejemplo n.º 28
0
def tresdeizar(X, Y, anchox, anchoy, angulo):
    engine = Engine()
    engine.start()
    scene = engine.new_scene()
    scene.scene.disable_render = True  # for speed

    visual.set_viewer(scene)

    surfaces = []
    for k in range(0, len(X)):
        source = ParametricSurface()
        source.function = 'ellipsoid'
        engine.add_source(source)

        surface = Surface()
        source.add_module(surface)

        actor = surface.actor  # mayavi actor, actor.actor is tvtk actor

        actor.property.opacity = 0.7
        actor.property.color = (0, 0, 1)  # tuple(np.random.rand(3))
        actor.mapper.scalar_visibility = False  # don't colour ellipses by their scalar indices into colour map

        actor.actor.orientation = np.array([90, angulo[k], 0
                                            ])  #* 90 #(angulo[k]) # in degrees

        actor.actor.position = np.array([X[k], Y[k], 0])
        actor.actor.scale = np.array(
            [anchox[k] / 2, anchox[k] / 2, anchoy[k] / 2])

        surfaces.append(surface)

        source.scene.background = (1.0, 1.0, 1.0)

    CellScann.set_img_3deizada(mlab)
    return mlab.show()
Ejemplo n.º 29
0
def StructuredAbs(Scalar, Phi, Theta, Name='', Polarization=None):

    Figure = mlab.figure(figure=None, size=(600, 300))
    visual.set_viewer(Figure)

    O = (0, 0, 0)
    O1 = (0, 0, -2)

    x, y, z = Sp2Cart(Scalar / np.max(Scalar) * 4, Phi, Theta)

    AddUnitAxes(Figure=Figure, Scale=5, Origin=O, ScaleTube=0.7)

    im = mlab.mesh(x, y, z - np.min(z), colormap='viridis', figure=Figure)

    mlab.colorbar(object=im,
                  label_fmt="%.0e",
                  nb_labels=5,
                  title='Normalized scale',
                  orientation='horizontal')

    if Polarization is not None:
        AddSource(Figure, O1, Polarization, Scale=1)

    return Figure
Ejemplo n.º 30
0
if __name__ == '__main__':

    path='../../../examples/elm-pb/data'

    data = collect("P", path=path)

    nt=data.shape[0]

    ns=data.shape[1]
    ne=data.shape[2]
    nz=data.shape[3]

    
    f = mayavi.mlab.figure(size=(600,600))
    # Tell visual to use this as the viewer.
    visual.set_viewer(f)

    #First way

    s1 = contour_surf(data[0,:,:,10]+.1, contours=30, line_width=.5, transparent=True)
    s = surf(data[0,:,:,10]+.1, colormap='Spectral')#, warp_scale='.1')#, representation='wireframe')


    # second way

    #x, y= mgrid[0:ns:1, 0:ne:1]
    #s = mesh(x,y,data[0,:,:,10], colormap='Spectral')#, warp_scale='auto')#, representation='wireframe')
    s.enable_contours=True
    s.contour.filled_contours=True
#
Ejemplo n.º 31
0
 def tearDown(self):
     visual.set_viewer(None)
Ejemplo n.º 32
0
 def setUp(self):
     self.viewer = DummyViewer()
     visual.set_viewer(self.viewer)
Ejemplo n.º 33
0
    def __init__(self,random_minerals=True,random_location=True, mineral_location= Location.CENTER,
                 reward = Reward.RELATIVE, grayscale = False, flat = False,
                 mineral_scale = 1.5, start_shift = 0, camera_height = 4,
                 actions = [Action.LEFT,Action.RIGHT,Action.FORWARDS,Action.BACKWARDS,Action.CW,Action.CCW],
                 decorations = False, camera_tilt =  0,start_pos=-23.5,
                 width = 900, height = (500-46),resize_scale=15,
                 x_collision_scale = 1,y_collision_scale = 1,k=5,silver=(.5,.5,.7), random_colors = False,random_lighting=False):
        
        self.random_minerals = random_minerals
        self.random_location = random_location
        self.mineral_location = mineral_location
        self.reward = reward
        self.grayscale = grayscale
        self.flat = flat
        self.actions = actions.copy()
        self.actions_index_dict = self.get_action_index_dictionary()
        self.camera_height = camera_height
        self.decorations = decorations
        self.camera_tilt = camera_tilt
        self.start_pos = start_pos
        self.resize_scale = resize_scale
        mlab.close(all=True)
        self.width = width
        self.height = height + 46
        self.f = mlab.figure(size=(self.width,self.height),bgcolor = (1,1,1))
        
        self.f.scene._lift()
        self.square_width = 23.5
        self.start_shift = start_shift
        self.x_collision_scale = x_collision_scale
        self.y_collision_scale = y_collision_scale
        self.k = k
        self.k_max_iterations = 10
        self.silver = silver
        self.random_colors = random_colors
        self.random_lighting = random_lighting
        visual.set_viewer(self.f)  
        a_side = 34.5
        tape_height = .2
        #distance between minerals
        self.d = 14.5 / np.sqrt(2)
        #color for silver
        #silver = (.8,.8,.8)
        floor_color = (.4,.4,.4)
        #reate field
        self.floor_3_3 = visual.box(x=0,y=0,z=-1, length = 23.5*3,height = 23.5*3,width = 2,color = floor_color)  
        #get mineral location
        locations = self.get_mineral_locations()
        #self.gold_mineral = visual.box(x=locations[0][0],y=locations[0][1],z=1, length=4,height=4,width=4, color = (1,1,0))
        mineral_radius = 2.75 * mineral_scale
        self.gold_mineral = visual.sphere(x=locations[0][0],y=locations[0][1],z=mineral_radius,radius =mineral_radius,color = (1,1,0) )
        self.silver_mineral_1 = visual.sphere(x=locations[1][0],y=locations[1][1],z=mineral_radius,radius =mineral_radius,color = self.silver)
        self.silver_mineral_2 = visual.sphere(x=locations[2][0],y=locations[2][1],z=mineral_radius,radius =mineral_radius,color = self.silver)

        #randomly pick the red or blue side
        r = np.round(np.random.random(1)[0])
        b = 1 - r
        tape_color = (r,0,b)
        #23.5 is the diameter of a square
        #place the crater tape
        
        self.vertical_lander_tape = visual.box(x=-self.square_width*3/2 + 1,y=a_side/2 - self.square_width*3/2,z=tape_height,length = 2, height = a_side, width = tape_height,color=tape_color)
        self.h_lander_tape = visual.box(x=-self.square_width*3/2 + a_side/2,y=-a_side/2,z=tape_height,length = 2, height = a_side * np.sqrt(2), width = tape_height,color=tape_color)
        self.h_lander_tape.rotate(45,axis = [0,0,1],origin = [self.h_lander_tape.x,self.h_lander_tape.y,self.h_lander_tape.z])
        self.marker_left = visual.box(x=self.square_width/2 + 1, y =self.square_width,z=tape_height,length=2,height = self.square_width,width=tape_height,color=tape_color)
        self.marker_right = visual.box(x=3*self.square_width/2 -1, y =self.square_width,z=tape_height,length=2,height = self.square_width,width=tape_height,color=tape_color)
        self.marker_bottom = visual.box(x=self.square_width,y=self.square_width/2 + 1, z = tape_height,length=self.square_width,height=2,width=tape_height,color=tape_color)
        self.marker_top = visual.box(x=self.square_width,y=3*self.square_width/2 - 1, z = tape_height,length=self.square_width,height=2,width=tape_height,color=tape_color)

        #add bars
        if self.decorations:
            bar_width = 1.5
            bar_height = 1
            middle_height = 12 - bar_height*2
            middle_color = floor_color
            bar_length = self.square_width * 3
            bar_color = (0,0,0)
            self.bar1 = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color)
            self.bar1.rotate(90,axis=[0,0,1],origin=self.bar1.pos)
            
            self.bar1m = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color)
            self.bar1m.rotate(90,axis=[0,0,1],origin=self.bar1m.pos)
            
            self.bar1t = visual.box(x=self.square_width*1.5-bar_width/2,y=0,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color)
            self.bar1t.rotate(90,axis=[0,0,1],origin=self.bar1t.pos)

            
            self.bar2 = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color)
            self.bar2.rotate(90,axis=[0,0,1],origin=self.bar2.pos)
            
            self.bar2m = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color)
            self.bar2m.rotate(90,axis=[0,0,1],origin=self.bar2m.pos)
            
            self.bar2t = visual.box(x=-self.square_width*1.5+bar_width/2,y=0,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color)
            self.bar2t.rotate(90,axis=[0,0,1],origin=self.bar2t.pos)
            
            
            
            self.bar3 = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color)
            
            self.bar3m = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color)

            self.bar3t = visual.box(x=0,y=self.square_width*1.5-bar_width/2,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color)

            
            self.bar4 = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=tape_height, width= bar_width, height=bar_height,length=bar_length, color = bar_color)
            
            self.bar4m = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=bar_height+middle_height/2, width= middle_height, height=bar_width,length=bar_length, color = middle_color)

            self.bar4t = visual.box(x=0,y=-self.square_width*1.5+bar_width/2,z=bar_height+middle_height, width= bar_height, height=bar_width,length=bar_length, color = bar_color)
            
            if self.random_colors:
                height_scale = 40
                new_height =  bar_height * height_scale
                self.bar1t.width= new_height
                self.bar1t.rotate(90,axis=[0,0,1],origin=self.bar1t.pos)
                self.bar2t.width= new_height
                self.bar2t.rotate(90,axis=[0,0,1],origin=self.bar2t.pos)
                self.bar3t.width = new_height
                self.bar4t.width = new_height
                
                self.randomize_colors()
                
                
            
        self.x, self.y, self.pos_angle = self.get_start_position()
        self.init_position()
        if self.random_lighting:
            self.randomize_lighting()
        self.move_distance = 2
        self.turn_angle = 5
Ejemplo n.º 34
0
def affichage_terre():
    from mayavi import mlab
    from tvtk.tools import visual
    a = mlab.figure(1,
                    bgcolor=(0.48, 0.48, 0.48),
                    fgcolor=(0, 0, 0),
                    size=(1000, 800))

    mlab.clf()
    visual.set_viewer(a)
    from mayavi.sources.builtin_surface import BuiltinSurface
    continents_src = BuiltinSurface(source='earth', name='Countries')
    continents_src.data_source.on_ratio = 2
    continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0))
    sphere = mlab.points3d(0,
                           0,
                           0,
                           scale_mode='none',
                           scale_factor=2,
                           color=(0.67, 0.77, 0.93),
                           resolution=50,
                           opacity=0.7,
                           name='Earth')
    sphere.actor.property.specular = 0.45
    sphere.actor.property.specular_power = 5
    sphere.actor.property.backface_culling = True

    def Arrow_From_A_to_B(x1, y1, z1, x2, y2, z2):
        ar1 = visual.arrow(x=x1, y=y1, z=z1)
        ar1.length_cone = 0.4

        arrow_length = np.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
        ar1.actor.scale = [arrow_length, arrow_length, arrow_length]
        ar1.pos = ar1.pos / arrow_length
        ar1.axis = [x2 - x1, y2 - y1, z2 - z1]
        #ix = mlab.points3d(2,0,0,mode='arrow') PLUS ELEGANT ???
        #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html ! POINTS3D !
        return ar1

    axX = Arrow_From_A_to_B(0, 0, 0, 1, 0, 0)
    axY = Arrow_From_A_to_B(0, 0, 0, 0, 1, 0)
    axZ = Arrow_From_A_to_B(0, 0, 0, 0, 0, 1)
    '''coords = kepler2card(np.array([1,0,0]),satellites[0][14],-satellites[0][15])
    sat1 = Arrow_From_A_to_B(0, 0, 0, coords[0], coords[1], coords[2])
    coords2 = kepler2card(np.array([1,0,0]),satellites[0][14],0)
    sat2 = Arrow_From_A_to_B(0, 0, 0, coords[0], coords[1], coords[2])
    '''

    theta = np.linspace(0, 2 * np.pi, 100)
    for i in range(len(satellites)):
        U = kepler2card(np.array([1, 0, 0]), -satellites[i][15],
                        satellites[i][14])
        N = kepler2card(np.array([0, 0, 1]), -satellites[i][15],
                        satellites[i][14])

        #U = kepler2card(np.array([1,0,0]),-82.1335,54.1115)
        #N = kepler2card(np.array([0,0,1]),-82.1335,54.1115)

        UN = np.cross(U, N)

        #P = R*np.cos(theta)*U+R*np.sin(theta)*U.cross(N)
        x = R * np.cos(theta) * U[0] + R * np.sin(theta) * UN[0]
        y = R * np.cos(theta) * U[1] + R * np.sin(theta) * UN[1]
        z = R * np.cos(theta) * U[2] + R * np.sin(theta) * UN[2]
        mlab.plot3d(x, y, z, color=(1, 1, 1), opacity=0.2, tube_radius=None)

    for i in range(len(satellites)):
        U = kepler2card(np.array([1, 0, 0]), -cosatellites[i][15],
                        satellites[i][14])
        N = kepler2card(np.array([0, 0, 1]), -satellites[i][15],
                        satellites[i][14])

        #U = kepler2card(np.array([1,0,0]),-82.1335,54.1115)
        #N = kepler2card(np.array([0,0,1]),-82.1335,54.1115)

        UN = np.cross(U, N)
        theta = np.deg2rad(satellites[i][18]) * 0
        n = satellites[i][18]
        d = ((mu**(1 / 3)) / ((2 * n * np.pi / 86400)**(2 / 3)))
        x = (d * np.cos(theta) * U[0] + d * np.sin(theta) * UN[0]) * R
        y = (d * np.cos(theta) * U[1] + d * np.sin(theta) * UN[1]) * R
        z = (d * np.cos(theta) * U[2] + d * np.sin(theta) * UN[2]) * R

        if (satellites[i][0].find("16") != -1
                or satellites[i][0].find("26") != -1):
            points = mlab.points3d(x,
                                   y,
                                   z,
                                   scale_mode='none',
                                   scale_factor=0.1,
                                   color=(1, 0, 0))

        x = (d * np.cos(theta) * U[0] + d * np.sin(theta) * UN[0])
        y = (d * np.cos(theta) * U[1] + d * np.sin(theta) * UN[1])
        z = (d * np.cos(theta) * U[2] + d * np.sin(theta) * UN[2])

        if (satellites[i][0].find("16") != -1
                or satellites[i][0].find("26") != -1):
            print(theta)
            points = mlab.points3d(x,
                                   y,
                                   z,
                                   scale_mode='none',
                                   scale_factor=0.1,
                                   color=(1, 0, 0))
    return n, d
    def __init__(self,
                 hex_list,
                 np_file='/tmp/magnetic_ground_truth.np',
                 robot_height=40,
                 width=800,
                 height=600,
                 start_point=(0, 0, 0),
                 message='experiment default message...',
                 battery=99999):
        self.debug = False
        self.animator = None
        self.movement_mode = 0
        self.start_point = start_point
        self.robot_height = robot_height
        self.message = message

        self.start_time = int(time.time() * 1000)
        self.timestep = 0

        self.width = width
        self.height = height

        self.f = mlab.figure(size=(self.width, self.height))
        visual.set_viewer(self.f)

        v = mlab.view(270, 180)
        #print v

        engine = mlab.get_engine()
        self.s = engine.current_scene
        self.s.scene.interactor.add_observer('KeyPressEvent',
                                             self.keypress_callback)

        self.robots = []

        colors = list(PathBatterySimulator.color_codes)

        for key, local_hex_list in sorted(hex_list['internal_routes'].items()):
            color = colors.pop(0)

            ball = visual.sphere(color=color,
                                 radius=PathBatterySimulator.ball_radius)
            ball.x = self.start_point[0]
            ball.y = self.start_point[1]
            ball.z = self.start_point[2]

            r, g, b = color
            rt = r + (0.25 * (1 - r))
            gt = g + (0.25 * (1 - g))
            bt = b + (0.25 * (1 - b))
            curve_color = (rt, gt, bt)

            curve = visual.curve(color=curve_color,
                                 radius=PathBatterySimulator.curve_radius)

            r_ball = RobotBall(key,
                               local_hex_list,
                               hex_list['external_routes'][key],
                               ball,
                               curve,
                               battery=battery)
            self.robots.append(r_ball)

        x = np.linspace(0, self.width, 1)
        y = np.linspace(0, self.height, 1)

        z = np.loadtxt(np_file)
        z *= 255.0 / z.max()

        # HARDCODED
        # Todo: REMOVE THIS CODE ON THE FINAL RELEASE
        for xx in xrange(0, 200):
            for yy in xrange(400, 600):
                z[yy][xx] = 0

        mlab.surf(x, y, z)

        self.master_cmd = MasterCommand(self.robots)

        self.robot_pos = open('/tmp/robot_log.txt', 'a')
Ejemplo n.º 36
0
def plotpolslice(var3d, gridfile, period=1, zangle=0.0, rz=1, fig=0):
    """ data2d = plotpolslice(data3d, 'gridfile' , period=1, zangle=0.0, rz:return (r,z) grid also=1, fig: to do the graph, set to 1 ) """

    g = file_import(gridfile)

    nx = var3d.shape[0]
    ny = var3d.shape[1]
    nz = var3d.shape[2]

    zShift = g.get('zShift')
    rxy = g.get('Rxy')
    zxy = g.get('Zxy')

    dz = 2.0 * np.pi / float(period * (nz - 1))

    ny2 = ny
    nskip = np.zeros(ny - 1)
    for i in range(ny - 1):
        ip = (i + 1) % ny
        nskip[i] = 0
        for x in range(nx):
            ns = old_div(np.max(np.abs(zShift[x, ip] - zShift[x, i])), dz) - 1
            if ns > nskip[i]: nskip[i] = ns

    nskip = np.int_(np.round(nskip))
    ny2 = np.int_(ny2 + np.sum(nskip))

    print("Number of poloidal points in output:" + str(ny2))

    var2d = np.zeros((nx, ny2))
    r = np.zeros((nx, ny2))
    z = np.zeros((nx, ny2))

    ypos = 0
    for y in range(ny - 1):
        # put in the original points
        for x in range(nx):
            zind = old_div((zangle - zShift[x, y]), dz)
            var2d[x, ypos] = zinterp(var3d[x, y, :], zind)
            #     IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,y]
            r[x, ypos] = rxy[x, y]
            z[x, ypos] = zxy[x, y]

        ypos = ypos + 1

        print((y, ypos))

        # and the extra points

        for x in range(nx):
            zi0 = old_div((zangle - zShift[x, y]), dz)
            zip1 = old_div((zangle - zShift[x, y + 1]), dz)

            dzi = old_div((zip1 - zi0), (nskip[y] + 1))

            for i in range(nskip[y]):
                zi = zi0 + float(i + 1) * dzi  # zindex
                w = old_div(float(i + 1), float(nskip[y] + 1))  # weighting

                var2d[x, ypos + i] = w * zinterp(var3d[x, y + 1, :], zi) + (
                    1.0 - w) * zinterp(var3d[x, y, :], zi)
                #  IF KEYWORD_SET(profile) THEN var2d[x,ypos+i] = var2d[x,ypos+i] + w*profile[x,y+1] + (1.0-w)*profile[x,y]
                r[x, ypos + i] = w * rxy[x, y + 1] + (1.0 - w) * rxy[x, y]
                z[x, ypos + i] = w * zxy[x, y + 1] + (1.0 - w) * zxy[x, y]

        ypos = ypos + nskip[y]

# FINAL POINT

    for x in range(nx):
        zind = old_div((zangle - zShift[x, ny - 1]), dz)
        var2d[x, ypos] = zinterp(var3d[x, ny - 1, :], zind)
        # IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,ny-1]
        r[x, ypos] = rxy[x, ny - 1]
        z[x, ypos] = zxy[x, ny - 1]

    if (fig == 1):

        f = mlab.figure(size=(600, 600))
        # Tell visual to use this as the viewer.
        visual.set_viewer(f)

        s = mlab.mesh(r, z, var2d, colormap='PuOr'
                      )  #, wrap_scale='true')#, representation='wireframe')
        s.enable_contours = True
        s.contour.filled_contours = True
        mlab.view(0, 0)

    else:
        # return according to opt
        if rz == 1:
            return r, z, var2d
        else:
            return var2d
Ejemplo n.º 37
0
    def __init__(self,
                 model,
                 building_layout,
                 building_size,
                 building_spacing,
                 fig=None):
        self.model = model
        self.building_layout = np.array(building_layout)
        self.building_size = building_size
        self.building_spacing = np.float64(building_spacing)
        if fig is None:
            self.fig = mlab.figure(size=(500, 500), bgcolor=(0.1, 0.1, 0.1))
        else:
            self.fig = fig

        # Set figure for visual objects
        visual.set_viewer(self.fig)

        # Convenient local aliases
        nx, ny = self.building_layout.shape
        n = nx * ny

        # Beautiful colors
        self.building_colors = map(
            tuple,
            np.array((np.linspace(0.0, 0.0, n), np.linspace(0.8, 0.3, n),
                      np.linspace(0.3, 0.8, n))).T)

        # For storing buildings and their locations
        self.buildings = []
        self.building_centers = np.zeros((n, 2))

        # Generate buildings
        for i, x in enumerate(
                np.linspace(0, (nx - 1) *
                            (self.building_size[0] + self.building_spacing),
                            nx)):
            for j, y in enumerate(
                    np.linspace(
                        0, (ny - 1) *
                        (self.building_size[1] + self.building_spacing), ny)):
                if not self.building_layout[i, j]: continue
                idx = int(ny * i + j)
                self.building_centers[idx] = (x, y)
                self.buildings.append(
                    visual.box(x=x,
                               y=y,
                               z=self.building_size[2] / 2,
                               size=self.building_size,
                               color=self.building_colors[idx]))

        # Generate ground plane
        if self.buildings:
            ground_xx, ground_yy = map(
                np.transpose,
                np.meshgrid(
                    np.linspace(np.min(self.building_centers[:, 0] - 10),
                                np.max(self.building_centers[:, 0] + 10), 2),
                    np.linspace(np.min(self.building_centers[:, 1] - 10),
                                np.max(self.building_centers[:, 1] + 10), 2)))
            self.ground = mlab.surf(ground_xx,
                                    ground_yy,
                                    np.zeros_like(ground_xx),
                                    color=(0, 0.2, 0.2),
                                    warp_scale=1)
        else:
            self.ground = None

        # Generate multicopter
        self.copter_radius = 1.1 * npl.norm(
            self.model.thruster_positions[0, :2])
        self.copter_sticks = np.vstack(([
            (0, 0, 0), (self.copter_radius, 0, 0)
        ], self.model.thruster_positions, (self.copter_radius, 0, 0))).T
        self.copter_sticks_plot = mlab.plot3d(self.copter_sticks[0, :],
                                              self.copter_sticks[1, :],
                                              self.copter_sticks[2, :],
                                              line_width=5,
                                              color=(1, 0, 1))
        self.copter_nodes = np.vstack(([0, 0,
                                        0], self.model.thruster_positions)).T
        self.copter_nodes_plot = mlab.points3d(self.copter_nodes[0, :],
                                               self.copter_nodes[1, :],
                                               self.copter_nodes[2, :],
                                               scale_factor=0.15)
        self.copter_nodes_plot.glyph.scale_mode = "scale_by_vector"
        self.copter_nodes_plot.mlab_source.dataset.point_data.scalars = [
            0, 1, 0.7, 0.7, 0.7, 0.7, 1, 0
        ]  # hack to individually color points
        self.copter_vecs = [
            np.vstack((thr.position, thr.position + 1e-5 * thr.direction)).T
            for thr in self.model.thruster_list
        ]
        self.copter_vecs_plots = [
            mlab.plot3d(vec[0, :], vec[1, :], vec[2, :], color=(1, 1, 1))
            for vec in self.copter_vecs
        ]

        # Aliases for Mayavi animate decorator and show function
        self.animate = mlab.animate
        self.show = mlab.show
Ejemplo n.º 38
0
def plotpolslice(var3d,gridfile,period=1,zangle=0.0, rz=1, fig=0):
    """ data2d = plotpolslice(data3d, 'gridfile' , period=1, zangle=0.0, rz:return (r,z) grid also=1, fig: to do the graph, set to 1 ) """

    g=file_import(gridfile)

    nx=var3d.shape[0]
    ny=var3d.shape[1]
    nz=var3d.shape[2]


    zShift=g.get('zShift')
    rxy=g.get('Rxy')
    zxy=g.get('Zxy')

    dz = 2.0*np.pi / float(period*nz)

    ny2=ny
    nskip=np.zeros(ny-1)
    for i in range(ny-1):
        ip=(i+1)%ny
        nskip[i]=0
        for x in range(nx):
            ns=old_div(np.max(np.abs(zShift[x,ip]-zShift[x,i])),dz)-1
            if ns > nskip[i] : nskip[i] = ns

    nskip = np.int_(np.round(nskip))
    ny2 = np.int_(ny2 + np.sum(nskip))

    print("Number of poloidal points in output:" + str(ny2))

    var2d = np.zeros((nx, ny2))
    r = np.zeros((nx, ny2))
    z = np.zeros((nx, ny2))

    ypos = 0
    for y in range (ny-1) :
      # put in the original points
        for x in range (nx):
            zind = old_div((zangle - zShift[x,y]),dz)
            var2d[x,ypos] = zinterp(var3d[x,y,:], zind)
     #     IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,y]
            r[x,ypos] = rxy[x,y]
            z[x,ypos] = zxy[x,y]

        ypos = ypos + 1

        print((y, ypos))

      # and the extra points

        for x in range (nx):
            zi0 = old_div((zangle - zShift[x,y]),dz)
            zip1 = old_div((zangle - zShift[x,y+1]),dz)

            dzi = old_div((zip1 - zi0), (nskip[y] + 1))

            for i in range (nskip[y]):
                zi = zi0 + float(i+1)*dzi # zindex
                w = old_div(float(i+1),float(nskip[y]+1)) # weighting

                var2d[x,ypos+i] = w*zinterp(var3d[x,y+1,:], zi) + (1.0-w)*zinterp(var3d[x,y,:], zi)
            #  IF KEYWORD_SET(profile) THEN var2d[x,ypos+i] = var2d[x,ypos+i] + w*profile[x,y+1] + (1.0-w)*profile[x,y]
                r[x,ypos+i] = w*rxy[x,y+1] + (1.0-w)*rxy[x,y]
                z[x,ypos+i] = w*zxy[x,y+1] + (1.0-w)*zxy[x,y]



        ypos = ypos + nskip[y]


  # FINAL POINT

    for x in range(nx):
        zind = old_div((zangle - zShift[x,ny-1]),dz)
        var2d[x,ypos] = zinterp(var3d[x,ny-1,:], zind)
     # IF KEYWORD_SET(profile) THEN var2d[x,ypos] = var2d[x,ypos] + profile[x,ny-1]
        r[x,ypos] = rxy[x,ny-1]
        z[x,ypos] = zxy[x,ny-1]


    if(fig==1):

        f = mlab.figure(size=(600,600))
        # Tell visual to use this as the viewer.
        visual.set_viewer(f)


        s = mlab.mesh(r,z,var2d, colormap='PuOr')#, wrap_scale='true')#, representation='wireframe')
        s.enable_contours=True
        s.contour.filled_contours=True
        mlab.view(0,0)

    else:
        # return according to opt
        if rz==1 :
            return r,z,var2d
        else:
            return var2d
Ejemplo n.º 39
0
try:
    engine = mayavi.engine
except NameError:
    from mayavi.api import Engine
    engine = Engine()
    engine.start()
if len(engine.scenes) == 0:
    engine.new_scene(size=(600, 800))
scene = engine.scenes[0]
fig = mlab.gcf(engine)
figure = mlab.figure(figure=fig,
                     bgcolor=(0.0, 0.0, 0.0),
                     fgcolor=(0.0, 0.0, 0.0),
                     engine=engine)
visual.set_viewer(fig)
fig.scene.disable_render = True

peaks = []
space_plots = []
for i in range(len(structures)):
    struc = structures[i]
    space_plots.append(rsplt.space_plot(struc.lattice))
    if (struc.plot_peaks):
        peaks.append(space_plots[i].plot_peaks(qx_lims=qx_lims,
                                               qy_lims=qy_lims,
                                               qz_lims=qz_lims,
                                               q_inplane_lim=q_inplane_lim,
                                               mag_q_lims=mag_q_lims,
                                               color=struc.color))
    if (struc.plot_rods):
Ejemplo n.º 40
0
    ar1=visual.arrow(x=x1, y=y1, z=z1)
    ar1.length_cone=0.4

    arrow_length=np.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)
    ar1.actor.scale=[arrow_length, arrow_length, arrow_length]
    ar1.pos = ar1.pos/arrow_length
    ar1.axis = [x2-x1, y2-y1, z2-z1]
    return ar1

fig = mlab.figure()
scene = mlab.gcf().scene
scene.renderer.render_window.set(alpha_bit_planes=1,multi_samples=0)
scene.renderer.set(use_depth_peeling=True,maximum_number_of_peels=4,occlusion_ratio=0.1)

from tvtk.tools import visual
visual.set_viewer(fig)
Arrow_From_A_to_B(0,0,0,avg_d[0],avg_d[1],avg_d[2])

for i, line in enumerate(curves):
    c = np.random.rand(3,1)
    mlab.plot3d(line[:,0], line[:,1], line[:,2], range(0,len(line)))
    orig = streams[i]
    mlab.plot3d(orig[:,0], orig[:,1], orig[:,2], color=(1,1,1), opacity=0.5)

mlab.points3d(avg_com[0],avg_com[1],avg_com[2],color=(1,0,0), mode='axes',scale_factor=5)
mlab.points3d(avg_mid[0],avg_mid[1],avg_mid[2],color=(0,0,1), mode='axes',scale_factor=5)
mlab.show() 

sys.exit()

# from matplotlib import pyplot as plt
Ejemplo n.º 41
0
if __name__ == "__main__":

    path = "../../../examples/elm-pb/data"

    data = collect("P", path=path)

    nt = data.shape[0]

    ns = data.shape[1]
    ne = data.shape[2]
    nz = data.shape[3]

    f = mlab.figure(size=(600, 600))
    # Tell visual to use this as the viewer.
    visual.set_viewer(f)

    # First way

    s1 = contour_surf(data[0, :, :, 10] + 0.1,
                      contours=30,
                      line_width=0.5,
                      transparent=True)
    s = surf(data[0, :, :, 10] + 0.1, colormap="Spectral"
             )  # , warp_scale='.1')#, representation='wireframe')

    # second way

    # x, y= mgrid[0:ns:1, 0:ne:1]
    # s = mesh(x,y,data[0,:,:,10], colormap='Spectral')#, warp_scale='auto')
    # #, representation='wireframe')