Exemple #1
0
def init_cudaqs_module(res_ctx, ctx):
    print('init_cudaqs_module')

    device, dtype = ctx['device'], torch.double
    batch_size = ctx['batch_size']
    verbose = ctx['verbose'] if 'verbose' in ctx else False
    use_multi_thread = False
    shared_data_dir = res_ctx['shared_data_dir']
    patch_id = ctx['patch_id'] if 'patch_id' in ctx else -1
    stiffen_anchor_factor = ctx['stiffen_anchor_factor']
    use_variable_m = ctx['use_variable_m']

    stiffen_anchor = load_anchor_data(shared_data_dir)
    edges, l0, k = load_spring_data(shared_data_dir)
    axial_i, axial_w, axial_k = load_axial_data(shared_data_dir)

    if patch_id >= 0:
        patch_manager = PatchManager(
            shared_data_dir=res_ctx['shared_data_dir'])
        patch_vt_ids = patch_manager.load_patch_vt_ids(patch_id)
        patch_edge_ids = patch_manager.get_patch_edge_ids(patch_vt_ids, edges)
        stiffen_anchor = stiffen_anchor[patch_vt_ids]
        edges = patch_manager.get_patch_edges(patch_id, edges)
        l0 = l0[patch_edge_ids]
        k = k[patch_edge_ids]
        patch_axial_edge_ids = patch_manager.get_patch_edge_ids(
            patch_vt_ids, axial_i)
        axial_i = patch_manager.get_patch_edges(patch_id, axial_i)
        axial_w = axial_w[patch_axial_edge_ids]
        axial_k = axial_k[patch_axial_edge_ids]

    stiffen_anchor = torch.from_numpy(stiffen_anchor).to(
        device=device, dtype=dtype) * stiffen_anchor_factor
    edges = torch.from_numpy(edges).to(device=device, dtype=torch.int32)
    l0 = torch.from_numpy(l0).to(device=device, dtype=dtype)
    k = torch.from_numpy(k).to(device=device, dtype=dtype)
    axial_i = torch.from_numpy(axial_i).to(device=device, dtype=torch.int32)
    axial_w = torch.from_numpy(axial_w).to(device=device, dtype=dtype)
    axial_k = torch.from_numpy(axial_k).to(device=device, dtype=dtype)
    n_vts = len(stiffen_anchor)

    module = CudaqsModule()
    cudaqs.init(n_vts, batch_size, use_multi_thread, verbose)
    spring_data = cudaqs.init_spring(edges, l0, k)
    axial_data = cudaqs.init_axial(axial_i, axial_w, axial_k)
    system = cudaqs.init_system(n_vts, spring_data, axial_data)
    forward_opt = cudaqs.init_forward(system)
    backward_opt = cudaqs.init_backward(system, use_variable_m)
    # print('len(edges):',len(edges))
    opt_data = cudaqs.init_opt_data(batch_size, n_vts, len(edges))
    module.init(spring_data, axial_data, system, forward_opt, backward_opt,
                opt_data, use_variable_m)
    module.stiffen_anchor = stiffen_anchor.unsqueeze(0)

    print('init_cudaqs_module finish')

    return module
Exemple #2
0
class SpringOptModule(nn.Module):
    def __init__(self,res_ctx,ctx):
        super(SpringOptModule,self).__init__()
        self.device=ctx['device']
        self.dtype=ctx['dtype']
        self.patch_id=ctx['patch_id']

        m,edges,l0=load_opt_data(res_ctx,ctx)
        k=res_ctx['stiffness']
        harmonic_m=1/(1/m[edges[:,0]]+1/m[edges[:,1]])
        k*=harmonic_m

        if self.patch_id>=0:
            self.patch_manager=PatchManager(shared_data_dir=res_ctx['shared_data_dir'])
            self.patch_vt_ids=self.patch_manager.load_patch_vt_ids(self.patch_id)
            patch_edge_ids=self.patch_manager.get_patch_edge_ids(self.patch_vt_ids,edges)
            m=m[self.patch_vt_ids]
            l0=l0[patch_edge_ids]
            edges=self.patch_manager.get_patch_edges(self.patch_id,edges)
            k=k[patch_edge_ids]

        axial_i,axial_w=load_axial_data(res_ctx)
        if self.patch_id>=0:
            axial_i,axial_w=get_patch_axial_data(self.patch_vt_ids,axial_i,axial_w)
        m0,m1,m2,m3=m[axial_i[:,0]],m[axial_i[:,1]],m[axial_i[:,2]],m[axial_i[:,3]]
        axial_harmonic_m=4/(1/m0+1/m1+1/m2+1/m3)
        axial_k=axial_harmonic_m*1e-1 # magic number

        m*=2

        self.m=torch.from_numpy(m).to(dtype=self.dtype,device=self.device).view(-1,1)
        self.edges=torch.from_numpy(edges).to(dtype=torch.long,device=self.device).view(-1,2)
        self.l0=torch.from_numpy(l0).to(dtype=self.dtype,device=self.device).view(-1,1)
        self.k=torch.from_numpy(k).to(dtype=self.dtype,device=self.device).view(-1,1)
        axial_i=torch.from_numpy(axial_i).to(dtype=torch.long,device=self.device).view(-1,4)
        axial_w=torch.from_numpy(axial_w).to(dtype=self.dtype,device=self.device).view(-1,4)
        axial_k=torch.from_numpy(axial_k).to(dtype=self.dtype,device=self.device).view(-1,1)
        self.axial_data=(axial_i,axial_w,axial_k)

        self.system=SpringOptSystem(self.m,self.edges,self.l0,self.k,m_alpha=0.1,axial_data=self.axial_data) # magic number
        self.opt=NewtonOpt(self.system,newton_tol=1e-12,cg_tol=1e-3,cg_max_iter=max(len(self.m)//2,250)) # magic number

    def forward(self,x):
        return spring_opt(self.opt,x)
Exemple #3
0
    def __init__(self):
        self.shared_data_dir = '../../shared_data'
        self.pd_dir = 'opt_test/cvxpy'
        self.cr_dir = 'opt_test/cvxpy'
        self.patch_id = -1
        if self.patch_id >= 0:
            self.pd_dir = join(self.pd_dir, 'p{:02d}'.format(self.patch_id))
            self.cr_dir = join(self.cr_dir, 'p{:02d}'.format(self.patch_id))
        else:
            self.pd_dir = join(self.pd_dir, 'whole')
            self.cr_dir = join(self.cr_dir, 'whole')
        self.vlz_dir = join(self.cr_dir, 'vlz')

        if not isdir(self.pd_dir):
            os.makedirs(self.pd_dir)
        if not isdir(self.cr_dir):
            os.makedirs(self.cr_dir)
        if not isdir(self.vlz_dir):
            os.makedirs(self.vlz_dir)

        res_ctx = {'shared_data_dir': self.shared_data_dir}
        ctx = {'max_num_constraints': -1}
        m, edges, l0 = load_opt_data(res_ctx, ctx)
        self.agg_n_vts = len(m)

        flat_obj = read_obj(join(self.shared_data_dir, 'flat_tshirt.obj'))
        self.f = flat_obj.f

        if self.patch_id >= 0:
            patch_manager = PatchManager(
                shared_data_dir=res_ctx['shared_data_dir'])
            self.patch_vt_ids = patch_manager.load_patch_vt_ids(self.patch_id)
            self.patch_fc_ids = patch_manager.get_patch_fc_ids(
                self.patch_vt_ids, self.f)
            self.patch_edge_ids = patch_manager.get_patch_edge_ids(
                self.patch_vt_ids, edges)
            m = m[self.patch_vt_ids]
            l0 = l0[self.patch_edge_ids]
            edges = patch_manager.get_patch_edges(self.patch_id, edges)

        self.opt = CvxpyOpt(m, edges, l0)
Exemple #4
0
class SpringOptTest:
    def __init__(self):
        self.data_root_dir = '/data/zhenglin/poses_v3'
        self.pd_dir = 'spring_test/newton'
        self.cr_dir = 'spring_test/newton'
        self.shared_data_dir = '../../shared_data'

        self.device = torch.device('cuda:0')
        self.dtype = torch.double

        self.patch_id = -1
        # self.patch_id=13

        res_ctx = {'shared_data_dir': self.shared_data_dir}
        ctx = {
            'dtype': self.dtype,
            'device': self.device,
            'patch_id': self.patch_id,
            'max_num_constraints': -1,
            'use_spring': True
        }
        self.res_ctx = res_ctx
        self.ctx = ctx
        m, edges, l0 = load_opt_data(res_ctx, ctx)
        k = res_ctx['stiffness']
        harmonic_m = 1 / (1 / m[edges[:, 0]] + 1 / m[edges[:, 1]])
        k *= harmonic_m
        print('avg m:', np.mean(m), 'avg k:', np.mean(k))

        flat_obj = read_obj(join(self.shared_data_dir, 'flat_tshirt.obj'))
        self.f = flat_obj.f
        self.agg_n_vts = len(flat_obj.v)

        if self.patch_id >= 0:
            self.patch_manager = PatchManager(
                shared_data_dir=res_ctx['shared_data_dir'])
            self.patch_vt_ids = self.patch_manager.load_patch_vt_ids(
                self.patch_id)
            self.patch_fc_ids = self.patch_manager.get_patch_fc_ids(
                self.patch_vt_ids, self.f)
            self.patch_local_fcs = self.patch_manager.get_patch_local_fcs(
                self.patch_vt_ids, self.f[self.patch_fc_ids])
            patch_edge_ids = self.patch_manager.get_patch_edge_ids(
                self.patch_vt_ids, edges)
            m = m[self.patch_vt_ids]
            l0 = l0[patch_edge_ids]
            edges = self.patch_manager.get_patch_edges(self.patch_id, edges)
            k = k[patch_edge_ids]

            self.pd_dir = join(self.pd_dir, 'p{}'.format(self.patch_id))
            self.cr_dir = join(self.cr_dir, 'p{}'.format(self.patch_id))
        else:
            self.pd_dir = join(self.pd_dir, 'whole')
            self.cr_dir = join(self.cr_dir, 'whole')

        self.opt_dir = join(self.pd_dir, 'opt')
        if not isdir(self.pd_dir):
            os.makedirs(self.pd_dir)
        if not isdir(self.cr_dir):
            os.makedirs(self.cr_dir)
        if not isdir(self.opt_dir):
            os.makedirs(self.opt_dir)

        self.use_axial_springs = True
        if self.use_axial_springs:
            axial_i, axial_w = load_axial_data(res_ctx)
            if self.patch_id >= 0:
                axial_i, axial_w = get_patch_axial_data(
                    self.patch_vt_ids, axial_i, axial_w)
            m0, m1, m2, m3 = m[axial_i[:, 0]], m[axial_i[:, 1]], m[
                axial_i[:, 2]], m[axial_i[:, 3]]
            axial_harmonic_m = 4 / (1 / m0 + 1 / m1 + 1 / m2 + 1 / m3)
            axial_k = axial_harmonic_m * 1e-1

        # m*=2
        # m*=0.05
        m *= 0.2

        # out_dir='spring_test/data'
        # if not isdir(out_dir):
        #     os.makedirs(out_dir)
        # np.savetxt(join(out_dir,'stiffen_anchor.txt'),m,fmt='%.100f')
        # np.savetxt(join(out_dir,'edges.txt'),edges,fmt='%d')
        # np.savetxt(join(out_dir,'l0.txt'),l0,fmt='%.100f')
        # np.savetxt(join(out_dir,'k.txt'),k,fmt='%.100f')
        # np.savetxt(join(out_dir,'axial_i.txt'),axial_i,fmt='%d')
        # np.savetxt(join(out_dir,'axial_w.txt'),axial_w,fmt='%.100f')
        # np.savetxt(join(out_dir,'axial_k.txt'),axial_k,fmt='%.100f')
        # exit(0)

        # self.m=torch.ones((len(m),1)).to(dtype=self.dtype,device=self.device)
        # self.m=(torch.ones((len(m),1))+(torch.rand((len(m),1))-0.5)*1).to(dtype=self.dtype,device=self.device)*4
        self.stiffen_anchors_net = torch.from_numpy(m).to(
            dtype=self.dtype, device=self.device).view(-1, 1) / 2
        self.stiffen_anchors_reg = torch.from_numpy(m).to(
            dtype=self.dtype, device=self.device).view(-1, 1) / 2
        self.edges = torch.from_numpy(edges).to(dtype=torch.long,
                                                device=self.device).view(
                                                    -1, 2)
        self.l0 = torch.from_numpy(l0).to(dtype=self.dtype,
                                          device=self.device).view(-1, 1)
        self.k = torch.from_numpy(k).to(dtype=self.dtype,
                                        device=self.device).view(-1, 1)

        if self.use_axial_springs:
            axial_i = torch.from_numpy(axial_i).to(dtype=torch.long,
                                                   device=self.device).view(
                                                       -1, 4)
            axial_w = torch.from_numpy(axial_w).to(dtype=self.dtype,
                                                   device=self.device).view(
                                                       -1, 4)
            axial_k = torch.from_numpy(axial_k).to(dtype=self.dtype,
                                                   device=self.device).view(
                                                       -1, 1)
            self.axial_data = (axial_i, axial_w, axial_k)
        else:
            self.axial_data = None

    def read_obj(self, path, patch_id=-1):
        pd_obj = read_obj(path)
        pd_vt = pd_obj.v
        f = pd_obj.f
        if patch_id >= 0:
            pd_vt = pd_vt[self.patch_vt_ids]
            f = f[self.patch_fc_ids]
        return pd_vt, f

    def write_obj(self, v, f, out_path, patch_id=-1):
        if patch_id >= 0:
            full_v = np.zeros((self.agg_n_vts, 3))
            full_v[self.patch_vt_ids, :] = v
            v = full_v
        print('write to', out_path)
        write_obj(Obj(v=v, f=f), out_path)

    def test_forward(self, sample_id, n_iters=10):
        # gt_path=join(self.pd_dir,'gt_{:08d}.obj'.format(sample_id))
        # v,f=self.read_obj(gt_path,patch_id=self.patch_id)
        # print('save gt')
        # np.savetxt('spring_test/data/gt_{:08d}.txt'.format(sample_id),v,fmt='%.100f')
        # exit(0)

        pd_path = join(self.pd_dir, 'pd_{:08d}.obj'.format(sample_id))
        v, f = self.read_obj(pd_path, patch_id=self.patch_id)
        # np.savetxt('spring_test/data/fcs.txt',f,fmt='%d')
        # np.savetxt('spring_test/data/anchor.txt',v,fmt='%.100f')
        v = torch.from_numpy(v).to(device=self.device, dtype=self.dtype)
        system = SpringOptSystem(self.stiffen_anchors_net,
                                 self.stiffen_anchors_reg,
                                 self.edges,
                                 self.l0,
                                 self.k,
                                 m_alpha=0.1,
                                 axial_data=self.axial_data)
        opt = NewtonOpt(system, newton_tol=1e-3, cg_tol=1e-3, cg_max_iter=1000)
        x = v
        start_time = time.time()
        for i in range(n_iters):
            x, data, success = opt.solve(v, x)
            # print('diff',torch.norm(x-v).item())
            end_time = time.time()
            print('forward time:', end_time - start_time)
            if i % 1 == 0:
                x_save = x.detach().cpu().numpy()
                cr_path = join(self.cr_dir,
                               'cr_{:08d}_i{:02d}.obj'.format(sample_id, i))
                self.write_obj(x_save, f, cr_path, patch_id=self.patch_id)
        cr_path = join(self.cr_dir, 'cr_{:08d}.npy'.format(sample_id))
        np.save(cr_path, x_save)
        # m_path=join(self.cr_dir,'m_{:08d}.npy'.format(sample_id))
        # np.save(m_path,data['m_adjusted'].cpu().numpy())

        # data_dir=join(self.cr_dir,'data')
        # if not isdir(data_dir):
        #     os.makedirs(data_dir)
        # save_data(data_dir,gather_data([data]))

    def test_dataset(self, start, end, n_iters=10):
        gt_offset_dir = join(self.data_root_dir, 'lowres_offset_npys')
        skin_dir = join(self.data_root_dir, 'lowres_skin_npys')
        out_dir = join(self.data_root_dir,
                       'lowres_offsets_i{}'.format(n_iters))
        if not isdir(out_dir):
            os.makedirs(out_dir)
        system = SpringOptSystem(self.m,
                                 self.edges,
                                 self.l0,
                                 self.k,
                                 m_alpha=0.1,
                                 axial_data=self.axial_data)
        opt = NewtonOpt(system, newton_tol=1e-12, cg_tol=1e-3, cg_max_iter=250)
        for sample_id in range(start, end + 1):
            print('sample_id', sample_id)
            try:
                offset = np.load(
                    join(gt_offset_dir, 'offset_{:08d}.npy'.format(sample_id)))
                skin = np.load(
                    join(skin_dir, 'skin_{:08d}.npy'.format(sample_id)))
                x = torch.from_numpy(offset + skin).to(device=self.device,
                                                       dtype=self.dtype)
                for i in range(n_iters):
                    x = opt.solve(x)
                x_save = x.cpu().numpy()
                offset_save = x_save - skin
                np.save(join(out_dir, 'offset_{:08d}.npy'.format(sample_id)),
                        offset_save)
                # cr_path=join(self.cr_dir,'cr_{:08d}.obj'.format(sample_id))
                # self.write_obj(x_save,None,cr_path,patch_id=self.patch_id)
            except:
                continue

    def test_forward_dir(self, in_dir, out_dir, n_iters=1, start=0, end=2247):
        system = SpringOptSystem(self.stiffen_anchors_net,
                                 self.stiffen_anchors_reg,
                                 self.edges,
                                 self.l0,
                                 self.k,
                                 m_alpha=0.1,
                                 axial_data=self.axial_data)
        opt = NewtonOpt(system, newton_tol=1e-12, cg_tol=1e-3, cg_max_iter=250)
        if not isdir(out_dir):
            os.makedirs(out_dir)

        for sample_id in range(start, end + 1):
            pd_path = join(in_dir, '{:08d}.obj'.format(sample_id))
            v, f = self.read_obj(pd_path, patch_id=self.patch_id)
            v = torch.from_numpy(v).to(device=self.device, dtype=self.dtype)
            x = v
            start_time = time.time()
            for i in range(n_iters):
                x, data, success = opt.solve(v, x)
                end_time = time.time()
                print('forward time:', end_time - start_time)
            x_save = x.detach().cpu().numpy()
            cr_path = join(out_dir, '{:08d}.obj'.format(sample_id))
            self.write_obj(x_save, f, cr_path, patch_id=self.patch_id)

    def test_backward(self, sample_id):
        pd_path = join(self.pd_dir, 'pd_{:08d}.obj'.format(sample_id))
        pd_v, f = self.read_obj(pd_path, patch_id=self.patch_id)
        pd_v = torch.from_numpy(pd_v).to(device=self.device, dtype=self.dtype)
        gt_path = join(self.pd_dir, 'gt_{:08d}.obj'.format(sample_id))
        gt_v, _ = self.read_obj(gt_path, patch_id=self.patch_id)
        gt_v = torch.from_numpy(gt_v).to(device=self.device, dtype=self.dtype)
        dv = pd_v - gt_v
        cr_path = join(self.cr_dir, 'cr_{:08d}.npy'.format(sample_id))
        cr_v = np.load(cr_path)
        cr_v = torch.from_numpy(cr_v).to(device=self.device, dtype=self.dtype)
        # m_path=join(self.cr_dir,'m_{:08d}.npy'.format(sample_id))
        # m_adjusted=np.load(m_path)
        # m_adjusted=torch.from_numpy(m_adjusted).to(device=self.device,dtype=self.dtype)

        # system=SpringOptSystem(self.m,self.edges,self.l0,self.k,m_alpha=0.1,axial_data=self.axial_data)
        system = SpringOptSystem(self.stiffen_anchors_net,
                                 self.stiffen_anchors_reg,
                                 self.edges,
                                 self.l0,
                                 self.k,
                                 m_alpha=0.1,
                                 axial_data=self.axial_data)
        system.use_m_adjusted = False
        data = system.get_data(cr_v)
        data['c'] = pd_v
        data['anchors_net'] = pd_v
        data['anchors_reg'] = pd_v
        data['stiffen_anchors_net'] = self.stiffen_anchors_net
        data['stiffen_anchors_reg'] = self.stiffen_anchors_reg

        # data['m_adjusted']=m_adjusted
        J = system.get_J(data)
        norm_J = torch.norm(J)
        data['J_rms'] = norm_J / np.sqrt(len(cr_v))

        dx = spring_opt_backward(system,
                                 data,
                                 dv,
                                 cg_tol=1e-3,
                                 cg_max_iter=250)
        grad_path = join(self.cr_dir, 'grad_{:08d}.npy'.format(sample_id))
        print('save to', grad_path)
        np.save(grad_path, dx.cpu().numpy())

    def test_grad(self, sample_id):
        pd_path = join(self.pd_dir, 'pd_{:08d}.obj'.format(sample_id))
        print('pd_path', pd_path)
        pd_vt, _ = self.read_obj(pd_path, patch_id=self.patch_id)
        grad = np.load(join(self.cr_dir, 'grad_{:08d}.npy'.format(sample_id)))
        print('grad.norm', np.linalg.norm(grad))
        grad_len = 1
        ed_vt = pd_vt - grad * grad_len
        n_vts = len(pd_vt)
        obj_path = join(self.cr_dir, 'grad_{:08d}.obj'.format(sample_id))
        print('write to', obj_path)
        with open(obj_path, 'w') as f:
            for v in pd_vt:
                f.write('v {} {} {}\n'.format(v[0], v[1], v[2]))
            for v in ed_vt:
                f.write('v {} {} {}\n'.format(v[0], v[1], v[2]))
            for i in range(n_vts):
                f.write('l {} {}\n'.format(i + 1, i + 1 + n_vts))

    def test_module(self, sample_id, n_iters=1):
        pd_path = join(self.pd_dir, 'pd_{:08d}.obj'.format(sample_id))
        pd_v, f = self.read_obj(pd_path, patch_id=self.patch_id)
        pd_v = torch.from_numpy(pd_v).to(device=self.device,
                                         dtype=self.dtype).unsqueeze(0)
        gt_path = join(self.pd_dir, 'gt_{:08d}.obj'.format(sample_id))
        gt_v, _ = self.read_obj(gt_path, patch_id=self.patch_id)
        gt_v = torch.from_numpy(gt_v).to(device=self.device,
                                         dtype=self.dtype).unsqueeze(0)
        proj_module = SpringOptModule(self.res_ctx, self.ctx)
        x = pd_v
        x.requires_grad_(True)
        for i in range(n_iters):
            x = proj_module(x)
        loss = torch.sum((gt_v - x)**2) / 2
        loss.backward()
        print('grad.norm', torch.norm(pd_v.grad))

    def test_loss_along_line(self, sample_id, n_iters):
        pd_path = join(self.pd_dir, 'pd_{:08d}.obj'.format(sample_id))
        pd_v, f = self.read_obj(pd_path, patch_id=self.patch_id)
        pd_v = torch.from_numpy(pd_v).to(device=self.device,
                                         dtype=self.dtype).unsqueeze(0)

        # gt_vt=np.load(join(self.data_root_dir,'lowres_skin_npys/skin_{:08d}.npy'.format(sample_id)))+np.load(join(self.data_root_dir,'lowres_offsets_i10/offset_{:08d}.npy'.format(sample_id)))
        gt_path = join(self.pd_dir, 'gt_{:08d}.obj'.format(sample_id))
        gt_v, f = self.read_obj(gt_path, patch_id=self.patch_id)
        gt_v = torch.from_numpy(gt_v).to(device=self.device,
                                         dtype=self.dtype).unsqueeze(0)

        proj_module = SpringOptModule(self.res_ctx, self.ctx)

        def f(x):
            for i in range(n_iters):
                x = proj_module(x)
            return torch.sum(((x - gt_v)**2).view(x.size(0), -1), dim=1) / 2

        pd_v.requires_grad_(True)
        loss = f(pd_v)
        loss.backward()
        g = pd_v.grad[0]
        pd_v.requires_grad_(False)

        loss_list = []
        total_n = 100
        processed_n = 0
        end = 2
        batch_size = 1
        while processed_n < total_n:
            x = pd_v.repeat(batch_size, 1, 1)
            for i in range(batch_size):
                t = (i + processed_n) / total_n * end
                x[i] -= t * g
            loss = f(x)
            loss_list += loss.tolist()
            processed_n += batch_size
        print(loss_list)
        np.savetxt(join(self.opt_dir, 'loss_{}.txt'.format(end)),
                   np.array(loss_list))

    def plot_loss_along_line(self, sample_id):
        end = 2
        loss = np.loadtxt(join(self.opt_dir, 'loss_{}.txt'.format(2)))
        x = np.linspace(0, end, len(loss))
        fig = plt.gcf()
        ax = plt.gca()
        ax.plot(x, loss)
        ax.set_title('iter=10')
        plot_path = join(self.opt_dir, 'loss_{}.png'.format(end))
        print('plot_path', plot_path)
        fig.savefig(plot_path)
Exemple #5
0
def init_ecos_opt_module(res_ctx,ctx):
    print('use_lap:',ctx['use_lap'])
    device,dtype=torch.device('cpu'),ctx['dtype']
    batch_size=ctx['batch_size']
    verbose=ctx['verbose'] if 'verbose' in ctx else False
    use_multi_thread=True
    use_debug=ctx['use_debug']
    cvx_opt_cpp.init(batch_size,verbose,use_multi_thread,use_debug)

    m,edges,l0=load_opt_data(res_ctx,ctx)
    patch_id=ctx['patch_id'] if 'patch_id' in ctx else -1
    if patch_id>=0:
        patch_manager=PatchManager(shared_data_dir=res_ctx['shared_data_dir'])
        patch_vt_ids=patch_manager.load_patch_vt_ids(patch_id)
        patch_edge_ids=patch_manager.get_patch_edge_ids(patch_vt_ids,edges)
        m=m[patch_vt_ids]
        l0=l0[patch_edge_ids]
        edges=patch_manager.get_patch_edges(patch_id,edges)
    m=torch.from_numpy(m).to(device=device,dtype=dtype)
    edges=torch.from_numpy(edges).to(device=device,dtype=torch.long)
    l0=torch.from_numpy(l0).to(device=device,dtype=dtype)
    if ctx['use_spring']:
        k=res_ctx['stiffness'] # set by load_opt_data
        if patch_id>=0:
            k=k[patch_edge_ids]
        res_ctx['stiffness']=k
        k=torch.from_numpy(k).to(device=device,dtype=dtype)
        cvx_opt_cpp.init_spring(k,ctx['lmd_k'])
        print('init_spring')

    if ctx['use_lap']:
        assert(patch_id<0)
        Lpr_np,Ljc_np,Lir_np=load_lap_matrix(res_ctx['shared_data_dir'],len(m))
        Lpr=torch.from_numpy(Lpr_np).to(device=device,dtype=dtype)
        Ljc=torch.from_numpy(Ljc_np[1:]).to(device=device,dtype=torch.long)
        Lir=torch.from_numpy(Lir_np).to(device=device,dtype=torch.long)
        print('init_lap')
        cvx_opt_cpp.init_lap(Lpr,Ljc,Lir,ctx['lmd_lap'])

    cvx_opt_cpp.init_forward(m,edges,l0)
    cvx_opt_cpp.init_backward()
    print('n_edges:',len(edges))

    maxit=ctx.get('maxit',50)
    feastol=ctx.get('feastol',1e-6)
    abstol=ctx.get('abstol',1e-6)
    reltol=ctx.get('reltol',5e-1)
    # reltol=ctx.get('reltol',1e-6)
    feastol_inacc=ctx.get('feastol_inacc',5e-3)
    abstol_inacc=ctx.get('abstol_inacc',1e-2)
    reltol_inacc=ctx.get('reltol_inacc',5e0)
    print('maxit',maxit,'feastol',feastol,'abstol',abstol,'reltol',reltol,'feastol_inacc',feastol_inacc,'abstol_inacc',abstol_inacc,'reltol_inacc',reltol_inacc)
    cvx_opt_cpp.init_options(maxit,feastol,abstol,reltol,feastol_inacc,abstol_inacc,reltol_inacc)

    module=EcosOptModule()
    module.edges=edges.numpy()
    module.m=m.numpy()
    module.l0=l0.numpy()
    if ctx['use_spring']:
        module.k=k

    if ctx['use_lap']:
        n_vts=len(m)
        module.L=csc_matrix((Lpr_np,Lir_np,Ljc_np),(n_vts,n_vts))

    return module
Exemple #6
0
    return ratios

def plot_ratios(path,ratios,title,xlim):
    ax=plt.gca()
    fig=plt.gcf()
    ax.hist(ratios,bins=20,range=xlim)
    fig.savefig(path)

if __name__=='__main__':
    shared_data_dir='../../shared_data_midres/'
    l0=np.loadtxt(join(shared_data_dir,'mat_or_med_linear.txt'))
    edges=np.loadtxt(join(shared_data_dir,'linear_edges.txt')).astype(np.int)

    patch_id=13
    if patch_id>=0:
        patch_manager=PatchManager(shared_data_dir=shared_data_dir)
        patch_vt_ids=patch_manager.load_patch_vt_ids(patch_id)
        patch_edge_ids=patch_manager.get_patch_edge_ids(patch_vt_ids,edges)
        l0=l0[patch_edge_ids]
        edges=patch_manager.get_patch_edges(patch_id,edges)

    ratios_path='figs/0528/ratios_vt.npy'
    png_path='figs/0528/ratios_vt.png'
    # ratios=compute_edge_lengths('../../rundir/midres_vt_patch/t0/eval_test/waist_front_hip_front_hip_right_waist_right','pd_{:08d}.obj',edges,l0)
    # np.save(ratios_path,ratios)
    # ratios=np.load(ratios_path)
    # plot_ratios(png_path,ratios,'w/o cvx',(0.8,1.2))

    ratios=np.load('figs/0528/ratios_avg.npy')
    plot_ratios('figs/0528/ratios_avg.png',ratios,'avg',(0.8,1.2))