def spread_of_news_model(p, k): assert isinstance(p, const) and isinstance(k, const) #t0 = 4 #t1 = ? #p = .5 * P => P(1 - e^(-k*4)) = .5*P (where t=4) => k = -0.25*ln(0.5) ~= 1.73 => f(t) = P(1 - e^(-1.73*t)) #p1 = .9 * P (p0 and p1 given) #we can now compute t1 #0.9*P = P(1 - e^(-1.73*t)) => t ~= 13.3 #generally #f(t) = P(1-e^(-kt)) we know that f(0) = 0 #where p0 is initial knowing pop at time t0 #and p1 is pop at time t1 #return f(t) #where f(t) = p*(1 - e^(-k*t)) #where k = (1/t0)*ln(p0) #so return p*(1 - e^(( -( (1/t0)*ln(p0) ) )*t)) #if given p0 and t0 #we are given k so: #return p*(1 - e^(-k*t)) return prod( p, plus( 1, prod(const(-1.0), make_e_expr(prod(prod(const(-1), k), make_pwr('t', 1))))))
def radioactive_decay(lmbda, p0, t): assert isinstance(lmbda, const) assert isinstance(p0, const) assert isinstance(t, const) #exponential decay is P(t) = p0 * e^(-lambda * t) return prod(p0, make_e_expr(prod(lmbda, make_pwr('t', 1))))
def prod_deriv(p): assert isinstance(p, prod) m1 = p.get_mult1() m2 = p.get_mult2() if isinstance(m1, const):# ie: 2 * x if isinstance(m2, const):# ie: 2 * 4 return make_const(0.0) elif is_valid_non_const_expr(m2): return flattenProduct(prod(m1,deriv(m2))) # elif isinstance(m2, pwr): # #m1*drv(m2) # return flattenProduct(prod(m1,deriv(m2))) # elif isinstance(m2, plus): # #(f*g)' = f'*g + f*g' but f is a constant so... # return flattenProduct(prod(m1,deriv(m2))) # elif isinstance(m2, prod): # return flattenProduct(prod(m1,deriv(m2))) else: raise Exception('prod_deriv: case 1' + str(p)) # elif isinstance(m1, plus): elif isinstance(m2, const): #(f*g)' = f'*g + f*g' where g' == 0 so (f*g)' = f'*g return flattenProduct(prod(m2,deriv(m1))) elif is_valid_non_const_expr(m1): #(f*g)' = f'*g + f*g' return plus( flattenProduct(prod(m2,deriv(m1))), flattenProduct(prod(m1,deriv(m2))) ) #full product rule else: raise Exception('prod_deriv: case 2:' + str(p))
def make_3rd_degree_poly(a, b, c, d): assert isinstance(a, const) assert isinstance(b, const) assert isinstance(c, const) assert isinstance(d, const) return plus( plus(plus(prod(a, make_pwr('x', 3.0)), prod(b, make_pwr('x', 2.0))), prod(c, make_pwr('x', 1.0))), prod(d, make_pwr('x', 0.0)))
def spread_of_news_model(p, k): assert isinstance(p, const) and isinstance(k, const) expr = prod( p, plus(make_const(-1.0), pwr(math.e, prod(make_const(-1.73), var("t"))))) return expr
def quot_deriv(p):# f/g = (gf'-fg')/g^2 quotient rule assert isinstance(p, quot) f = p.get_num() g = p.get_denom() if isinstance(f, const) and isinstance(g, const): return const(0) else: return quot(plus(prod(g, deriv(f)), prod(const(-1),prod(f, deriv(g)))), pwr(g, const(2.0)))
def percent_retention_model(lmbda, a): assert isinstance(lmbda, const) assert isinstance(a, const) #r(t) = (100 - a)*e^(-lmda*t) + a return plus( prod(plus(const(100.0), prod(const(-1.0), a)), make_e_expr(prod(prod(const(-1.0), lmbda), make_pwr('t', 1)))), a)
def find_poly_1_zeros(expr): firstpart = expr.get_elt1() a = firstpart.get_mult1() b = expr.get_elt2() fex1 = prod(mult1=b, mult2=-1) fex2 = make_quot(1, a) return const(val=prod(mult1=fex1, mult2=fex2))
def percent_retention_model(lmbda, a): assert isinstance(lmbda, const) assert isinstance(a, const) expr = plus( prod(plus(100, prod(a, const(-1.0))), pwr(math.e, prod(lmbda, prod(const(-1.0), var("t"))))), a) return expr
def solve_pdeq_with_init_cond(y0, k): assert isinstance(y0, const) assert isinstance(k, const) #y` = ky #y(0) = P_0 #and #y = P(t) = y(0)*e^(kt) = P_0*e^(kt) #return y0 * e^(k*x) return prod(y0, make_e_expr(prod(k, make_pwr('x', 1.0))))
def find_growth_model(p0, t, n): assert isinstance(p0, const) assert isinstance(t, const) assert isinstance(n, const) #p0 is C #n is k #t is t return prod(p0, make_e_expr(prod(quot(ln(n), t), make_pwr('t', 1))))
def pwr_deriv(p): assert isinstance(p, pwr) b = p.get_base() d = p.get_deg() if isinstance(b, var): if isinstance(d, const): return prod(d, pwr(b, const(d.get_val() - 1))) elif isinstance(d, plus): return prod(d, pwr(b, const(d.get_val() - 1))) else: raise Exception('pwr_deriv: case 1: ' + str(p)) if isinstance(b, pwr): # think this is (x^2 (^3)) if isinstance(d, const): return prod(b.get_base(), prod(b.get_deg(), const)) else: raise Exception('pwr_deriv: case 2: ' + str(p)) elif isinstance(b, plus): # (x+2)^3 if isinstance(d, const): return prod(d, pwr(b, d.get_val() - 1)) else: raise Exception('pwr_deriv: case 3: ' + str(p)) elif isinstance(b, prod): #(3x)^2 => (2*3*x)^(2-1) if isinstance(d, const): pwr(prod(d, prod(b.get_mult1(), b.get_mult2())), d.get_val() - 1) else: raise Exception('pwr_deriv: case 4: ' + str(p)) elif isinstance(b, quot): if isinstance(d, const): #b*d * deriv(quot)^d-1 return prod(prod(d, pwr(b, const(d.get_val() - 1))), deriv(b)) else: raise Exception('power_deriv: case 5: ' + str(p)) else: raise Exception('power_deriv: case 6: ' + str(p))
def flattenProduct(prd): while type(prd) == type(prod(const(1),const(2))) and type(prd.get_mult2()) == type(prod(const(1),const(2))) and type(prd.get_mult2().get_mult1()) == type(const(1)) and type(prd.get_mult1()) == type(const(1)): #while left is const and right is product with const in first arg prd = prod(const(prd.get_mult1().get_val()*prd.get_mult2().get_mult1().get_val()),prd.get_mult2().get_mult2())#combine left left = prd.get_mult1() right = prd.get_mult2() if type(right) == type(const(1)) and type(left) == type(const(1)): return const.mult(right,left) return prd
def quot_deriv(expr): #recursively compute the derivatvie of a quotient assert isinstance(expr, quot) numerator = expr.get_num() denominator = expr.get_denom() numeratorPrime = deriv(numerator) denominatorPrime = deriv(denominator) element1 = prod(denominator, numeratorPrime) element2 = prod(numerator, denominatorPrime) element3 = prod(make_const(-1.0), element2) element4 = plus(element1, element3) element5 = pwr(denominator, make_const(2.0)) exprPrime = quot(element4, element5) return exprPrime
def prod_logdiff(expr): assert isinstance(expr, prod) left = expr.get_mult1() right = expr.get_mult2() if isinstance(left, const):#c*()*()... return flattenProduct(prod(left,logdiff(right))) # elif isinstance(left, var):#x*()*()... # raise Exception('prod_logdiff: case 2:' + str(expr)) elif is_valid_non_const_expr(left):#g(x)*(()*()) return flattenProduct( prod(expr , deriv(ln(expr))) ) else: raise Exception('prod_logdiff: case 1:' + str(expr))
def ln_deriv(p): #ln[g(x)] = 1/g(x) * g'(x) assert isinstance(p, ln) g = p.get_expr() if isinstance(g, prod): m1 = g.get_mult1() m2 = g.get_mult2() #(x)(x+1) #ln(x) + ln(x+1) if isinstance(m1, pwr) and isinstance(m2, pwr): return plus(quot(prod(m1.get_deg(), deriv(m1.get_base())), m1.get_base()), quot(prod(m2.get_deg(), deriv(m2.get_base())), m2.get_base())) return plus(ln_deriv(make_ln(m1)), ln_deriv(make_ln(m2))) else: return prod(quot(const(1.0), g), deriv(g))
def cumprod(x, axis=-1): if not isinstance(x, Variable): x = Variable(x) if axis is None: x = x.reshape(-1) axis = 0 elif axis < 0: axis = x.ndim + axis assert axis >= 0 and axis < x.ndim xp = cuda.get_array_module(x) ndim = x.ndim dims = x.shape[axis] shape_new = x.shape[:axis] + (dims, ) + x.shape[axis:] x = functions.expand_dims(x, axis) x = functions.broadcast_to(x, shape_new) # TODO: use cupy.tril mask = numpy.tril(numpy.ones((dims, dims), numpy.bool)) if xp is cupy: mask = cuda.to_gpu(mask) expander = [1] * axis + [dims, dims] + [1] * (ndim - axis - 1) mask = mask.reshape(expander) mask = xp.broadcast_to(mask, shape_new) x = functions.where(mask, x, xp.ones_like(x.data)) return prod(x, axis + 1)
def prod(self, other, tensor=False): """ multiply two kernels (either on the same space, or on the tensor product of the input space) :param other: the other kernel to be added :type other: GPy.kern """ K1 = self.copy() K2 = other.copy() slices = [] for sl1, sl2 in itertools.product(K1.input_slices, K2.input_slices): s1, s2 = [False] * K1.input_dim, [False] * K2.input_dim s1[sl1], s2[sl2] = [True], [True] slices += [s1 + s2] newkernparts = [ prod(k1, k2, tensor) for k1, k2 in itertools.product(K1.parts, K2.parts) ] if tensor: newkern = kern(K1.input_dim + K2.input_dim, newkernparts, slices) else: newkern = kern(K1.input_dim, newkernparts, slices) newkern._follow_constrains(K1, K2) return newkern
def test_assgn_01_prob_02_ut_04(self): print('\n***** Assign 01: Unit Test 04 ************') fex1 = prod(mult1=make_const(2), mult2=make_pwr('x', 2.0)) fex2 = plus(elt1=fex1, elt2=make_const(2.0)) graph_drv(fex2, [-10, 10], [-50.0, 50.0]) print('Assign 01: Unit Test 04: pass')
def max_profit(cost_fun, rev_fun): profit = plus(cost_fun, prod(rev_fun,-1)) profit_deriv = deriv(profit) zeroes = find_poly_2_zeros(profit_deriv) return max(zeroes)
def spread_of_disease_model(p, t0, p0, t1, p1): assert isinstance(p, const) and isinstance(t0, const) assert isinstance(p0, const) and isinstance(t1, const) #f(t) = P/(1+B*e^(-c*t)) #p = 500,000 #let t0 = 0 such that f(t0) = f(0) #this would make t1 = delta_t #where delta_t = t1 - t0 #f(0) = p0 = 200 = 500,000/(1+B*e^0) = 500,000/(1+B) => B = 2499 #generally: B = (p-p0)/p0 #f(1) = p1 = 500 = 500,000/(1+2499*e^(-c*1)) => c = .92 #generally: c = -ln((p-p1)/(p1*B))/t #so we get f(t) = p/(1+((p-p0)/p0)*e^(-(-ln((p-p1)/(p1*((p-p0)/p0))))*t)) #or f(t) = p/(1+((p-p0)/p0)*e^((ln((p-p1)/(p1*((p-p0)/p0)))/(t1-t0)*t)) #return f(t) return quot( p, plus( const(1.0), prod( quot(plus(p, prod(const(-1.0), p0)), p0), make_e_expr( ln( prod( quot( quot( plus(p, prod(const(-1.0), p1)), prod( p1, quot(plus(p, prod(const(-1.0), p0)), p0))), plus(t1, prod(const(-1.0), t0))), make_pwr('t', 1)))))))
def mult_x(expr): #1/12x^2 - 10x + 300 if isinstance(expr, plus): if isinstance(expr.get_elt2(), const): return plus(mult_x(expr.get_elt1()), prod(expr.get_elt2(), make_pwr('x', 1.0))) else: return plus(mult_x(expr.get_elt1()), mult_x(expr.get_elt2())) elif isinstance(expr, pwr): if isinstance(expr.get_deg(), const): return pwr(expr.get_base(), const(expr.get_deg().get_val()+1)) else: return pwr(mult_x(expr.get_base()), mult_x(expr.get_deg())) elif isinstance(expr, prod): return prod(mult_x(expr.get_mult1()), mult_x(expr.get_mult2())) elif isinstance(expr, quot): return quot(mult_x(expr.get_num()), mult_x(expr.get_denom())) else: return expr
def ln_deriv(expr): assert isinstance(expr,ln) lnexpression = expr.get_expr() if isinstance(lnexpression,const): return const(0) elif isinstance(lnexpression,absv): return quot(const(1),lnexpression.get_expr()) else: return prod(quot(const(1), lnexpression), deriv(lnexpression))
def test_assgn_01_ut_06(self): print('\n***** Assign 01: Unit Test 06 ************') fex1 = prod(mult1=make_const(2.0), mult2=make_pwr('x', 7.0)) fex2 = plus(elt1=prod(mult1=make_const(-1.0), mult2=make_pwr('x', 5.0)), elt2=make_const(8.0)) p = plus(elt1=fex1, elt2=fex2) drv = deriv(p) assert not drv is None drvf = tof(drv) assert not drvf is None gt = lambda x: 14.0*(x**6) - 5.0*(x**4) err = 0.00001 for i in range(-100, -1): assert abs(drvf(i) - gt(i)) <= err for i in range(1, 100): assert abs(drvf(i) - gt(i)) <= err print('Assign 01: Unit Test 06: pass')
def pwr_deriv(p): assert isinstance(p, pwr) b = p.get_base() d = p.get_deg() if isinstance(b, var): #if base is a variable (ie x^2) if isinstance(d, const): #no 2^x garbage if d.get_val() == 0.0:#x^0 return make_const(0.0) neg1 = make_const(-1.0) new_d = const.add(const_flatten(d),neg1) if new_d.get_val() == 0.0:#TODO: Handle something like x^0 is already 1 # return d # print 'here' return const(1.0) return flattenProduct(prod(mult1=d,mult2=pwr(b,new_d))) else: raise Exception('pwr_deriv: case 1: ' + str(p)) elif is_valid_non_const_expr(b):#base is an expression ie: (x + 2)^2 or (2x)^2 etc if isinstance(d, const): if d.get_val() == 0.0: return make_const(0.0) neg1 = make_const(-1.0) new_d = d.add(const_flatten(d),neg1) if new_d.get_val() == 0.0:#TODO: Handle something like x^0 is already 1 return deriv(b) return flattenProduct(prod(mult1=flattenProduct(prod(mult1=d, mult2=pwr(b,new_d))), mult2=deriv(b))) else: raise Exception('pwr_deriv: case 2: ' + str(p)) elif isConstE(b): if isinstance(d, const): #f`(e^c) == 0, where c is a constant return make_const(0.0) elif is_valid_non_const_expr(d): #base is an expression ie: (x + 2)^2 or (2x)^2 etc # d/dx(e^f(x)) = f`(x)*e^f(x) return flattenProduct(prod( deriv(d), p )) #where d is f`(x) and p is e^f(x), ie the original expression else: raise Exception('pwr_deriv: case 4: ' + str(p)) elif isinstance(b, const) and isinstance(d, const): return make_const(0.0)# d/dx(c^c) = 0 else: raise Exception('power_deriv: case 3: ' + str(p) + ' --type-- ' + str(type(b)))
def plant_growth_model(m, t1, x1, t2, x2): assert isinstance(m, const) and isinstance(t1, const) assert isinstance(x1, const) and isinstance(x2, const) assert isinstance(x2, const) b = (m.get_val() / x1.get_val()) - 1 k = (np.log(((m.get_val() / x2.get_val()) - 1.0) / b)) / (-1 * m.get_val() * t2.get_val()) expr = quot( m, plus( const(1.0), prod( const(b), make_e_expr( prod(const(m.get_val() * -1), prod(const(k), pwr(var("t"), const(1.0)))))))) return expr
def tumor_volume_change(m, c, k): assert isinstance(m, const) assert isinstance(c, const) assert isinstance(k, const) yt = prod(const(k.get_val() * math.pi), pwr('r', 3.0)) dydt = dydt_given_x_dxdt(yt, m, const(-1 * c.get_val())) return dydt
def prod_deriv(p): assert isinstance(p, prod) m1 = p.get_mult1() # 6 m2 = p.get_mult2() # x^3 if isinstance(m1, const): if isinstance(m2, const): return const(0) elif isinstance(m2, pwr): # 6*(x^3)=> 6*3*(x^(3-1)) # 3x^1 becomes (1*3)x^0 => simplified is 3 if isinstance(m2.get_deg(), const) and m2.get_deg().get_val() == 1: return m1 else: # get 6 * 3 simplifiedAlt1 = const(m1.get_val() * m2.get_deg().get_val()) # get x^3-1 simplifiedExp = const(m2.get_deg().get_val() - 1) alt2 = pwr(m2.get_base(), simplifiedExp) return prod(simplifiedAlt1, alt2) elif isinstance(m2, plus): # 3*(x+1) if isinstance(deriv(m2), const): return const(0) else: return prod(m1, deriv(m2)) elif isinstance(m2, prod): # 4*(3x) if isinstance(deriv(m2), const): return const(0) else: return prod(m1, deriv(m2)) else: raise Exception('prod_deriv: case 0' + str(p)) elif isinstance(m1, plus): if isinstance(m2, const): # (x+1)*3 if isinstance(deriv(m2), const): return const(0) else: return prod(m1, deriv(m2)) else: raise Exception('prod_deriv: case 1:' + str(p)) elif isinstance(m1, pwr): if isinstance(m2, const): # (x^2)*3 => (2x^1)*3 if isinstance(deriv(m2), const): return const(0) else: return prod(deriv(m1), m2) else: raise Exception('prod_deriv: case 2:' + str(p)) elif isinstance(m1, prod): if isinstance(m2, const): #(3x)*4 if isinstance(deriv(m2), const): return const(0) else: return prod(deriv(m1), m2) else: return prod(m1, deriv(m2)) else: raise Exception('prod_deriv: case 4:' + str(p))
def test_assgn_01_ut_03(self): print('\n***** Assign 01: Unit Test 03 ************') prd = prod(mult1=make_const(2.0), mult2=make_pwr('x', 5.0)) drv = deriv(prd) assert not drv is None drvf = tof(drv) assert not drvf is None gt = lambda x: 10*x**4 err = 0.00001 for i in range(-100, 100): assert abs(drvf(i) - gt(i)) <= err print('Assign 01: Unit Test 03: pass')
def check_forward(self, x_data): x = chainer.Variable(x_data) y = functions.prod(x, axis=self.axis, keepdims=self.keepdims) self.assertEqual(y.data.dtype, self.dtype) y_expect = self.x.prod(axis=self.axis, keepdims=self.keepdims) if self.dtype == numpy.float16: options = {'atol': 1e-3, 'rtol': 1e-3} else: options = {} testing.assert_allclose(y_expect, y.data, **options)
def prod(self,other): """ multiply two kernels defined on the same spaces. :param other: the other kernel to be added :type other: GPy.kern """ K1 = self.copy() K2 = other.copy() newkernparts = [prod(k1,k2) for k1, k2 in itertools.product(K1.parts,K2.parts)] slices = [] for sl1, sl2 in itertools.product(K1.input_slices,K2.input_slices): s1, s2 = [False]*K1.D, [False]*K2.D s1[sl1], s2[sl2] = [True], [True] slices += [s1+s2] newkern = kern(K1.D, newkernparts, slices) newkern._follow_constrains(K1,K2) return newkern
def prod(self, other, tensor=False): """ multiply two kernels (either on the same space, or on the tensor product of the input space) :param other: the other kernel to be added :type other: GPy.kern """ K1 = self.copy() K2 = other.copy() slices = [] for sl1, sl2 in itertools.product(K1.input_slices, K2.input_slices): s1, s2 = [False] * K1.input_dim, [False] * K2.input_dim s1[sl1], s2[sl2] = [True], [True] slices += [s1 + s2] newkernparts = [prod(k1, k2, tensor) for k1, k2 in itertools.product(K1.parts, K2.parts)] if tensor: newkern = kern(K1.input_dim + K2.input_dim, newkernparts, slices) else: newkern = kern(K1.input_dim, newkernparts, slices) newkern._follow_constrains(K1, K2) return newkern