Example #1
0
def Rosen():

    args = {'x1': Ch(-120.), 'x2': Ch(-100.)}
    r1 = Ch(lambda x1, x2: (x2 - x1**2.) * 10., args)
    r2 = Ch(lambda x1: x1 * -1. + 1, args)

    func = [r1, r2]

    return func, [args['x1'], args['x2']]
Example #2
0
def lstsq(a, b, rcond=-1):
    if rcond != -1:
        raise Exception('non-default rcond not yet implemented')

    x = Ch(lambda a, b: pinv(a).dot(b))
    x.a = a
    x.b = b
    residuals = ch.sum((x.a.dot(x) - x.b)**2, axis=0)
    rank = NotImplementedError
    s = NotImplementedError

    return x, residuals, rank, s
Example #3
0
def LightDotNormal(num_verts):

    normalize_rows = lambda v : v / ch.sqrt(ch.sum(v.reshape((-1,3))**2, axis=1)).reshape((-1,1))
    sum_rows = lambda v :  ch.sum(v.reshape((-1,3)), axis=1)

    return Ch(lambda light_pos, v, vn :
        sum_rows(normalize_rows(light_pos.reshape((1,3)) - v.reshape((-1,3))) * vn.reshape((-1,3))))
Example #4
0
 def test_dogleg_madsen(self):
     obj = Madsen(x=Ch(np.array((3., 1.))))
     minimize(fun=obj,
              x0=[obj.x],
              method='dogleg',
              options={
                  'maxiter': 34,
                  'disp': False
              })
     self.assertTrue(np.sum(obj.r**2) / 2 < 0.386599528247)
Example #5
0
    def test_bfgs_madsen(self):
        from ch import SumOfSquares
        import scipy.optimize
        obj = Ch(lambda x: SumOfSquares(Madsen(x=x)))

        def errfunc(x):
            obj.x = Ch(x)
            return obj.r

        def gradfunc(x):
            obj.x = Ch(x)
            return obj.dr_wrt(obj.x).ravel()

        x0 = np.array((3., 1.))

        # Optimize with built-in bfgs.
        # Note: with 8 iters, this actually requires 14 gradient evaluations.
        # This can be verified by setting "disp" to 1.
        #tm = time.time()
        x1 = scipy.optimize.fmin_bfgs(errfunc,
                                      x0,
                                      fprime=gradfunc,
                                      maxiter=8,
                                      disp=0)
        #print 'forward: took %.es' % (time.time() - tm,)
        self.assertLess(obj.r / 2., 0.4)

        # Optimize with chumpy's minimize (which uses scipy's bfgs).
        obj.x = x0
        minimize(fun=obj,
                 x0=[obj.x],
                 method='bfgs',
                 options={
                     'maxiter': 8,
                     'disp': False
                 })
        self.assertLess(obj.r / 2., 0.4)
    def test_ic(self):
        child = Child(a=Ch(10))
        parent = Parent(child=child, aliased=Ch(50))

        junk = [parent.aliased_dependency for k in range(3)]
        self.assertTrue(parent.dcount == 1)
        self.assertTrue(parent.ocount == 0)
        self.assertTrue(parent.rcount == 0)

        junk = [parent.r for k in range(3)]
        self.assertTrue(parent.dcount == 1)
        self.assertTrue(parent.ocount == 1)
        self.assertTrue(parent.rcount == 1)

        parent.aliased = Ch(20)
        junk = [parent.aliased_dependency for k in range(3)]
        self.assertTrue(parent.dcount == 2)
        self.assertTrue(parent.ocount == 1)
        self.assertTrue(parent.rcount == 1)

        junk = [parent.r for k in range(3)]
        self.assertTrue(parent.dcount == 2)
        self.assertTrue(parent.ocount == 2)
        self.assertTrue(parent.rcount == 2)
Example #7
0
def LightDotNormal(num_verts):
    def normalize_rows(v):
        b = ch.sqrt(ch.sum(v.reshape((-1, 3))**2, axis=1)).reshape((-1, 1))
        return v / b.compute_r()

    sum_rows = lambda v: ch.sum(v.reshape((-1, 3)), axis=1)

    def f(light_pos, v, vn):
        light_pos = light_pos[0, ]
        a = np.array([light_pos, light_pos, light_pos])
        v = v[0, ]
        b = np.array([v, v, v])
        return sum_rows(normalize_rows(a - b) * vn.reshape((-1, 3)))

    return Ch(f)
Example #8
0
    def test_inv2(self):
        from linalg import Inv
                
        eps = 1e-8
        idx = 13

        mtx1 = np.random.rand(100).reshape((10,10))
        mtx2 = mtx1.copy()
        mtx2.ravel()[idx] += eps
        
        diff_emp = (np.linalg.inv(mtx2) - np.linalg.inv(mtx1)) / eps
        
        mtx1 = Ch(mtx1)
        diff_pred = Inv(mtx1).dr_wrt(mtx1)[:,13].reshape(diff_emp.shape)
        #print diff_emp
        #print diff_pred
        #print diff_emp - diff_pred
        self.assertTrue(np.max(np.abs(diff_pred.ravel()-diff_emp.ravel())) < 1e-4)
Example #9
0
    def test_svd(self):
        from linalg import Svd
        eps = 1e-3
        idx = 10

        data = np.sin(np.arange(300)*100+10).reshape((-1,3))
        data[3,:] = data[3,:]*0+10
        data[:,1] *= 2
        data[:,2] *= 4
        data = data.copy()
        u,s,v = np.linalg.svd(data, full_matrices=False)
        data = Ch(data)
        data2 = data.r.copy()
        data2.ravel()[idx] += eps
        u2,s2,v2 = np.linalg.svd(data2, full_matrices=False)


        svdu, svdd, svdv = Svd(x=data)

        # test singular values
        diff_emp = (s2-s) / eps
        diff_pred = svdd.dr_wrt(data)[:,idx]
        #print diff_emp
        #print diff_pred
        ratio = diff_emp / diff_pred
        #print ratio
        self.assertTrue(np.max(np.abs(ratio - 1.)) < 1e-4)
            
        # test V
        diff_emp = (v2 - v) / eps
        diff_pred = svdv.dr_wrt(data)[:,idx].reshape(diff_emp.shape)
        ratio = diff_emp / diff_pred
        #print ratio
        self.assertTrue(np.max(np.abs(ratio - 1.)) < 1e-2)

        # test U
        diff_emp = (u2 - u) / eps
        diff_pred = svdu.dr_wrt(data)[:,idx].reshape(diff_emp.shape)
        ratio = diff_emp / diff_pred
        #print ratio
        self.assertTrue(np.max(np.abs(ratio - 1.)) < 1e-2)
Example #10
0
    def test_inv1(self):
        from linalg import Inv

        mtx1 = Ch(np.sin(2**np.arange(9)).reshape((3,3)))
        mtx1_inv = Inv(mtx1)
        dr = mtx1_inv.dr_wrt(mtx1)

        eps = 1e-5
        mtx2 = mtx1.r.copy()
        input_diff = np.sin(np.arange(mtx2.size)).reshape(mtx2.shape) * eps
        mtx2 += input_diff
        mtx2_inv = Inv(mtx2)

        output_diff_emp = (np.linalg.inv(mtx2) - np.linalg.inv(mtx1.r)).ravel()
        output_diff_pred = Inv(mtx1).dr_wrt(mtx1).dot(input_diff.ravel())

        #print output_diff_emp
        #print output_diff_pred

        self.assertTrue(np.max(np.abs(output_diff_emp - output_diff_pred)) < eps*1e-4)
        self.assertTrue(np.max(np.abs(mtx1_inv.r - np.linalg.inv(mtx1.r)).ravel()) == 0)
Example #11
0
    def test_inv3(self):
        """Test linalg.inv with broadcasting support."""
        
        from linalg import Inv

        mtx1 = Ch(np.sin(2**np.arange(12)).reshape((3,2,2)))
        mtx1_inv = Inv(mtx1)
        dr = mtx1_inv.dr_wrt(mtx1)

        eps = 1e-5
        mtx2 = mtx1.r.copy()
        input_diff = np.sin(np.arange(mtx2.size)).reshape(mtx2.shape) * eps
        mtx2 += input_diff
        mtx2_inv = Inv(mtx2)

        output_diff_emp = (np.linalg.inv(mtx2) - np.linalg.inv(mtx1.r)).ravel()
        output_diff_pred = Inv(mtx1).dr_wrt(mtx1).dot(input_diff.ravel())

        # print output_diff_emp
        # print output_diff_pred

        self.assertTrue(np.max(np.abs(output_diff_emp.ravel() - output_diff_pred.ravel())) < eps*1e-3)
        self.assertTrue(np.max(np.abs(mtx1_inv.r - np.linalg.inv(mtx1.r)).ravel()) == 0)
Example #12
0
    def render(self,
               vertices,
               faces=None,
               img=None,
               camera_t=np.zeros([3], dtype=np.float32),
               camera_rot=np.zeros([3], dtype=np.float32),
               camera_center=None,
               use_bg=False,
               bg_color=(0.0, 0.0, 0.0),
               body_color=None,
               focal_length=5000,
               disp_text=False,
               gt_keyp=None,
               pred_keyp=None,
               **kwargs):
        if img is not None:
            height, width = img.shape[:2]
        else:
            height, width = self.height, self.width

        if faces is None:
            faces = self.faces

        if camera_center is None:
            camera_center = np.array([width * 0.5, height * 0.5])

        self.renderer.camera = ProjectPoints(rt=camera_rot,
                                             t=camera_t,
                                             f=focal_length * np.ones(2),
                                             c=camera_center,
                                             k=np.zeros(5))
        dist = np.abs(self.renderer.camera.t.r[2] -
                      np.mean(vertices, axis=0)[2])
        far = dist + 20

        self.renderer.frustum = {
            'near': 1.0,
            'far': far,
            'width': width,
            'height': height
        }

        if img is not None:
            if use_bg:
                self.renderer.background_image = img
            else:
                self.renderer.background_image = np.ones_like(img) * np.array(
                    bg_color)

        if body_color is None:
            color = self.colors['blue']
        else:
            color = self.colors[body_color]

        if isinstance(self.renderer, TexturedRenderer):
            color = [1., 1., 1.]

        self.renderer.set(v=vertices,
                          f=faces,
                          vt=self.vt,
                          ft=self.ft,
                          vc=color,
                          bgcolor=np.ones(3),
                          texture_image=self.tex)
        albedo = self.renderer.vc
        # Construct Back Light (on back right corner)
        yrot = np.radians(120)

        self.renderer.vc = Ch(np.ones([6890, 3]))

        tmp = self.renderer.r
        out = self.renderer.texcoord_image
        return out
Example #13
0
 def set_and_get_dr(self, x_in):
     self.x = Ch(x_in)
     return self.dr_wrt(self.x).flatten()
Example #14
0
 def set_and_get_r(self, x_in):
     self.x = Ch(x_in)
     return col(self.r)
Example #15
0
 def gradfunc(x):
     obj.x = Ch(x)
     return obj.dr_wrt(obj.x).ravel()
Example #16
0
 def errfunc(x):
     obj.x = Ch(x)
     return obj.r