def compute_d1(self): # To stay consistent with numpy, we must upgrade 1D arrays to 2D ar = row(self.a.r) if len(self.a.r.shape)<2 else self.a.r.reshape((-1, self.a.r.shape[-1])) br = col(self.b.r) if len(self.b.r.shape)<2 else self.b.r.reshape((self.b.r.shape[0], -1)) if ar.ndim <= 2: return sp.kron(sp.eye(ar.shape[0], ar.shape[0]),br.T) else: raise NotImplementedError
def test_maximum(self): from blender_utils import row, col from ch import maximum # Make sure that when we compare the max of two *identical* numbers, # we get the right derivatives wrt both the_max = maximum(ch.Ch(1), ch.Ch(1)) self.assertTrue(the_max.r.ravel()[0] == 1.) self.assertTrue(the_max.dr_wrt(the_max.a)[0, 0] == 1.) self.assertTrue(the_max.dr_wrt(the_max.b)[0, 0] == 1.) # Now test given that all numbers are different, by allocating from # a pool of randomly permuted numbers. # We test combinations of scalars and 2d arrays. rnd = np.asarray(np.random.permutation(np.arange(20)), np.float64) c1 = ch.Ch(rnd[:6].reshape((2, 3))) c2 = ch.Ch(rnd[6:12].reshape((2, 3))) s1 = ch.Ch(rnd[12]) s2 = ch.Ch(rnd[13]) eps = .1 for first in [c1, s1]: for second in [c2, s2]: the_max = maximum(first, second) for which_to_change in [first, second]: max_r0 = the_max.r.copy() max_r_diff = np.max( np.abs(max_r0 - np.maximum(first.r, second.r))) self.assertTrue(max_r_diff == 0) max_dr = the_max.dr_wrt(which_to_change).copy() which_to_change.x = which_to_change.x + eps max_r1 = the_max.r.copy() emp_diff = (the_max.r - max_r0).ravel() pred_diff = max_dr.dot(col( eps * np.ones(max_dr.shape[1]))).ravel() #print 'comparing the following numbers/vectors:' #print first.r #print second.r #print 'empirical vs predicted difference:' #print emp_diff #print pred_diff #print '-----' max_dr_diff = np.max(np.abs(emp_diff - pred_diff)) #print 'max dr diff: %.2e' % (max_dr_diff,) self.assertTrue(max_dr_diff < 1e-14)
def test_transpose(self): from blender_utils import row, col from copy import deepcopy for which in ('C', 'F'): # test in fortran and contiguous mode a = ch.Ch( np.require(np.zeros(8).reshape((4, 2)), requirements=which)) b = a.T b1 = b.r.copy() #dr = b.dr_wrt(a).copy() dr = deepcopy(b.dr_wrt(a)) diff = np.arange(a.size).reshape(a.shape) a.x = np.require(a.r + diff, requirements=which) b2 = b.r.copy() diff_pred = dr.dot(col(diff)).ravel() diff_emp = (b2 - b1).ravel() np.testing.assert_array_equal(diff_pred, diff_emp)
def set_and_get_r(self, x_in): self.x = Ch(x_in) return col(self.r)