def FCC(L_x, L_y, L_z, Color='red'):
    Ax = []
    Ay = []
    Az = []
    #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells
    for O in range(L_x * 2 - 1):
        #for each layer in the y direction.
        for S in range(L_y * 2 - 1):
            #for each layer in the z direction.
            for A in range(L_z * 2 - 1):
                if (O + S + A) % 2 == 0:
                    #the 0.5 is becasue L_xyz was multiplied by 2
                    Ax.append(float(O * .5))
                    Ay.append(float(S * .5))
                    Az.append(float(A * .5))
                elif S % 2 == 1 and O % 2 == 1 and A % 2 == 0:
                    Ax.append(float(O * .5))
                    Ay.append(float(S * .5))
                    Az.append(float(A * .5))
                #if there should not be an atom
                #in theory this could be used to remove other atoms to make cubic or BCC structure
    #the x, y, z limits
    ipv.xyzlim(0, 10)  #define as a function highest of L_xyz
    ipv.scatter(np.array(Ax),
                np.array(Ay),
                np.array(Az),
                marker='sphere',
                size=6.5,
                color=Color)
    ipv.show()
Ejemplo n.º 2
0
    def ShowAnimation3D(self, size=15):
        ipv.figure()
        ipv.style.use("dark")

        x_Part = []
        y_Part = []
        z_Part = []

        for Part in self.Parts:
            temp_x = Part.x
            temp_y = Part.y
            temp_z = Part.z

            x_Part.append(temp_x)
            y_Part.append(temp_y)
            z_Part.append(temp_z)

        x = combine(self.speed * 5, *x_Part)
        y = combine(self.speed * 5, *y_Part)
        z = combine(self.speed * 5, *z_Part)

        u = ipv.scatter(x, y, z, marker="sphere", size=10, color="green")

        ipv.animation_control(u, interval=100)

        ipv.xyzlim(-size, size)
        ipv.show()
Ejemplo n.º 3
0
    def on_select_to_plot(self, change):
        """Call-back function for plotting a 3D visualisaiton of the segmentation"""

        #if the selected file has changed, import image, segmentation and global mask and plot
        if change['new'] != change['old']:
            print('new: ' + str(change['new']))
            print('old: ' + str(change['old']))

            image = skimage.io.imread(self.folder_name + '/' +
                                      self.select_file_to_plot.value,
                                      plugin='tifffile')
            image2 = skimage.io.imread(
                self.folder_name + '/' +
                os.path.splitext(self.select_file_to_plot.value)[0] +
                '_label.tif',
                plugin='tifffile')
            image3 = skimage.io.imread(
                self.folder_name + '/' +
                os.path.splitext(self.select_file_to_plot.value)[0] +
                '_region.tif',
                plugin='tifffile')

            #create ipyvolume figure
            ipv.figure()
            volume_image = ipv.volshow(image[0, :, :, :, 1],
                                       extent=[[0, 1024], [0, 1024], [-20,
                                                                      20]],
                                       level=[0.3, 0.2, 0.2],
                                       opacity=[0.2, 0, 0])
            volume_seg = ipv.plot_isosurface(np.swapaxes(image2 > 0, 0, 2),
                                             level=0.5,
                                             controls=True,
                                             color='green',
                                             extent=[[0, 1024], [0, 1024],
                                                     [-20, 20]])
            volume_reg = ipv.volshow(image3,
                                     extent=[[0, 1024], [0, 1024], [-20, 20]],
                                     level=[0.3, 0.2, 1],
                                     opacity=[0.0, 0, 0.5])
            volume_reg.brightness = 10
            volume_image.brightness = 10
            volume_image.opacity = 100
            ipv.xyzlim(0, 1024)
            ipv.zlim(-500, 500)
            ipv.style.background_color('black')

            #create additional controls to show/hide segmentation
            color = ColorPicker(description='Segmentation color')
            visible = ipw.Checkbox()
            jslink((volume_seg, 'color'), (color, 'value'))
            jslink((volume_seg, 'visible'), (visible, 'value'))
            ipv.show()
            with self.out:
                clear_output(wait=True)
                display(VBox([ipv.gcc(), color, visible]))

            viewer = napari.Viewer(ndisplay=3)
            viewer.add_image(image, colormap='red')
            viewer.add_image(image2, colormap='green', blending='additive')
            viewer.add_image(image3, colormap='blue', blending='additive')
Ejemplo n.º 4
0
def browse_history(history,
                   coords=["x", "y", "z"],
                   start=None,
                   stop=None,
                   size=None,
                   **draw_specs_kw):
    times = history.slice(start, stop, size)
    num_frames = times.size
    draw_specs = sheet_spec()
    spec_updater(draw_specs, draw_specs_kw)
    sheet = history.retrieve(0)
    ipv.clear()
    fig, meshes = sheet_view(sheet, coords, **draw_specs_kw)

    lim_inf = sheet.vert_df[sheet.coords].min().min()
    lim_sup = sheet.vert_df[sheet.coords].max().max()
    ipv.xyzlim(lim_inf, lim_sup)

    def set_frame(i=0):
        fig.animation = 0
        t = times[i]
        meshes = _get_meshes(history.retrieve(t), coords, draw_specs)
        update_view(fig, meshes)

    ipv.show()
    interact(set_frame, i=(0, num_frames - 1))
Ejemplo n.º 5
0
    def _display_sphere(
        self,
        fluxes,
        distances,
        theta,
        phi,
        cmap="magma",
        distance_transform=None,
        use_log=False,
        fig=None,
        background_color="white",
        show=True,
        **kwargs,
    ):

        if len(fluxes) == 0:
            log.warning("There are no detections to display")

            return

        if fig is None:

            fig = ipv.figure()

        ipv.pylab.style.box_off()
        ipv.pylab.style.axes_off()
        ipv.pylab.style.set_style_dark()
        ipv.pylab.style.background_color(background_color)

        if distance_transform is not None:

            distance = distance_transform(distances)

        else:

            distance = distances

        x, y, z = _create_sphere_variables(self._r_max, distance, theta, phi)

        _, colors = array_to_cmap(fluxes, cmap, use_log=True)

        ipv.scatter(x, y, z, color=colors, marker="sphere", **kwargs)

        r_value = fig

        if show:

            ipv.xyzlim(self._r_max)
            fig.camera.up = [1, 0, 0]
            control = pythreejs.OrbitControls(controlling=fig.camera)
            fig.controls = control
            control.autoRotate = True
            fig.render_continuous = True
            # control.autoRotate = True
            # toggle_rotate = widgets.ToggleButton(description="Rotate")
            # widgets.jslink((control, "autoRotate"), (toggle_rotate, "value"))
            # r_value = toggle_rotate

        return fig
def NACL(L_x, L_y=None, L_z=None, ColorNa='red', ColorCl='green'):
    if L_y == None:
        L_y = L_x
    if L_z == None:
        L_z = L_x
    if L_x > L_y:
        Max = L_x
    else:
        Max = L_y
    if L_z > Max:
        Max = L_z  #defined as a function highest of L_xyz
    #define a list of positions to append to
    Clx = []
    Cly = []
    Clz = []
    Nax = []
    Nay = []
    Naz = []
    #for each layer of the atom in the x direction. the *2-1 is so that L_x is the number of unit cells
    for O in range(L_x * 2 - 1):
        #for each layer in the y direction.
        for S in range(L_y * 2 - 1):
            #for each layer in the z direction.
            for A in range(L_z * 2 - 1):
                #if in this position there shoud be a Cl atom
                if (O + S + A) % 2 == 0:
                    #the 0.5 is becasue L_xyz was multiplied by 2
                    Clx.append(float(O * .5))
                    Cly.append(float(S * .5))
                    Clz.append(float(A * .5))
                #if there should be a Na atom
                elif (O + S + A) % 2 == 1:
                    Nax.append(float(O * .5))
                    Nay.append(float(S * .5))
                    Naz.append(float(A * .5))
                #if there should not be an atom
                #in theory this could be used to remove other atoms to make cubic or BCC structure
    #the x, y, z limits
    ipv.xyzlim(0, Max)
    #the color and size the Na and Cl atoms
    ipv.scatter(np.array(Clx),
                np.array(Cly),
                np.array(Clz),
                marker='sphere',
                size=6.5,
                color=ColorCl)
    ipv.scatter(
        np.array(Nax),
        np.array(Nay),
        np.array(Naz),
        marker='sphere',
        size=4,
        color=ColorNa,
    )
    ipv.show()
Ejemplo n.º 7
0
def plot_milkyway(R_sun=8, size=100):
    mw_image = PIL.Image.open(milkyway_image.fetch())
    rescale = 40
    t = np.linspace(0, 1, 100)
    xmw = np.linspace(0, 1, 10)
    ymw = np.linspace(0, 1, 10)
    xmw, ymw = np.meshgrid(xmw, ymw)
    zmw = xmw * 0 + 0.01
    mw = mesh = ipv.plot_mesh((xmw-0.5)*rescale, (ymw-0.5)*rescale+R_sun, zmw, u=xmw, v=ymw, texture=mw_image, wireframe=False)
    mw.material.blending = pythreejs.BlendingMode.CustomBlending
    mw.material.blendSrc = pythreejs.BlendFactors.SrcColorFactor
    mw.material.blendDst = pythreejs.BlendFactors.OneFactor
    mw.material.blendEquation = 'AddEquation'
    mw.material.transparent = True
    mw.material.depthWrite = False
    mw.material.alphaTest = 0.1
    ipv.xyzlim(size)
    return mesh
Ejemplo n.º 8
0
def test_ipyvolume():
    import ipyvolume as ipv

    s = 1 / 2**0.5
    # 4 vertices for the tetrahedron
    x = np.array([1., -1, 0, 0])
    y = np.array([0, 0, 1., -1])
    z = np.array([-s, -s, s, s])
    # and 4 surfaces (triangles), where the number refer to the vertex index
    triangles = [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 3, 2)]

    ipv.figure()
    # draw the tetrahedron mesh
    ipv.plot_trisurf(x, y, z, triangles=triangles, color='orange')
    # mark the vertices
    ipv.scatter(x, y, z, marker='sphere', color='blue')
    # set limits and show
    ipv.xyzlim(-2, 2)
    ipv.show()
def SC(L_x, L_y, L_z, Color='red'):
    Ax = []
    Ay = []
    Az = []
    for O in range(L_x):
        #for each layer in the y direction.
        for S in range(L_y):
            #for each layer in the z direction.
            for A in range(L_z):
                Ax.append(float(O))
                Ay.append(float(S))
                Az.append(float(A))
    #the x, y, z limits
    ipv.xyzlim(0, 10)  #define as a function highest of L_xyz
    ipv.scatter(np.array(Ax),
                np.array(Ay),
                np.array(Az),
                marker='sphere',
                size=6.5,
                color=Color)
    ipv.show()
Ejemplo n.º 10
0
def draw_compas_mesh(mesh, color='white', size=1.0):
    """
    Renders a compas mesh on a 3D canvas with ipyvolume.

    Parameters
    ----------
    mesh : :class: compas.datastructures.Mesh
        the mesh to be shown in 3D

    Returns
    -------
    an instance of ipyvolume.widgets.Mesh
    """
    import ipyvolume as ipv

    # extract lists of vertices and faces
    vertices, faces = mesh.to_vertices_and_faces()

    # extract x, y and z values into separate lists
    x = [v[0] for v in vertices]
    y = [v[1] for v in vertices]
    z = [v[2] for v in vertices]

    # triangulate n-gons
    triangles_only = []
    for f in faces:
        if len(f) == 3:
            triangles_only.append(f)
        else:
            for i in range(len(f) - 2):
                triangles_only.append([f[0], f[i+1], f[i+2]])

    # create the ipyvolume plot
    ipv.figure(width=800, height=450)
    viewermesh = ipv.plot_trisurf(x, y, z, triangles_only, color=color)
    ipv.xyzlim(size)
    ipv.style.use('minimal')
    ipv.show()

    return viewermesh
Ejemplo n.º 11
0
def sheet_view(sheet, coords=["x", "y", "z"], **draw_specs_kw):
    """
    Creates a javascript renderer of the edge lines to be displayed
    in Jupyter Notebooks

    Returns
    -------

    fig: a :class:`ipyvolume.widgets.Figure` widget
    mesh: a :class:`ipyvolume.widgets.Mesh` mesh widget

    """

    ipv.style.use(["dark", "minimal"])
    draw_specs = sheet_spec()
    spec_updater(draw_specs, draw_specs_kw)
    fig = ipv.gcf()

    edge_spec = draw_specs["edge"]
    if edge_spec["visible"]:
        edges = edge_mesh(sheet, coords, **edge_spec)
        fig.meshes = fig.meshes + [edges]
    else:
        edges = None

    face_spec = draw_specs["face"]
    if face_spec["visible"]:
        faces = face_mesh(sheet, coords, **face_spec)
        fig.meshes = fig.meshes + [faces]
    else:
        faces = None

    box_size = max(*(np.ptp(sheet.vert_df[u]) for u in sheet.coords))
    border = 0.05 * box_size
    lim_inf = sheet.vert_df[sheet.coords].min().min() - border
    lim_sup = sheet.vert_df[sheet.coords].max().max() + border
    ipv.xyzlim(lim_inf, lim_sup)
    return fig, (edges, faces)
Ejemplo n.º 12
0
def view_ipv(sheet, coords=["x", "y", "z"], **edge_specs):
    """
    Creates a javascript renderer of the edge lines to be displayed
    in Jupyter Notebooks

    Returns
    -------

    fig: a :class:`ipyvolume.widgets.Figure` widget
    mesh: a :class:`ipyvolume.widgets.Mesh` mesh widget

    """
    warnings.warn("`view_ipv` is deprecated, use the more generic `sheet_view`")
    mesh = edge_mesh(sheet, coords, **edge_specs)
    fig = ipv.gcf()
    fig.meshes = fig.meshes + [mesh]
    box_size = max(*(np.ptp(sheet.vert_df[u]) for u in sheet.coords))
    border = 0.05 * box_size
    lim_inf = sheet.vert_df[sheet.coords].min().min() - border
    lim_sup = sheet.vert_df[sheet.coords].max().max() + border
    ipv.xyzlim(lim_inf, lim_sup)

    return fig, mesh
Ejemplo n.º 13
0
def sheet_view(sheet, coords=["x", "y", "z"], **draw_specs_kw):
    """
    Creates a javascript renderer of the edge lines to be displayed
    in Jupyter Notebooks

    Returns
    -------

    fig: a :class:`ipyvolume.widgets.Figure` widget
    mesh: a :class:`ipyvolume.widgets.Mesh` mesh widget

    """

    # ipv.style.use(["dark", "minimal"])
    draw_specs = sheet_spec()
    spec_updater(draw_specs, draw_specs_kw)
    fig = ipv.gcf()
    fig.meshes = fig.meshes + _get_meshes(sheet, coords, draw_specs)
    box_size = max(*(np.ptp(sheet.vert_df[u]) for u in sheet.coords))
    border = 0.05 * box_size
    lim_inf = sheet.vert_df[sheet.coords].min().min() - border
    lim_sup = sheet.vert_df[sheet.coords].max().max() + border
    ipv.xyzlim(lim_inf, lim_sup)
    return fig, fig.meshes
Ejemplo n.º 14
0
def get_globe(topofile, df, size=None, key=None):
    """Return an ipywidget with an interactive globe.

       Arguments:
         topofile: filename of a TopoJSON file to render. This file is expected to have its
            major regions arranged as a list in ['objects']['areas']['geometries'].
         df: dataframe where each row will be turned into an animation frame and columns
            are expected to match the major regions in the topofile.
         size: in integer pixels
         key: string key to pass to ipyvolume, allows replacement of earlier charts
    """
    with open(topofile, 'r') as fid:
        topo = json.loads(fid.read())
    (width, height) = (size, size) if size is not None else (500, 500)
    ipv.pylab.clear()
    fig = ipv.figure(width=width, height=height, key=key, controls=True)

    # Make a simple globe
    x, y, z = np.array([[0.], [0.], [0.]])
    ipv.scatter(x, y, z, size=100, color='blue', marker="sphere")

    # draw raised outlines for each area
    animate = []
    for area in topo['objects']['areas']['geometries']:
        name = area['id']
        if name not in df.columns:
            continue
        lines = _extract_lines(topo, name=name)
        x = []
        y = []
        z = []
        triangles = []
        data = df.loc[:, name].fillna(0.0)
        for (year, row) in df.iterrows():
            x_t = [0]
            y_t = [0]
            z_t = [0]
            tri_t = []
            offset = 1
            total = row.get('Total', row.get('World', 1.0))
            val = row.get(name, 0.0)
            radius = 1.01 + (((val / total) * 0.15) if total > 0.0 else 0.0)
            for line in lines:
                xyz = [
                    _latlon2xyz(lat, lon, radius=radius) for (lon, lat) in line
                ]
                x1, y1, z1 = [list(t) for t in zip(*xyz)]
                x_t.extend(x1 + [0])
                y_t.extend(y1 + [0])
                z_t.extend(z1 + [0])
                for _ in range(0, len(x1)):
                    tri_t.append([0, offset, offset + 1])
                    offset += 1
                offset += 1
            x.append(x_t)
            y.append(y_t)
            z.append(z_t)
            triangles.append(tri_t)

        color = ui.color.webcolor_to_hex(ui.color.get_region_color(name))
        s = ipv.scatter(x=-np.array(x),
                        y=np.array(z),
                        z=np.array(y),
                        color=color,
                        size=0.5,
                        connected=True,
                        marker='sphere')
        s.material.visible = False
        animate.append(s)
        s = ipv.pylab.plot_trisurf(-np.array(x),
                                   np.array(z),
                                   np.array(y),
                                   color=color,
                                   triangles=triangles)
        animate.append(s)

    ipv.animation_control(animate, interval=100)
    ipv.xyzlim(-1, 1)
    ipv.style.box_on()
    ipv.style.axes_off()
    return ipv.gcc()
Ejemplo n.º 15
0
    def on_select_to_plot(self, b):
        """Call-back function for plotting a 3D visualisaiton of the segmentation"""

        self.out.clear_output()

        image = skimage.io.imread(self.folders.cur_dir.as_posix() + '/' +
                                  self.folders.file_list.value[0],
                                  plugin='tifffile')
        image2 = skimage.io.imread(
            self.folders.cur_dir.as_posix() + '/' +
            os.path.splitext(self.folders.file_list.value[0])[0] +
            '_label.tif',
            plugin='tifffile')
        image3 = skimage.io.imread(
            self.folders.cur_dir.as_posix() + '/' +
            os.path.splitext(self.folders.file_list.value[0])[0] +
            '_region.tif',
            plugin='tifffile')

        scalez = 1024 / (int(self.scalingfactor.value))
        xy_extent = [0, 1024]
        #create ipyvolume figure
        with self.out:
            ipv.figure()
            self.volume_image = ipv.volshow(
                image[0, :, :, :, 1],
                extent=[xy_extent, xy_extent, [-scalez, scalez]],
                level=[0.3, 0.2, 0.2],
                opacity=[0.2, 0, 0],
                controls=False)
            self.volume_seg = ipv.plot_isosurface(
                np.swapaxes(image2 > 0, 0, 2),
                level=0.5,
                controls=False,
                color='green',
                extent=[xy_extent, xy_extent, [-scalez, scalez]])
            self.volume_reg = ipv.plot_isosurface(
                np.swapaxes(image3 > 0, 0, 2),
                level=0.5,
                controls=False,
                color='blue',
                extent=[xy_extent, xy_extent, [-scalez, scalez]])

            self.volume_reg.brightness = 10
            self.volume_image.brightness = 10
            self.volume_image.opacity = 100
            ipv.xyzlim(0, 1024)
            ipv.zlim(-500, 500)
            ipv.style.background_color('white')

            minval_data = ipw.IntSlider(min=0,
                                        max=255,
                                        value=255,
                                        description='min val')
            maxval_data = ipw.IntSlider(min=0,
                                        max=255,
                                        value=255,
                                        description='max val')
            brightness_data = ipw.FloatSlider(min=0,
                                              max=100,
                                              value=7.0,
                                              description='brightness')
            opacity_data = ipw.FloatSlider(min=0,
                                           max=100,
                                           value=7.0,
                                           description='opacity')
            level_data = ipw.FloatSlider(min=0,
                                         max=1,
                                         value=0.3,
                                         step=0.01,
                                         description='level')
            levelwidth_data = ipw.FloatSlider(min=0,
                                              max=1,
                                              value=0.1,
                                              step=0.01,
                                              description='level width')

            color = ColorPicker(description='Segmentation color')
            color2 = ColorPicker(description='Segmentation color')

            visible_seg = ipw.Checkbox()
            visible_reg = ipw.Checkbox()

            jslink((self.volume_image, 'show_min'), (minval_data, 'value'))
            jslink((self.volume_image, 'show_max'), (maxval_data, 'value'))
            jslink((self.volume_image, 'brightness'),
                   (brightness_data, 'value'))
            jslink((self.volume_image.tf, 'opacity1'), (opacity_data, 'value'))
            jslink((self.volume_image.tf, 'level1'), (level_data, 'value'))
            jslink((self.volume_image.tf, 'width1'),
                   (levelwidth_data, 'value'))
            jslink((self.volume_seg, 'color'), (color, 'value'))
            jslink((self.volume_reg, 'color'), (color2, 'value'))
            jslink((self.volume_seg, 'visible'), (visible_seg, 'value'))
            jslink((self.volume_reg, 'visible'), (visible_reg, 'value'))
            ipv.show()

            image_controls = HBox([
                VBox([minval_data, maxval_data]),
                VBox([
                    brightness_data, opacity_data, level_data, levelwidth_data
                ])
            ])
            display(
                VBox([
                    HBox([color, visible_seg]),
                    HBox([color2, visible_reg]), image_controls
                ]))
Ejemplo n.º 16
0
def animate_in_space(
    position_interpolator,
    n_step=200,
    show_detector_pointing=False,
    show_earth=True,
    show_sun=False,
    show_moon=False,
    background_color="#01000F",
    detector_scaling_factor=20000.0,
    show_stars=False,
    show_inactive=False,
    earth_time="night",
    realistic=True,
    interval=200,
):
    """
    Animiate fermi in Space!

    :param position_interpolator: 
    :param n_step: 
    :param show_detector_pointing: 
    :param show_earth: 
    :param show_sun: 
    :param show_moon: 
    :param background_color: 
    :param detector_scaling_factor: 
    :param show_stars: 
    :returns: 
    :rtype: 

    """

    fig = ipv.figure()

    ipv.pylab.style.box_off()
    ipv.pylab.style.axes_off()
    ipv.pylab.style.set_style_dark()
    ipv.pylab.style.background_color(background_color)

    tmin, tmax = position_interpolator.minmax_time()

    time = np.linspace(tmin, tmax, n_step)

    artists = []

    distances = [15000]

    if show_earth:

        astro_times = [position_interpolator.astro_time(t) for t in time]

        earth = Earth(
            earth_time=earth_time, realistic=realistic, astro_time=astro_times,
        )

        tmp = earth.plot()

        if realistic:
            artists.append(tmp)

    if show_sun:

        xs = []
        ys = []
        zs = []

        for t in time:

            sun_pos = position_interpolator.sun_position(t)
            x, y, z = sun_pos.cartesian.xyz.to("km").value

            xs.append(x)
            ys.append(y)
            zs.append(z)

        sol = Sol(np.array(xs), np.array(ys), np.array(zs))

        distances.append(compute_distance(x, y, z, sol.radius))

        artists.append(sol.plot())

    if show_moon:

        xs = []
        ys = []
        zs = []

        for t in time:

            moon_pos = position_interpolator.moon_position(t)
            x, y, z = moon_pos.cartesian.xyz.to("km").value

            xs.append(x)
            ys.append(y)
            zs.append(z)

        moon = Moon(np.array(xs), np.array(ys), np.array(zs))
        distances.append(compute_distance(x, y, z, moon.radius))
        artists.append(moon.plot())

    # now get fermi position
    sxs = []
    sys = []
    szs = []

    x_off = []
    y_off = []
    z_off = []

    if show_detector_pointing:

        distances.append(detector_scaling_factor)

        gbm = GBM(
            position_interpolator.quaternion(tmin), position_interpolator.sc_pos(tmin),
        )

        dets_xo = {}
        dets_yo = {}
        dets_zo = {}
        dets_xp = {}
        dets_yp = {}
        dets_zp = {}

        for k, _ in gbm.detectors.items():

            dets_xo[k] = []
            dets_yo[k] = []
            dets_zo[k] = []
            dets_xp[k] = []
            dets_yp[k] = []
            dets_zp[k] = []

    for t in time:

        sx, sy, sz = position_interpolator.sc_pos(t)

        sxs.append(sx)
        sys.append(sy)
        szs.append(sz)

        if not position_interpolator.is_fermi_active(t):
            x_off.append(sx)
            y_off.append(sy)
            z_off.append(sz)

        if show_detector_pointing:

            gbm.set_quaternion(position_interpolator.quaternion(t))

            for k, v in gbm.detectors.items():

                x, y, z = v.center_icrs.cartesian.xyz.value * max(distances)

                dets_xo[k].append(sx)
                dets_yo[k].append(sy)
                dets_zo[k].append(sz)
                dets_xp[k].append(sx + x)
                dets_yp[k].append(sy + y)
                dets_zp[k].append(sz + z)

    if show_detector_pointing:

        for k, v in gbm.detectors.items():

            dets_xo[k] = np.array(dets_xo[k])
            dets_yo[k] = np.array(dets_yo[k])
            dets_zo[k] = np.array(dets_zo[k])
            dets_xp[k] = np.array(dets_xp[k])
            dets_yp[k] = np.array(dets_yp[k])
            dets_zp[k] = np.array(dets_zp[k])

            color = _det_colors[k]

            cone = Cone(
                dets_xo[k],
                dets_yo[k],
                dets_zo[k],
                dets_xp[k],
                dets_yp[k],
                dets_zp[k],
                _open_angle,
            )
            artists.append(cone.plot(color=color))

    #            artists.append(ipv.pylab.plot(dets_x[k], dets_y[k], dets_z[k], color=color))

    sxs = np.array(sxs)
    sys = np.array(sys)
    szs = np.array(szs)
    if show_inactive:

        ipv.pylab.scatter(
            np.array(x_off),
            np.array(y_off),
            np.array(z_off),
            color="#DC1212",
            alpha=0.5,
            marke="circle_2d",
            size=1,
        )

    # fermi = FermiPoint(sxs, sys, szs)
    # artists.append(fermi.plot())

    fermi_real = Fermi(
        position_interpolator.quaternion(time),
        sc_pos=position_interpolator.sc_pos(time),
        transform_to_space=True,
    )
    artists.extend(fermi_real.plot_fermi_ipy())

    if show_stars:

        sf = StarField(n_stars=200, distance=max(distances) - 2)
        sf.plot()

    ipv.xyzlim(max(distances))

    ipv.animation_control(artists, interval=interval)

    ipv.show()

    return fig
Ejemplo n.º 17
0
def plot_in_space(
    position_interpolator,
    time,
    show_detector_pointing=False,
    show_earth=True,
    show_sun=False,
    show_moon=False,
    background_color="#01000F",
    detector_scaling_factor=20000.0,
    show_stars=False,
    show_orbit=True,
    realistic=True,
    earth_time="night",
    sky_points=None,
    min_distance=8000,
):
    """
    Plot Fermi in Space!

    :param position_interpolator: 
    :param time: 
    :param show_detector_pointing: 
    :param show_earth: 
    :param show_sun: 
    :param show_moon: 
    :param background_color: 
    :param detector_scaling_factor: 
    :returns: 
    :rtype: 

    """

    fig = ipv.figure(width=800, height=600)

    ipv.pylab.style.box_off()
    ipv.pylab.style.axes_off()
    ipv.pylab.style.set_style_dark()
    ipv.pylab.style.background_color(background_color)

    distances = [min_distance]

    if sky_points is not None:
        sky_points = np.atleast_1d(sky_points)

    if show_orbit:

        tmin, tmax = position_interpolator.minmax_time()
        tt = np.linspace(tmin, tmax, 500)

        sc_pos = position_interpolator.sc_pos(tt)

        ipv.plot(sc_pos[:, 0], sc_pos[:, 1], sc_pos[:, 2], lw=0.5)

    if show_earth:

        earth = Earth(
            earth_time=earth_time,
            realistic=realistic,
            astro_time=position_interpolator.astro_time(time),
        )

        earth.plot()

    if show_sun:

        sun_pos = position_interpolator.sun_position(time)
        x, y, z = sun_pos.cartesian.xyz.to("km").value

        sol = Sol(x, y, z)
        distances.append(compute_distance(x, y, z, sol.radius))
        sol.plot()

    if show_moon:

        moon_pos = position_interpolator.moon_position(time)
        x, y, z = moon_pos.cartesian.xyz.to("km").value

        moon = Moon(x, y, z, realistic=True)
        distances.append(compute_distance(x, y, z, moon.radius))
        moon.plot()

    # now get fermi position

    sx, sy, sz = position_interpolator.sc_pos(time)

    fermi_real = Fermi(
        position_interpolator.quaternion(time),
        sc_pos=position_interpolator.sc_pos(time),
        transform_to_space=True,
    )
    fermi_real.plot_fermi_ipy()

    if show_detector_pointing:

        distances.append(detector_scaling_factor)

        gbm = GBM(
            position_interpolator.quaternion(time), position_interpolator.sc_pos(time),
        )

        for k, v in gbm.detectors.items():
            x, y, z = v.center_icrs.cartesian.xyz.value * max(distances)

            # x_line = np.array([sx, sx + x])
            # y_line = np.array([sy, sy + y])
            # z_line = np.array([sz, sz + z])

            color = _det_colors[k]

            cone = Cone(sx, sy, sz, sx + x, sy + y, sz + z, _open_angle)
            cone.plot(color=color)

            # ipv.pylab.plot(x_line, y_line, z_line, color=color)

    if sky_points is not None:
        for sp in sky_points:

            sp.plot(sx, sy, sz, max(distances))

            # distances.append(sp.distance)

    if show_stars:

        sf = StarField(n_stars=100, distance=max(distances) - 2)
        sf.plot()

    # move the camera here

    fig.camera.position = tuple(
        position_interpolator.sc_pos(time)
        / np.linalg.norm(position_interpolator.sc_pos(time))
    )

    ipv.xyzlim(max(distances))

    ipv.show()

    return fig
Ejemplo n.º 18
0
    def display(
        self,
        earth_time="day",
        obs_time="2010-01-01T00:00:00",
        names=None,
        size=10,
        color="yellow",
    ):

        fig = ipv.figure()
        ipv.pylab.style.box_off()
        ipv.pylab.style.axes_off()
        ipv.pylab.style.set_style_dark()
        ipv.pylab.style.background_color("black")

        tt = atime.Time(obs_time)

        earth = Earth(earth_time=earth_time, realistic=True, astro_time=tt,)

        earth.plot()

        x = []
        y = []
        z = []

        distances = []

        for name, sat in self._satellites.items():

            add_sat = False

            if names is not None:

                if name in names:

                    add_sat = True
            else:

                add_sat = True

            if add_sat:

                x.append(sat.xyz[0])
                y.append(sat.xyz[1])
                z.append(sat.xyz[2])

                distances.append(sat.true_alt)

        ipv.pylab.scatter(
            np.array(x),
            np.array(y),
            np.array(z),
            marker="sphere",
            color=color,
            size=size,
        )

        ipv.xyzlim(max(distances))

        ipv.show()

        return fig
import ipyvolume
import ipyvolume as ipv
import vaex

ds = vaex.example()
N = 1000

ipv.figure()
quiver = ipv.scatter(ds.data.x[:N], ds.data.y[:N], ds.data.z[:N])
ipv.xyzlim(-30,30)
ipv.show()