Exemplo n.º 1
0
from cmmlib import cmm
from cmmlib.inout import load_mesh
from cmmlib.vis.weights import show_weights

K1 = 8 + 6 + 12
K2 = 4
verts, tris = load_mesh('meshes/bumpy_cube6.obj')

Phi_cpr1 = cmm.compressed_manifold_modes(verts, tris, K1, mu=20., scaled=False)
Phi_cpr2 = cmm.compressed_manifold_modes(verts, tris, K2, mu=20., scaled=False)
Phi_vari1 = cmm.varimax_modes(verts, tris, K1)
Phi_vari2 = cmm.varimax_modes(verts, tris, K2)

# establish some consistent ordering of varimax modes just for visualization
i = (Phi_cpr2[:, 0]**2).argmax()  # select one vertex
# permute according to activation strength of that vertex
Phi_vari2 = Phi_vari2[:, (Phi_vari2[i]**2).argsort()[::-1]]
Phi_vari1 = Phi_vari1[:, (Phi_vari1[i]**2).argsort()[::-1]]
Phi_cpr2 = Phi_cpr2[:, (Phi_cpr2[i]**2).argsort()[::-1]]
Phi_cpr1 = Phi_cpr1[:, (Phi_cpr1[i]**2).argsort()[::-1]]

show_weights(verts,
             tris, (Phi_cpr1, Phi_cpr2, Phi_vari1, Phi_vari2),
             ('CMM, K=%d' % K1, 'CMM, K=%d' % K2, 'Variax, K=%d' % K1,
              'Varimax, K=%d' % K2),
             contours=7,
             show_labels=True)
Exemplo n.º 2
0
from cmmlib import cmm
from cmmlib.inout import load_mesh
from cmmlib.vis.weights import show_weights


K = 8 + 6 + 12
mu = 20.0
filename = 'meshes/bumpy_cube6.obj'

verts, tris = load_mesh(filename)

Phi_cpr = cmm.compressed_manifold_modes(verts, tris, K, mu=mu)
Phi_dense = cmm.manifold_harmonics(verts, tris, K)
Phi_vari = cmm.varimax_modes(verts, tris, K)

show_weights(verts, tris, (Phi_cpr, Phi_dense, Phi_vari),
             ('CMM', 'MH', 'Varimax'), show_labels=True)
from cmmlib import cmm
from cmmlib.inout import load_mesh
from cmmlib.vis.weights import show_weights


K1 = 8 + 6 + 12
K2 = 4
verts, tris = load_mesh('meshes/bumpy_cube6.obj')

Phi_cpr1 = cmm.compressed_manifold_modes(verts, tris, K1, mu=20., scaled=False)
Phi_cpr2 = cmm.compressed_manifold_modes(verts, tris, K2, mu=20., scaled=False)
Phi_vari1 = cmm.varimax_modes(verts, tris, K1)
Phi_vari2 = cmm.varimax_modes(verts, tris, K2)

# establish some consistent ordering of varimax modes just for visualization
i = (Phi_cpr2[:, 0]**2).argmax()  # select one vertex
# permute according to activation strength of that vertex
Phi_vari2 = Phi_vari2[:, (Phi_vari2[i]**2).argsort()[::-1]]
Phi_vari1 = Phi_vari1[:, (Phi_vari1[i]**2).argsort()[::-1]]
Phi_cpr2 = Phi_cpr2[:, (Phi_cpr2[i]**2).argsort()[::-1]]
Phi_cpr1 = Phi_cpr1[:, (Phi_cpr1[i]**2).argsort()[::-1]]

show_weights(
    verts, tris,
    (Phi_cpr1, Phi_cpr2, Phi_vari1, Phi_vari2),
    ('CMM, K=%d' % K1, 'CMM, K=%d' % K2, 'Variax, K=%d' % K1, 'Varimax, K=%d' % K2),
    contours=7, show_labels=True)
Exemplo n.º 4
0
    elif init == 1:
        Phi_init = 1 * (color2[:, 0] > 200).astype(np.float).reshape(len(verts), K)
    else:
        Phi_init = np.random.uniform(-1, 1, (len(verts), K))
    Phis = [Phi_init]

    def callback(H, mu, Phi, E, S, **kwargs):
        global i
        i += 1
        if i in at_iters:
            Phis.append(Phi)

    i = 0
    cmm.compressed_manifold_modes(
        verts, tris, K, mu=20, init=Phi_init, scaled=True,
        callback=callback, tol_abs=0, tol_rel=0, maxiter=max(at_iters)+1,
        check_interval=1)

    all_Phis.append(Phis)

Phi_at_iters = np.array([np.array(Phis) for Phis in all_Phis])

show_weights(
    verts, tris,
    Phi_at_iters.reshape((num_inits*len(at_iters), len(verts), K)),
    ["Iteration %d (%d)" % (it, exp) if it > 0 else "Initialization (%d)" % exp
     for exp, it in product(range(num_inits), at_iters)],
    show_labels=True, label_offset_axis=1, offset_spacing2=1.3, 
    label_offset=0.8, num_columns=len(at_iters),
)
Exemplo n.º 5
0
def main(input_filename, K, mu, output_dir=None, visualize=False, scaled=False,
         maxiter=None, ply=False, off=False):

    if (off or ply) and not output_dir:
        print ("please specify an output directory")
        return 1

    if output_dir and not path.exists(output_dir):
        print("%s does not exist" % output_dir)
        return 2

    verts, tris = load_mesh(input_filename, normalize=True)
    print ("%d vertices, %d faces" % (len(verts), len(tris)))

    Phi_cpr, D = cmm.compressed_manifold_modes(
        verts, tris, K, mu=mu, scaled=scaled,
        maxiter=maxiter, verbose=100, return_D=True)

    if D is None:
        D_diag = np.ones(len(verts))
        D = sparse.eye(len(verts))
    else:
        D_diag = D.data

    if visualize:
        from cmmlib.vis.weights import show_weights
        show_weights(verts, tris, Phi_cpr)

    if output_dir:
        # save in simple text format
        np.savetxt(path.join(output_dir, 'phi.txt'), Phi_cpr, fmt='%f')
        np.savetxt(path.join(output_dir, 'D_diag.txt'), D_diag, fmt='%f')

        # save in matlab format
        savemat(path.join(output_dir, 'phi.mat'),
                dict(verts=verts, tris=tris+1, phi=Phi_cpr, D=D))

        # save HDF5 format if possible
        try:
            import h5py
        except ImportError:
            print ("Cannot save as HDF5, please install the h5py module")
        else:
            with h5py.File(path.join(output_dir, 'phi.h5'), 'w') as f:
                f['verts'] = verts
                f['tris'] = tris
                f['phi'] = Phi_cpr
                f['d_diag'] = D_diag

        # save NPY format
        np.save(path.join(output_dir, 'phi.npy'), Phi_cpr)
        np.save(path.join(output_dir, 'D_diag.npy'), Phi_cpr)

        if off or ply:
            # map phi scalars to colors
            from mayavi.core.lut_manager import LUTManager
            from cmmlib.vis.weights import _centered
            lut = LUTManager(lut_mode='RdBu').lut.table.to_array()[:, :3]
            colors = [
                lut[(_centered(Phi_cpr[:, k]) * (lut.shape[0]-1)).astype(int)]
                for k in range(K)]
            # save in a single scene as a collage
            w = int(np.ceil(np.sqrt(K))) if K > 6 else K
            spacing = 1.2 * verts.ptp(axis=0)
            all_verts = [verts + spacing * (1.5, 0, 0)]
            all_tris = [tris]
            all_color = [np.zeros(verts.shape, np.int) + 127]
            for k in range(K):
                all_verts.append(verts + spacing * (-(k % w), 0, int(k / w)))
                all_tris.append(tris + len(verts) * (k+1))
                all_color.append(colors[k])

            if off:
                save_coff(path.join(output_dir, 'input.off'),
                          verts.astype(np.float32), tris)
                for k in range(K):
                    save_coff(path.join(output_dir, 'cmh_%03d.off' % k),
                              verts.astype(np.float32), tris, colors[k])
                save_coff(path.join(output_dir, 'all.off'),
                          np.vstack(all_verts), np.vstack(all_tris),
                          np.vstack(all_color))

            if ply:
                from tvtk.api import tvtk
                pd = tvtk.PolyData(
                    points=np.vstack(all_verts).astype(np.float32),
                    polys=np.vstack(all_tris).astype(np.uint32))
                pd.point_data.scalars = np.vstack(all_color).astype(np.uint8)
                pd.point_data.scalars.name = 'colors'
                ply = tvtk.PLYWriter(
                    file_name=path.join(output_dir, 'all.ply'),
                    input=pd, color=(1, 1, 1))
                ply.array_name = 'colors'
                ply.write()
def main():
    # prepare data
    verts, tris = load_mesh('meshes/bumpy_cube6.obj')
    K = 8 + 6 + 12
    mu = 20.0
    maxiter = 500
    num_experiments = 1

    # prepare data structures
    ResultData = namedtuple('ResultData', 'Phi info logger')
    data_per_algo = defaultdict(list)
    # parameters passed to algorithms - to be fair,
    # turn off automatic penalty adjustment in our method
    # set check_interval = 1 to force callback to be called in every iteration
    algorithms = [
        ('osher', cmm.solve_compressed_osher,
            dict()),
        ('ours', cmm.solve_compressed_splitorth,
            dict(auto_adjust_penalty=False, check_interval=1)),
    ]

    # run the algorithm with same input mesh and
    # different random initializations
    print "will now run the method with %d different initializations" % num_experiments
    print "the primal residual with our method should consistently be lower compared to Oshers et al."
    for random_seed in range(num_experiments):
        np.random.seed(random_seed)
        Phi_init = np.random.random((len(verts), K))
        print "--"
        print "running experiment %d" % random_seed
        for name, method, options in algorithms:
            Phi, info, logger = test_convergence(
                verts, tris, K, mu,
                Phi_init, method, maxiter, **options)
            print name, info['r_primal']
            data_per_algo[name].append(ResultData(Phi, info, logger))

    # visualize results
    import matplotlib
    if len(sys.argv) > 1:
        matplotlib.use('pgf') # TODO PGF
    else:
        matplotlib.use('WxAgg')

    import pylab as pl
    pl.rc('text', usetex=True)
    pl.rc('font', size=6)
    pl.figure(figsize=(0.9, 1.1))
    plot_fun = pl.semilogy
    plot_fun(data_per_algo['osher'][0].logger.r_primals, c='r',
             label=r'osher')
    plot_fun(data_per_algo['ours'][0].logger.r_primals, c='g',
             label=r'ours')
    pl.legend(loc='center right').draggable()
    pl.locator_params(nbins=4, axis='x')
    pl.xlabel('iteration')
    pl.ylabel(r'$  \left\Vert r \right\Vert_2$')
    pl.gca().yaxis.set_major_locator(matplotlib.ticker.LogLocator(numticks=4))

    if len(sys.argv) > 2:
        pl.savefig(sys.argv[1])  #, bbox_inches='tight')
    else:
        pl.ion()
        pl.show()

    # let us first visualize the modes where things go wrong
    # which are most probably those where the primal residual is very high
    Q = data_per_algo['osher'][0].info['Q']
    P = data_per_algo['osher'][0].info['P']
    worst_first = ((Q - P)**2).sum(axis=0).argsort()[::-1]

    show_weights(
        verts, tris,
        (data_per_algo['osher'][0].Phi[:, worst_first], 
         data_per_algo['ours'][0].Phi[:, worst_first]), 
        ('osher', 'ours')
    )
Exemplo n.º 7
0
def main(input_filename, K, mu, output_dir=None, visualize=False, scaled=False,
         maxiter=None, ply=False, off=False):

    if (off or ply) and not output_dir:
        print "please specify an output directory"
        return 1

    if output_dir and not path.exists(output_dir):
        print "%s does not exist" % output_dir
        return 2

    verts, tris = load_mesh(input_filename, normalize=True)
    print "%d vertices, %d faces" % (len(verts), len(tris))

    Phi_cpr, D = cmm.compressed_manifold_modes(
        verts, tris, K, mu=mu, scaled=scaled,
        maxiter=maxiter, verbose=100, return_D=True)

    if D is None:
        D_diag = np.ones(len(verts))
        D = sparse.eye(len(verts))
    else:
        D_diag = D.data

    if visualize:
        from cmmlib.vis.weights import show_weights
        show_weights(verts, tris, Phi_cpr)

    if output_dir:
        # save in simple text format
        np.savetxt(path.join(output_dir, 'phi.txt'), Phi_cpr, fmt='%f')
        np.savetxt(path.join(output_dir, 'D_diag.txt'), D_diag, fmt='%f')

        # save in matlab format
        savemat(path.join(output_dir, 'phi.mat'),
                dict(verts=verts, tris=tris+1, phi=Phi_cpr, D=D))

        # save HDF5 format if possible
        try:
            import h5py
        except ImportError:
            print "Cannot save as HDF5, please install the h5py module"
        else:
            with h5py.File(path.join(output_dir, 'phi.h5'), 'w') as f:
                f['verts'] = verts
                f['tris'] = tris
                f['phi'] = Phi_cpr
                f['d_diag'] = D_diag

        # save NPY format
        np.save(path.join(output_dir, 'phi.npy'), Phi_cpr)
        np.save(path.join(output_dir, 'D_diag.npy'), Phi_cpr)

        if off or ply:
            # map phi scalars to colors
            from mayavi.core.lut_manager import LUTManager
            from cmmlib.vis.weights import _centered
            lut = LUTManager(lut_mode='RdBu').lut.table.to_array()[:, :3]
            colors = [
                lut[(_centered(Phi_cpr[:, k]) * (lut.shape[0]-1)).astype(int)]
                for k in xrange(K)]
            # save in a single scene as a collage
            w = int(np.ceil(np.sqrt(K))) if K > 6 else K
            spacing = 1.2 * verts.ptp(axis=0)
            all_verts = [verts + spacing * (1.5, 0, 0)]
            all_tris = [tris]
            all_color = [np.zeros(verts.shape, np.int) + 127]
            for k in xrange(K):
                all_verts.append(verts + spacing * (-(k % w), 0, int(k / w)))
                all_tris.append(tris + len(verts) * (k+1))
                all_color.append(colors[k])

            if off:
                save_coff(path.join(output_dir, 'input.off'),
                          verts.astype(np.float32), tris)
                for k in xrange(K):
                    save_coff(path.join(output_dir, 'cmh_%03d.off' % k),
                              verts.astype(np.float32), tris, colors[k])
                save_coff(path.join(output_dir, 'all.off'),
                          np.vstack(all_verts), np.vstack(all_tris),
                          np.vstack(all_color))

            if ply:
                from tvtk.api import tvtk
                pd = tvtk.PolyData(
                    points=np.vstack(all_verts).astype(np.float32),
                    polys=np.vstack(all_tris).astype(np.uint32))
                pd.point_data.scalars = np.vstack(all_color).astype(np.uint8)
                pd.point_data.scalars.name = 'colors'
                ply = tvtk.PLYWriter(
                    file_name=path.join(output_dir, 'all.ply'),
                    input=pd, color=(1, 1, 1))
                ply.array_name = 'colors'
                ply.write()
Exemplo n.º 8
0
from cmmlib import cmm
from cmmlib.inout import load_mesh
from cmmlib.vis.weights import show_weights

K = 8 + 6 + 12
mu = 20.0
filename = 'meshes/bumpy_cube6.obj'

verts, tris = load_mesh(filename)

Phi_cpr = cmm.compressed_manifold_modes(verts, tris, K, mu=mu)
Phi_dense = cmm.manifold_harmonics(verts, tris, K)
Phi_vari = cmm.varimax_modes(verts, tris, K)

show_weights(verts,
             tris, (Phi_cpr, Phi_dense, Phi_vari), ('CMM', 'MH', 'Varimax'),
             show_labels=True)
import numpy as np

from cmmlib import cmm
from cmmlib.align import optimal_permutation
from cmmlib.inout import load_mesh
from cmmlib.vis.weights import show_weights


verts, tris = load_mesh('meshes/hand_4054.obj')
K = 6
mus = [1/100., 1., 10.]

all_Phi = [cmm.manifold_harmonics(verts, tris, K)] \
        + [cmm.compressed_manifold_modes(verts, tris, K, mu, scaled=False)
           for mu in mus]

# permute modes so we can visualize them side-by-side
all_Phi_aligned = \
    [np.dot(optimal_permutation(Phi.T, all_Phi[-1].T, allow_reflection=True), Phi.T).T
     for Phi in all_Phi[:-1]] + \
    [all_Phi[-1]]

show_weights(verts, tris, all_Phi_aligned, names=['dense'] + map(str, mus))
Exemplo n.º 10
0
                                  tris,
                                  K,
                                  mu=20,
                                  init=Phi_init,
                                  scaled=True,
                                  callback=callback,
                                  tol_abs=0,
                                  tol_rel=0,
                                  maxiter=max(at_iters) + 1,
                                  check_interval=1)

    all_Phis.append(Phis)

Phi_at_iters = np.array([np.array(Phis) for Phis in all_Phis])

show_weights(
    verts,
    tris,
    Phi_at_iters.reshape((num_inits * len(at_iters), len(verts), K)),
    [
        "Iteration %d (%d)" %
        (it, exp) if it > 0 else "Initialization (%d)" % exp
        for exp, it in product(range(num_inits), at_iters)
    ],
    show_labels=True,
    label_offset_axis=1,
    offset_spacing2=1.3,
    label_offset=0.8,
    num_columns=len(at_iters),
)