Esempio n. 1
0
def plot_uncertainty(filename, img_path="/tmp/diss_explore", show=True):
    """Compute the sum of uncertainty and plot as function of time"""

    with h5py.File(filename, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']

        # get all the keys for the groups
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))
    
        t_array = []
        w_array = []

        for ii, wk in enumerate(w_keys):
            t_array.append(ii)
            w_array.append(np.sum(rw[wk][()]))

        t_array = np.array(t_array)
        w_array = np.array(w_array)

        print(w_array[-1])
    
    # now call the plotting function
    publication.plot_uncertainty(t_array, w_array, img_path=img_path, pgf_save=True,
                                 show=show)
Esempio n. 2
0
def exploration_generate_plots(data_path, img_path='/tmp/diss_explore', 
                               magnification=4, step=1, show=True):
    """Given a HDF5 file generated by explore (C++) this will generate some plots
    """

    if not os.path.exists(img_path):
        os.makedirs(img_path)

    with h5py.File(data_path, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']
        
        # get all the keys
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = np.squeeze(hf['initial_weight'][()])

        # determine the maximum extents of the mesh and add some margin
        scale = 1.25
        max_x = scale*np.max(v_initial[:, 0])
        min_x = scale*np.min(v_initial[:, 0])
        max_y = scale*np.max(v_initial[:, 1])
        min_y = scale*np.min(v_initial[:, 1])
        max_z = scale*np.max(v_initial[:, 2])
        min_z = scale*np.min(v_initial[:, 2])

        """Partial images during the reconstruction"""
        mfig = graphics.mayavi_figure(offscreen=(not show))
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)
        partial_index = np.array([0, v_keys.shape[0]*1/4, v_keys.shape[0]*1/2,
                                  v_keys.shape[0]*3/4, v_keys.shape[0]*4/4-1],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it 
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:,2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=magnification)
        
        """Plot the truth asteroid"""
        v_true = hf['truth_vertex'][()]
        f_true = hf['truth_faces'][()]
        ms.reset(x=v_true[:, 0], y=v_true[:, 1], z=v_true[:,2], triangles=f_true)
        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)
        graphics.mlab.savefig(os.path.join(img_path, 'truth.jpg' ), magnification=magnification)
Esempio n. 3
0
def plot_state_trajectory(filename):
    """Plot the state trajectory

    Plot state in 3D
    Plot state in cartesian map project
    """

    # load the hdf5
    with h5py.File(filename, 'r') as hf:
        state_group = hf['state']

        # get all the keys for the groups
        state_keys = np.array(utilities.sorted_nicely(list(state_group.keys())))
    
        t_array = np.zeros(len(state_keys))
        state_inertial_array = np.zeros((len(state_keys), 18))
        state_asteroid_array = np.zeros((len(state_keys), 18))

        for ii, sk in enumerate(state_keys):
            t_array[ii] = ii
            state_inertial_array[ii, :] = state_group[sk][()]
            state_asteroid_array[ii, :] = state_group[sk][()]

    
    # pass to the plotting function
    publication.plot_state(t_array, state_inertial_array, state_asteroid_array)
Esempio n. 4
0
def inertial_asteroid_landing_cpp_save(time,
                                       state,
                                       filename,
                                       mayavi_objects,
                                       output_path,
                                       move_cam=False,
                                       mesh_weight=False,
                                       magnification=1):
    """Animation for the landing portion 
    """
    mesh, com, time_text, weight_text = mayavi_objects

    fig = mlab.gcf()
    camera = fig.scene.camera

    ms = mesh.mlab_source
    ts = com.mlab_source

    with h5py.File(filename, 'r') as hf:
        v = hf['landing/vertices'][()]
        f = hf['landing/faces'][()]

        Ra_group = hf['landing/Ra']
        keys = np.array(utilities.sorted_nicely(list(Ra_group.keys())))

        ii = 0
        for (t, pos, Rb2i, key) in zip(time, state[:, 0:3], state[:, 6:15],
                                       keys):
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            new_vertices = Ra.dot(v.T).T
            new_faces = f

            time_text.trait_set(text="t: {:8.1f}".format(t))

            # option to change color of mesh_weight
            ms.set(x=new_vertices[:, 0],
                   y=new_vertices[:, 1],
                   z=new_vertices[:, 2],
                   triangles=new_faces)

            ts.set(x=pos[0], y=pos[1], z=pos[2])

            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(fig,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])
            filename = os.path.join(output_path, str(ii).zfill(7) + '.jpg')
            mesh.scene.disable_render = False
            graphics.mlab.savefig(filename, magnification=magnification)
            ii += 1
Esempio n. 5
0
def view_final_reconstruction(data_path):
    """View the final mesh after reconstruction"""
    with h5py.File(data_path, 'r') as hf:
        rv = hf['reconstructed_vertex']

        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))

        v = rv[v_keys[-1]][()]
        f = hf['initial_faces'][()]

        mfig = graphics.mayavi_figure()
        graphics.mayavi_addMesh(mfig, v, f)
Esempio n. 6
0
def plot_volume(filename, img_path="/tmp/diss_explore", show=True):
    """Compute the volume of the asteroid at each time step
    """
    with h5py.File(filename, 'r') as hf:
        rv_group = hf['reconstructed_vertex']
        f_initial = hf['initial_faces'][()]

        rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))

        t_array = np.zeros(len(rv_keys))
        vol_array = np.zeros(len(rv_keys))

        for ii, key in enumerate(rv_keys):
            t_array[ii] = ii
            vol_array[ii] = stats.volume(rv_group[key][()], f_initial)

        true_vertices = hf['truth_vertex'][()]
        true_faces = hf['truth_faces'][()]
        true_volume = stats.volume(true_vertices, true_faces)

    publication.plot_volume(t_array, vol_array, true_volume, img_path=img_path, pgf_save=True,
                            show=show)
Esempio n. 7
0
def asteroid_generate_plots(data_path,
                            img_path='/tmp/diss_reconstruct',
                            magnification=1,
                            step=10):
    """Given a HDF5 file this will read the data and create a bunch of plots/images
    """
    # check and create output directory if not existed
    if not os.path.exists(img_path):
        os.makedirs(img_path)

    with h5py.File(data_path, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']

        # get all the keys for the groups
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = hf['initial_weight'][()]
        """Partial images during the reconstruction"""
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=4)
        """Partial images using a colormap for the data"""
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig,
                                       v_initial,
                                       f_initial,
                                       color=None,
                                       colormap='viridis',
                                       scalars=w_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path,
                                    'partial_weights_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            w = rw[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mlab.savefig(filename, magnification=4)
        """Generate the completed shape at a variety of different angles"""
        # change the mesh to the finished mesh
        ms.reset(x=rv[v_keys[-1]][()][:, 0],
                 y=rv[v_keys[-1]][()][:, 1],
                 z=rv[v_keys[-1]][()][:, 2],
                 triangles=f_initial)
        elevation = np.array([30, -30])
        azimuth = np.array([0, 45, 135, 215, 315])

        for az, el in itertools.product(azimuth, elevation):
            filename = os.path.join(
                img_path, 'final_az=' + str(az) + '_el=' + str(el) + '.jpg')
            graphics.mayavi_view(fig=mfig, azimuth=az, elevation=el)
            graphics.mlab.savefig(filename, magnification=4)
        """Create a bunch of images for animation"""
        animation_path = os.path.join(img_path, 'animation')
        if not os.path.exists(animation_path):
            os.makedirs(animation_path)

        ms.reset(x=v_initial[:, 0],
                 y=v_initial[:, 1],
                 z=v_initial[:, 2],
                 triangles=f_initial,
                 scalars=w_initial)
        graphics.mayavi_view(mfig)
        for ii, vk in enumerate(v_keys[::step]):
            filename = os.path.join(animation_path, str(ii).zfill(7) + '.jpg')
            v = rv[vk][()]
            w = rw[str(vk)][()]
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mayavi_savefig(mfig,
                                    filename,
                                    magnification=magnification)

    return 0
Esempio n. 8
0
def inertial_asteroid_refinement_cpp_save(time,
                                          state,
                                          inertial_intersections,
                                          hdf5_file,
                                          mayavi_objects,
                                          move_cam=False,
                                          mesh_weight=False,
                                          output_path="/tmp/refinement",
                                          magnification=1):
    """Save the refinment process to a bunch of images"""
    mesh, com, pc_points, time_text, weight_text = mayavi_objects

    f = mlab.gcf()
    camera = f.scene.camera
    # get all the keys for the reconstructed vertices and faces

    # animate the rotation fo the asteroid
    ms = mesh.mlab_source
    ts = com.mlab_source
    # ast_xs = ast_axes[0].mlab_source
    # ast_ys = ast_axes[1].mlab_source
    # ast_zs = ast_axes[2].mlab_source

    # dum_xs = dum_axes[0].mlab_source
    # dum_ys = dum_axes[1].mlab_source
    # dum_zs = dum_axes[2].mlab_source

    pc_sources = pc_points.mlab_source

    with h5py.File(hdf5_file, 'r') as hf:
        # oriignal vertices
        est_initial_vertices = hf[
            'simulation_parameters/estimate_asteroid/initial_vertices'][()]
        num_vert = est_initial_vertices.shape[0]

        rv_group = hf['refinement/reconstructed_vertex']
        rf_group = hf['refinement/reconstructed_face']
        rw_group = hf['refinement/reconstructed_weight']
        Ra_group = hf['refinement/Ra']

        rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))
        ii = 0
        for (t, pos, Rb2i, ints, key) in zip(time, state[:, 0:3], state[:,
                                                                        6:15],
                                             inertial_intersections, rv_keys):
            # rotate teh asteroid
            # Ra = ast.rot_ast2int(t)
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            # parse out the vertices x, y, z
            # rotate the asteroid
            new_vertices = Ra.dot(rv_group[key][()].T).T
            new_faces = rf_group[key][()]
            new_weight = np.squeeze(rw_group[key][()])

            # store value for number of vertices
            # add current time
            time_text.trait_set(text="t: {:8.1f}".format(t))
            weight_text.trait_set(text="w: {:8.1f}".format(np.sum(new_weight)))

            # update asteroid
            if mesh_weight:
                # check if size is different than the last mesh
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces,
                             scalars=new_weight)
                    num_vert = new_vertices.shape[0]
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces,
                           scalars=new_weight)
            else:
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces)
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces)

            # update the satellite
            ts.set(x=pos[0], y=pos[1], z=pos[2])

            # update the camera view to be right behind the satellite
            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(f,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])

            pc_sources.set(x=ints[:, 0], y=ints[:, 1], z=ints[:, 2])

            mesh.scene.disable_render = False
            filename = os.path.join(output_path, str(ii).zfill(7) + '.jpg')
            graphics.mlab.savefig(filename, magnification=magnification)
            ii += 1
Esempio n. 9
0
def inertial_asteroid_trajectory_cpp(time,
                                     state,
                                     inertial_intersections,
                                     hdf5_file,
                                     mayavi_objects,
                                     move_cam=False,
                                     mesh_weight=False):
    """Animate the rotation of an asteroid and the motion of SC

    This assumes an asteroid object from C++ and using the exploration sim
    """
    # pdb.set_trace()
    # mesh, ast_axes, com, dum_axes, pc_lines = mayavi_objects
    mesh, com, pc_points, time_text, weight_text = mayavi_objects

    f = mlab.gcf()
    camera = f.scene.camera
    # get all the keys for the reconstructed vertices and faces

    # animate the rotation fo the asteroid
    ms = mesh.mlab_source
    ts = com.mlab_source
    # ast_xs = ast_axes[0].mlab_source
    # ast_ys = ast_axes[1].mlab_source
    # ast_zs = ast_axes[2].mlab_source

    # dum_xs = dum_axes[0].mlab_source
    # dum_ys = dum_axes[1].mlab_source
    # dum_zs = dum_axes[2].mlab_source

    pc_sources = pc_points.mlab_source

    with h5py.File(hdf5_file, 'r') as hf:
        # oriignal vertices
        est_initial_vertices = hf[
            'simulation_parameters/estimate_asteroid/initial_vertices'][()]
        num_vert = est_initial_vertices.shape[0]

        rv_group = hf['reconstructed_vertex']
        rf_group = hf['reconstructed_face']
        rw_group = hf['reconstructed_weight']
        Ra_group = hf['Ra']

        rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))

        for (t, pos, Rb2i, ints, key) in zip(time, state[:, 0:3], state[:,
                                                                        6:15],
                                             inertial_intersections, rv_keys):
            # rotate teh asteroid
            # Ra = ast.rot_ast2int(t)
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            # parse out the vertices x, y, z
            # rotate the asteroid
            new_vertices = Ra.dot(rv_group[key][()].T).T
            new_faces = rf_group[key][()]
            new_weight = np.squeeze(rw_group[key][()])

            # store value for number of vertices
            # add current time
            time_text.trait_set(text="t: {:8.1f}".format(t))
            weight_text.trait_set(text="w: {:8.1f}".format(np.sum(new_weight)))

            # update asteroid
            if mesh_weight:
                # check if size is different than the last mesh
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces,
                             scalars=new_weight)
                    num_vert = new_vertices.shape[0]
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces,
                           scalars=new_weight)
            else:
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces)
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces)

            # update the satellite
            ts.set(x=pos[0], y=pos[1], z=pos[2])

            # update the camera view to be right behind the satellite
            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(f,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])
            # update the asteroid axes
            # ast_xs.set(x=[0, Ra[0,0]], y=[0, Ra[1,0]], z=[0, Ra[2,0]])
            # ast_ys.set(x=[0, Ra[0,1]], y=[0, Ra[1,1]], z=[0, Ra[2,1]])
            # ast_zs.set(x=[0, Ra[0,2]], y=[0, Ra[1,2]], z=[0, Ra[2,2]])

            # dum_xs.set(x=[pos[0], pos[0]+Rb2i[0,0]], y=[pos[1], pos[1]+Rb2i[1,0]],
            #              z=[pos[2], pos[2]+Rb2i[2,0]])
            # dum_ys.set(x=[pos[0], pos[0]+Rb2i[0,1]], y=[pos[1], pos[1]+Rb2i[1,1]],
            #              z=[pos[2], pos[2]+Rb2i[2,1]])
            # dum_zs.set(x=[pos[0], pos[0]+Rb2i[0,2]], y=[pos[1], pos[1]+Rb2i[1,2]],
            #              z=[pos[2], pos[2]+Rb2i[2,2]])

            pc_sources.set(x=ints[:, 0], y=ints[:, 1], z=ints[:, 2])
            # for pcs, inter in zip(pc_sources, ints):
            # check if intersection is empty
            # if inter.size > 2:
            #     pcs.set(x=inter[0], y=inter[1], z=inter[2])
            # else:
            #     pcs.set(x=0, y=0, z=0)
            # pcs.set(x=1, y=1, z=1)

            mesh.scene.disable_render = False
            yield
Esempio n. 10
0
def read_mesh_reconstruct(filename, output_path='/tmp/reconstruct_images'):
    """Use H5PY to read the data back and plot
    """
    logger = logging.getLogger(__name__)
    logger.info('Starting the image generation')

    # check if location exists
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    logger.info('Opening {}'.format(filename))
    with h5py.File(filename, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rf = hf['reconstructed_face']
        rw = hf['reconstructed_weight']

        # get all the keys for the groups
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        f_keys = np.array(utilities.sorted_nicely(list(rf.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = hf['initial_weight'][()]
        """Partial images during the reconstruction"""
        logger.info('Starting on partial reconstruction images')

        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(output_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=4)
        """Partial images using a colormap for the data"""
        logger.info('Now using a colormap for the uncertainty')
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig,
                                       v_initial,
                                       f_initial,
                                       color=None,
                                       colormap='viridis',
                                       scalars=w_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(output_path,
                                    'partial_weights_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            w = rw[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mlab.savefig(filename, magnification=4)
        """Generate the completed shape at a variety of different angles"""
        logger.info('Now generating some views of the final shape')
        # change the mesh to the finished mesh
        ms.reset(x=rv[v_keys[-1]][()][:, 0],
                 y=rv[v_keys[-1]][()][:, 1],
                 z=rv[v_keys[-1]][()][:, 2],
                 triangles=f_initial)
        elevation = np.array([30, -30])
        azimuth = np.array([0, 45, 135, 215, 315])

        for az, el in itertools.product(azimuth, elevation):
            filename = os.path.join(
                output_path, 'final_az=' + str(az) + '_el=' + str(el) + '.jpg')
            graphics.mayavi_view(fig=mfig, azimuth=az, elevation=el)
            graphics.mlab.savefig(filename, magnification=4)
        """Create a bunch of images for animation"""
        logger.info('Now making images for a movie')
        animation_path = os.path.join(output_path, 'animation')
        if not os.path.exists(animation_path):
            os.makedirs(animation_path)

        ms.reset(x=v_initial[:, 0],
                 y=v_initial[:, 1],
                 z=v_initial[:, 2],
                 triangles=f_initial)

        for ii, vk in enumerate(v_keys):
            filename = os.path.join(animation_path, str(ii).zfill(7) + '.jpg')
            v = rv[vk][()]
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mayavi_savefig(mfig, filename, magnification=4)

    logger.info('Finished')

    return mfig
Esempio n. 11
0
def TestSortedNicely():
    s = ['booklet', '4 sheets', '48 sheets', '12 sheets']
    s_sorted = utilities.sorted_nicely(s)
    s_sorted_exp = ['4 sheets', '12 sheets', '48 sheets', 'booklet']
    np.testing.assert_allclose(s_sorted, s_sorted_exp)
Esempio n. 12
0
def save_animation(filename, output_path, mesh_weight=False, magnification=4):
    
    output_path = os.path.join(output_path, 'animation')
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    with h5py.File(filename, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']
        
        # get all the keys
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = np.squeeze(hf['initial_weight'][()])
            
        # think about a black background as well
        mfig = graphics.mayavi_figure(bg=(0, 0, 0), size=(800,600), offscreen=True)
        
        if mesh_weight:
            mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial,
                                           scalars=w_initial,
                                           color=None, colormap='viridis')
        else:
            mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)

        # xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0)) 
        # yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0)) 
        # zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1)) 
        # ast_axes = (xaxis, yaxis, zaxis)
        
        print("Images will be saved to {}".format(output_path))
        ms = mesh.mlab_source
        # determine the maximum extents of the mesh and add some margin
        scale = 1.25
        max_x = scale*np.max(v_initial[:, 0])
        min_x = scale*np.min(v_initial[:, 0])
        max_y = scale*np.max(v_initial[:, 1])
        min_y = scale*np.min(v_initial[:, 1])
        max_z = scale*np.max(v_initial[:, 2])
        min_z = scale*np.min(v_initial[:, 2])

        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        # loop over keys and save images
        for img_index, vk in enumerate(v_keys):
            filename = os.path.join(output_path, str(vk).zfill(7) + '.jpg')
            new_vertices = rv[str(vk)][()]
            new_faces = f_initial
            new_weight = rw[str(vk)][()]

            # generate an image and save it 
            if mesh_weight:
                ms.set(x=new_vertices[:, 0],y=new_vertices[:, 1],
                       z=new_vertices[:,2], triangles=new_faces,
                       scalars=new_weight)
            else:
                ms.set(x=new_vertices[:, 0],y=new_vertices[:, 1],
                       z=new_vertices[:,2], triangles=new_faces)

            graphics.mlab.savefig(filename, magnification=magnification)

    # now call ffmpeg
    fps = 60
    name_str = "reconstruction_" + datetime.datetime.now().strftime("%Y%m%dT%H%M%S") + ".mp4"

    name = os.path.join(output_path, name_str)
    ffmpeg_fname = os.path.join(output_path, '%07d.jpg')
    cmd = "ffmpeg -framerate {} -i {} -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2' {}".format(fps, ffmpeg_fname, name)
    print(cmd)
    subprocess.check_output(['bash', '-c', cmd])

    # remove folder now
    for file in os.listdir(output_path): 
        file_path = os.path.join(output_path, file)
        if file_path.endswith('.jpg'):
            os.remove(file_path)
mfig = graphics.mayavi_figure(offscreen=False)
mesh = graphics.mayavi_addMesh(mfig, vb_true, fb_true)
graphics.mayavi_view(mfig, *view)
graphics.mayavi_savefig(mfig, '/tmp/castalia_bump_true.jpg', magnification=4)

# load the refinement final version
with h5py.File('./data/exploration/refine/20180619_castalia_refinement.hdf5',
               'r') as hf:
    # oriignal vertices
    est_initial_vertices = hf[
        'simulation_parameters/estimate_asteroid/initial_vertices'][()]
    num_vert = est_initial_vertices.shape[0]

    rv_group = hf['refinement/reconstructed_vertex']
    rf_group = hf['refinement/reconstructed_face']
    rw_group = hf['refinement/reconstructed_weight']
    Ra_group = hf['refinement/Ra']

    rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))

    v = rv_group[rv_keys[-1]][()]
    f = rf_group[rv_keys[-1]][()]
    w = rw_group[rv_keys[-1]][()]

    mfig_est = graphics.mayavi_figure(offscreen=False)
    mesh = graphics.mayavi_addMesh(mfig_est, v, f)
    graphics.mayavi_view(mfig_est, *view)
    graphics.mayavi_savefig(mfig_est,
                            '/tmp/castalia_bump_est.jpg',
                            magnification=4)