Beispiel #1
0
def plot_mesh(value_mesh_list, w1_mesh, w2_mesh, save, show_box, show_axes):
    ipv.clear()
    figs = []
    for mesh in value_mesh_list:
        fig = ipv.pylab.figure()
        fig.camera.up = (0, 0, 1)
        fig.camera.position = (-2, 1, -0.5)
        fig.camera_control = "trackball"
        if not show_axes:
            ipv.style.box_off()
        else:
            ipv.xlabel("w1")
            ipv.ylabel("w2")
            ipv.zlabel("f_lambda")
        if not show_box:
            ipv.pylab.style.axes_off()

        ipv.pylab.zlim(mesh.min(), mesh.max())
        ptp = (mesh - mesh.min()).ptp()

        col = []
        for m in mesh:
            znorm = (m - m.min()) / (m.max() - m.min() + 1e-8)
            color = np.asarray([[interpolate(darker(colors_alpha[0], 1.5 * x + 0.75),
                                             darker(colors_alpha[1], 1.5 * (1 - x) + 0.75), x) for x in y] for y in
                                znorm])
            col.append(color)
        color = np.array(col)
        surf = ipv.plot_surface(w1_mesh, w2_mesh, mesh, color=color[..., :3])
        ipv.animation_control(surf, interval=400)
        figs.append(fig)
        ipv.show()
    if save:
        ipv.save(f'renders/{datetime.datetime.now().strftime("%m%d-%H%M")}.html', offline=True)
    return figs
def ipv_animate(particles, velocities, particleColors, particleSizes,
                paramRanges):

    nTimesteps = particles.shape[0]
    nParticles = particles.shape[1]

    # determine quiver sizes and colors
    veloQuiverSizes = np.zeros((nTimesteps, nParticles, 1))
    for iTimestep in range(nTimesteps):
        veloQuiverSizes[iTimestep, :,
                        0] = np.linalg.norm(velocities[iTimestep, :, :],
                                            axis=1)
    veloQuiverSizes = np.clip(veloQuiverSizes, 0, 2)
    quiverColors = np.ones(
        (nTimesteps, nParticles, 4)) * .8  #veloQuiverSizes/3

    ipv.figure()
    #bPlots = ipv.scatter( best[:, :, 0],  best[:, :, 1],  best[:, :, 2], marker = 'sphere', size=2, color = 'red' )
    pPlots = ipv.scatter(particles[:, :, 0],
                         particles[:, :, 1],
                         particles[:, :, 2],
                         marker='sphere',
                         size=particleSizes,
                         color=particleColors)
    #qvPlots = ipv.quiver( particles[:, :, 0], particles[:, :, 1], particles[:, :, 2], velocities[:, :, 0], velocities[:, :, 1], velocities[:, :, 2], size=veloQuiverSizes[:,:,0]*3, color=quiverColors)

    ipv.animation_control([pPlots], interval=600)
    ipv.xlim(paramRanges[0][1], paramRanges[0][2])
    ipv.ylim(paramRanges[1][1], paramRanges[1][2])
    ipv.zlim(paramRanges[2][1], paramRanges[2][2])

    ipv.show()
    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()
def particleSimulate(num_particles,
                     box_size,
                     total_time,
                     time_step,
                     particle_radius,
                     grav=False,
                     save=False):

    print("Running simulation...")
    """Run the simulation and extract the x,y,z coordinates to plot the particle's path"""
    particle_list = initialize_particles(num_particles, box_size, time_step,
                                         grav)  #Generate starting points

    x = np.zeros([total_time, num_particles, 1])
    y = np.zeros([total_time, num_particles, 1])
    z = np.zeros([total_time, num_particles, 1])

    time = 0

    #print(str(tot_eng(particle_list))) #Used to track the total energy of the particles

    while time < total_time:  #Loop through iterations of particle movements

        #Check to see if bouncing occurs
        isbounce(particle_list, particle_radius, time_step)

        for i in range(len(particle_list)):
            particle_list[i].pos_update(time_step)  #Update position

            x[time, i] = particle_list[i].pos[0]
            y[time, i] = particle_list[i].pos[1]
            z[time, i] = particle_list[i].pos[2]

        time += 1

        if (time / total_time) * 100 % 10 == 0:
            print(str(time / total_time * 100) + "% complete")
    """Plot the results of all of the particle movements"""

    colors = []
    for i in range(num_particles):
        colors.append(
            [np.random.random(),
             np.random.random(),
             np.random.random()])

    ipv.figure()
    s = ipv.scatter(x, z, y, color=colors, size=7, marker="sphere")
    ipv.animation_control(s, interval=1)
    ipv.xlim(-1, box_size + 1)
    ipv.ylim(-1, box_size + 1)
    ipv.zlim(-1, box_size + 1)

    ipv.style.axes_off()
    ipv.show()

    if save == True:
        print("Saving the video of the simulation in the current directory...")
        ipv.save('./particle_sim.html')
Beispiel #5
0
def brain(draw=True, show=True, fiducial=True, flat=True, inflated=True, subject='S1', interval=1000, uv=True, color=None):
    import ipyvolume as ipv
    try:
        import cortex
    except:
        warnings.warn("it seems pycortex is not installed, which is needed for this example")
        raise
    xlist, ylist, zlist = [], [], []
    polys_list = []
    def add(pts, polys):
        xlist.append(pts[:,0])
        ylist.append(pts[:,1])
        zlist.append(pts[:,2])
        polys_list.append(polys)
    def n(x):
        return (x - x.min()) / x.ptp()
    if fiducial or color is True:
        pts, polys = cortex.db.get_surf('S1', 'fiducial', merge=True)
        x, y, z = pts.T
        r = n(x)
        g = n(y)
        b = n(z)
        if color is True:
            color = np.array([r,g,b]).T.copy()
        else:
            color = None
        if fiducial:
            add(pts, polys)
    else:
        if color is False:
            color = None
    if inflated:
        add(*cortex.db.get_surf('S1', 'inflated', merge=True, nudge=True))
    u = v = None
    if flat or uv:
        pts, polys = cortex.db.get_surf('S1', 'flat', merge=True, nudge=True)
        x, y, z = pts.T
        u = n(x)
        v = n(y)
        if flat:
            add(pts, polys)

    polys_list.sort(key=lambda x: len(x))
    polys = polys_list[0]
    if draw:
        if color is None:
            mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, u=u, v=v)
        else:
            mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, color=color, u=u, v=v)
        if show:
            if len(x) > 1:
                ipv.animation_control(mesh, interval=interval)
            ipv.squarelim()
            ipv.show()
        return mesh
    else:
        return xlist, ylist, zlist, polys
Beispiel #6
0
def aniplot(folder, frame):
    if frame is None:
        frame = len(
            fnmatch.filter(os.listdir('/u/yali/' + folder + '/test/output'),
                           '*.hdf5'))

    x = []
    y = []
    z = []
    vx = []
    vy = []
    vz = []
    v = []

    for i in np.arange(frame):
        fname = str(format(i, '03d'))
        f = h5py.File("/u/yali/" + folder + "/test/output/snapshot_" + fname +
                      ".hdf5", 'r')  # Read-only access to the file
        #intE = []
        #density = []
        x.append(f['PartType0']['Coordinates'][:, 0])
        y.append(f['PartType0']['Coordinates'][:, 1])
        z.append(f['PartType0']['Coordinates'][:, 2])
        #intE.append(f['Partype0']['InternalEnergy'][:])
        vx.append(f['PartType0']['Velocities'][:, 0])
        vy.append(f['PartType0']['Velocities'][:, 1])
        vz.append(f['PartType0']['Velocities'][:, 2])
        #density.append(f['PartType0']['Density'][:])

    # and normalize
    x = np.array(x)
    y = np.array(y)
    z = np.array(z)
    vx = np.array(vx)
    vy = np.array(vy)
    vz = np.array(vz)
    v = np.array(np.sqrt(vx**2 + vy**2 + vz**2))
    v -= v.min()
    v /= v.max()

    # map the normalized values to rgba colors
    cmap = cm.Reds
    colors = np.array([cmap(k) for k in v])
    colors.shape

    # plot animation
    fig = ipv.figure()
    ipv.style.use('dark')
    # use just rgb colors, not rgba
    quiver = ipv.quiver(x, y, z, vx, vy, vz, size=5, color=colors[:, :, :3])
    # create the animation widgets/slider
    ipv.animation_control(quiver, interval=500)
    ipv.show()
Beispiel #7
0
def animate_rollout_quiver(positions, vector):
    """Takes positions & vector(acceleration or velocity) and renders 3d quiver animation"""
    num_steps = len(positions)
    num_particles = positions[0].size(0)
    data = np.zeros((6, num_steps, num_particles))
    for s in range(num_steps):
        pos = positions[s].numpy()
        v = vector[s].numpy()
        for i in range(3):
            data[i][s] = pos[:, i]
            data[i + 3][s] = v[:, i]
    fig = ipv.figure()
    color = [(1, 0, 0) if i < 64 else (0, 0, 1) for i in range(len(pos))]
    s = ipv.quiver(*data, color=color, size=5)
    ipv.animation_control(s)
    ipv.show()
Beispiel #8
0
def animate_rollout(rollout):
    """Takes rollout positions and renders a 3d animation"""
    x, y, z = [], [], []
    for i, step in enumerate(rollout):
        pos = step.numpy()
        x.append(pos[:, 0])
        y.append(pos[:, 1])
        z.append(pos[:, 2])

    fig = ipv.figure()
    color = [(1, 0, 0) if i < 64 else (0, 0, 1) for i in range(len(pos))]
    s = ipv.scatter(np.array(x),
                    np.array(y),
                    np.array(z),
                    color=color,
                    size=5,
                    marker='sphere')
    ipv.animation_control(s)
    ipv.show()
def plot_particle_learning(nTimesteps, nParticles, testData_pDF,
                           bestParamIndex, predictionHistory):

    nTestSamples = testData_pDF.shape[0]
    colorStack = np.ones(
        (nTimesteps, nParticles, nTestSamples, 4)) * [1, 0, 0, 1]
    for iTimestep in range(nTimesteps):
        for iParticle in range(nParticles):
            colorStack[iTimestep, iParticle, :,
                       0] = predictionHistory[iTimestep, iParticle, :]

    nTestSamples = testData_pDF.shape[0]
    testDataRepeated = np.zeros((nTimesteps, nParticles, nTestSamples, 3))
    xNP = testData_pDF['x'].values
    yNP = testData_pDF['y'].values
    zNP = testData_pDF['z'].values
    for iTimestep in range(nTimesteps):
        for iParticle in range(nParticles):
            testDataRepeated[iTimestep, iParticle, :, 0] = xNP
            testDataRepeated[iTimestep, iParticle, :, 1] = yNP
            testDataRepeated[iTimestep, iParticle, :, 2] = zNP

    ipv.figure()
    nTimestepsToPlot = bestParamIndex[0] + 1
    bestParticle = bestParamIndex[1]

    predictionPlots = ipv.scatter(testDataRepeated[0:nTimestepsToPlot,
                                                   bestParticle, :, 0],
                                  testDataRepeated[0:nTimestepsToPlot,
                                                   bestParticle, :, 1],
                                  testDataRepeated[0:nTimestepsToPlot,
                                                   bestParticle, :, 2],
                                  color=colorStack[0:nTimestepsToPlot,
                                                   bestParticle, :, :],
                                  marker='sphere',
                                  size=.25)

    ipv.animation_control([predictionPlots], interval=600)
    ipv.pylab.squarelim()
    ipv.show()
    '''
def hpo_animate(particles,
                particleSizes,
                particleColors,
                paramRanges,
                nTimesteps=1):
    nParticles = particles.shape[1]
    colorStack = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .9
    colorStackLines = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .5
    for iTimestep in range(nTimesteps):
        colorStack[iTimestep, :,
                   0:3] = numpy.matlib.repmat(particleColors[0, :, :],
                                              nTimesteps, 1)
        colorStackLines[iTimestep, :,
                        0:3] = numpy.matlib.repmat(particleColors[0, :, :],
                                                   nTimesteps, 1)
        colorStackLines[iTimestep, :, 3] = .6  # alpha
    ipv.figure()

    pplot = ipv.scatter(particles[0:nTimesteps, :, 0],
                        particles[0:nTimesteps, :, 1],
                        particles[0:nTimesteps, :, 2],
                        marker='sphere',
                        size=particleSizes,
                        color=colorStack[:, :, :])

    for iParticle in range(nParticles):
        plines = ipv.plot(particles[0:nTimesteps, iParticle, 0],
                          particles[0:nTimesteps, iParticle, 1],
                          particles[0:nTimesteps, iParticle, 2],
                          color=colorStackLines[:, iParticle, :])

    ipv.animation_control([pplot], interval=600)
    ipv.xlim(paramRanges[0][1] - .5, paramRanges[0][2] + .5)
    ipv.ylim(paramRanges[1][1] - .1, paramRanges[1][2] + .1)
    ipv.zlim(paramRanges[2][1] - .1, paramRanges[2][2] + .1)
    ipv.show()
Beispiel #11
0
    def __init__(self, brain):
        if brain.data['time'] is None:
            raise ValueError('Brain class instance does not have time data.')

        self._brain = brain
        time = brain.data['time']
        time_idx = brain.data['time_idx']
        overlays = tuple(brain.overlays.values())
        control = ipv.animation_control(overlays,
                                        len(time),
                                        add=False,
                                        interval=500)
        slider = control.children[1]
        slider.readout = False
        slider.value = time_idx
        label = widgets.Label(self._get_label(time[time_idx]))

        # hadler for changing of selected time moment
        def slider_handler(change):
            k = brain.data['k']
            b = brain.data['b']
            lut = brain.data['lut']
            time_idx_new = int(change.new)

            for v in brain.views:
                for h in brain.hemis:
                    act_data = brain.data[h + '_array'][:, time_idx_new]
                    smooth_mat = brain.data[h + '_smooth_mat']
                    act_data = smooth_mat.dot(act_data)
                    act_data = k * act_data + b
                    act_data = np.clip(act_data, 0, 1)
                    act_color_new = lut(act_data)
                    brain.overlays[h + '_' + v].color = act_color_new

            # change label value
            label.value = self._get_label(time[time_idx_new])

        slider.observe(slider_handler, names='value')
        control = widgets.HBox((*control.children, label))
        ipv.gcc().children += (control,)
Beispiel #12
0
def test_animation_control():
    fig = ipv.figure()
    n_points = 3
    n_frames = 4
    ar = np.zeros(n_points)
    ar_frames = np.zeros((n_frames, n_points))
    colors = np.zeros((n_points, 3))
    colors_frames = np.zeros((n_frames, n_points, 3))
    scalar = 2

    s = ipv.scatter(x=scalar, y=scalar, z=scalar)
    with pytest.raises(ValueError):  # no animation present
        slider = ipv.animation_control(s, add=False).children[1]

    s = ipv.scatter(x=ar, y=scalar, z=scalar)
    slider = ipv.animation_control(s, add=False).children[1]
    assert slider.max == n_points - 1

    s = ipv.scatter(x=ar_frames, y=scalar, z=scalar)
    slider = ipv.animation_control(s, add=False).children[1]
    assert slider.max == n_frames - 1

    s = ipv.scatter(x=scalar, y=scalar, z=scalar, color=colors_frames)
    slider = ipv.animation_control(s, add=False).children[1]
    assert slider.max == n_frames - 1

    Nx, Ny = 10, 7
    x = np.arange(Nx)
    y = np.arange(Ny)
    x, y = np.meshgrid(x, y)
    z = x + y
    m = ipv.plot_surface(x, y, z)
    with pytest.raises(ValueError):  # no animation present
        slider = ipv.animation_control(m, add=False).children[1]


    z = [x + y * k for k in range(n_frames)]
    m = ipv.plot_surface(x, y, z)
    slider = ipv.animation_control(m, add=False).children[1]
    assert slider.max == n_frames - 1
Beispiel #13
0
    def visualize_objects(self,
                          train_idxs=None,
                          test_idxs=None,
                          max_time_steps=None,
                          train_sim=False,
                          test_sim=True,
                          train_marker_size=4,
                          test_marker_size=6):
        """
            train_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки,
                         которые надо визуализировать. Если  None - берем все объекты
                         
            test_idxs - numpy array из индексов объектов (sat_id) тренировочной выборки,
                         которые надо визуализировать. Если None - берем train_idxs
                         
            max_time_steps - максимальное количество измерений для одного объекта (sat_id)
            
            train_sim - если False - используем реальные данные (колонки без приставки sim)
            
            test_sim - если False - используем реальные (предсказанные) данные 
            (для этого в датафрейм нужно добавить приставки колонки с предсказаниями без приставки sim,
             как в трейне)
            
        """

        ipv.clear()
        if train_idxs is None:
            train_idxs = np.array(self.train_data['sat_id'].unique())
        if test_idxs is None:
            test_idxs = train_idxs

        if max_time_steps is None:
            max_time_steps_train = self.train_data.groupby(
                'sat_id').count()['epoch'].max()
            max_time_steps_test = self.test_data.groupby(
                'sat_id').count()['epoch'].max()
            max_time_steps = max(max_time_steps_train, max_time_steps_test)

        ## подготовка трейна и теста
        stream_train = self._prepare_stream('train', train_idxs,
                                            max_time_steps, train_sim)
        stream_test = self._prepare_stream('test', test_idxs, max_time_steps,
                                           test_sim)

        ## визуализация
        stream = np.dstack([stream_train[:, :, :], stream_test[:, :, :]])
        selected = stream_train.shape[2] + test_idxs
        self.q = ipv.quiver(*stream[:, :, :],
                            color="green",
                            color_selected='red',
                            size=train_marker_size,
                            size_selected=test_marker_size,
                            selected=selected)

        ##  Чтобы можно было менять размеры и цвета
        size = FloatSlider(min=1, max=15, step=0.2)
        size_selected = FloatSlider(min=1, max=15, step=0.2)
        color = ColorPicker()
        color_selected = ColorPicker()
        jslink((self.q, 'size'), (size, 'value'))
        jslink((self.q, 'size_selected'), (size_selected, 'value'))
        jslink((self.q, 'color'), (color, 'value'))
        jslink((self.q, 'color_selected'), (color_selected, 'value'))
        #         ipv.style.use('seaborn-darkgrid')
        ipv.animation_control(self.q, interval=75)
        ipv.show(
            [VBox([ipv.gcc(), size, size_selected, color, color_selected])])
Beispiel #14
0
def viz_swarm(swarm, paramLabels=False):
    swarmDF, particleHistory = viz_prep(swarm)

    particleHistoryCopy = copy.deepcopy(particleHistory)
    nParticles = swarm.nParticles

    nAnimationFrames = list(
        swarmDF['nEvals'])[0]  # max( sortedBarHeightsDF['nEvals'] )
    particleXYZ = np.zeros((nAnimationFrames, nParticles, 3))
    lastKnownLocation = {}

    # TODO: bestIterationNTrees
    # particleSizes[ iFrame, iParticle ] = particleHistoryCopy[iParticle]['bestIterationNTrees'].pop(0).copy()

    for iFrame in range(nAnimationFrames):
        for iParticle in range(nParticles):

            if iParticle in particleHistoryCopy.keys():
                # particle exists in the particleHistory and it has parameters for the current frame
                if len(particleHistoryCopy[iParticle]):
                    particleXYZ[iFrame, iParticle, :] = particleHistoryCopy[
                        iParticle].pop(0).copy()
                    lastKnownLocation[iParticle] = particleXYZ[
                        iFrame, iParticle, :].copy()
                else:
                    # particle exists but it's params have all been popped off -- use its last known location
                    if iParticle in lastKnownLocation.keys():
                        particleXYZ[iFrame, iParticle, :] = lastKnownLocation[
                            iParticle].copy()

            else:
                # particle does not exist in the particleHistory
                if iParticle in lastKnownLocation.keys():
                    # particle has no params in current frame, attempting to use last known location
                    particleXYZ[
                        iFrame,
                        iParticle, :] = lastKnownLocation[iParticle].copy()
                else:
                    print('particle never ran should we even display it')
                    assert (False)
                    # using initial params
                    #particleXYZ[iFrame, iParticle, : ] = initialParticleParams[iParticle].copy()
                    #lastKnownLocation[iParticle] = particleXYZ[iFrame, iParticle, : ].copy()

    ipvFig = ipv.figure(width=ipvPlotWidth, height=ipvPlotHeight)

    scatterPlots = ipv.scatter(particleXYZ[:, :, 0],
                               particleXYZ[:, :, 1],
                               particleXYZ[:, :, 2],
                               marker='sphere',
                               size=5,
                               color=swarm.particleColorStack)

    xyzLabelsButton = widgets.Button(description="x, y, z labels")
    paramNamesLabelsButton = widgets.Button(description="parameter labels")

    ipv.animation_control([scatterPlots], interval=400)
    ipv.xlim(swarm.paramRanges[0][1] - .5, swarm.paramRanges[0][2] + .5)
    ipv.ylim(swarm.paramRanges[1][1] - .1, swarm.paramRanges[1][2] + .1)
    ipv.zlim(swarm.paramRanges[2][1] - .1, swarm.paramRanges[2][2] + .1)

    container = ipv.gcc()
    container.layout.align_items = 'center'
    comboBox = append_label_buttons(swarm, ipvFig, container)
    display(comboBox)
Beispiel #15
0
%pylab inline
import ipyvolume as ipv
import ipyvolume.pylab as p3
import numpy as np
import rebound
from rebound import hash as h

from astropy.io import ascii

p3.clear()
##Location of npz files produced by other script
loc="./"
x=np.load(loc+'x.npz')
y=np.load(loc+'y.npz')
z=np.load(loc+'z.npz')

s2=p3.plot(x['arr_0'], y['arr_0'], z['arr_0'])
# s3=p3.plot(x['arr_0'][:, 1, :], y['arr_0'][:, 1, :], z['arr_0'][:, 1, :], color='red', size=0.3, alpha='0.5')

ipv.pylab.xlim(-1,1)
ipv.pylab.ylim(-1,1)
ipv.pylab.zlim(-1,1)
ipv.pylab.view(azimuth=None, elevation=-90, distance=1.5)

p3.show()
ipv.animation_control(s2)
Beispiel #16
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()
Beispiel #17
0
import ipyvolume as ipv
import numpy as np
import ipywidgets as widgets
from ipyvolume.widgets import quickscatter
from ipyvolume.widgets import Figure
import numpy as np, pandas as pd

np.random.seed(0)
import seaborn as sns

sns.set(style="white", color_codes=True)

# In[74]:

x = np.array(margin)
y = np.array(gp)
z = np.array(spread_to_const)

# In[76]:

ipv.figure()
s = ipv.scatter(x, y, z, marker='sphere', size=2)

ipv.pylab.xlabel('Margin')
ipv.pylab.ylabel('GP')
ipv.pylab.zlabel('Var to Const')

ipv.animation_control(s)  # shows controls for animation controls
ipv.show()
Beispiel #18
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