def simulateHestonModel( T, N, R, mu, kappa, vBar, sigmaV, rho, x0, v0 ) : deltaT = T / (float)(N - 1) x = [af.constant(x0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32)] v = [af.constant(v0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32)] sqrtDeltaT = math.sqrt(deltaT) sqrtOneMinusRhoSquare = math.sqrt(1-rho**2) m = af.constant(0, 2, dtype=af.Dtype.f32) m[0] = rho m[1] = sqrtOneMinusRhoSquare zeroArray = af.constant(0, R, 1, dtype=af.Dtype.f32) for t in range(1, N) : tPrevious = (t + 1) % 2 tCurrent = t % 2 dBt = af.randn(R, 2, dtype=af.Dtype.f32) * sqrtDeltaT vLag = af.maxof(v[tPrevious], zeroArray) sqrtVLag = af.sqrt(vLag) x[tCurrent] = x[tPrevious] + (mu - 0.5 * vLag) * deltaT + sqrtVLag * dBt[:, 0] v[tCurrent] = vLag + kappa * (vBar - vLag) * deltaT + sigmaV * (sqrtVLag * af.matmul(dBt, m)) return (x[tCurrent], af.maxof(v[tCurrent], zeroArray))
def relu(image): #TODO: Remove assumption of image.dims()[3] == 1 if len(image.dims()) is 1: return af.maxof(image, af.constant(0, image.dims()[0])) elif len(image.dims()) is 3: d0, d1, d2 = image.dims() return af.maxof(image, af.constant(0, d0, d1, d2)) print "error, bad val num dims" return
def main(): T = 1 nT = 20 * T R_first = 1000 R = 5000000 x0 = 0 # initial log stock price v0 = 0.087**2 # initial volatility r = math.log(1.0319) # risk-free rate rho = -0.82 # instantaneous correlation between Brownian motions sigmaV = 0.14 # variance of volatility kappa = 3.46 # mean reversion speed vBar = 0.008 # mean variance k = math.log(0.95) # strike price # first run (x, v) = simulateHestonModel(T, nT, R_first, r, kappa, vBar, sigmaV, rho, x0, v0) # Price plain vanilla call option tic = time.time() (x, v) = simulateHestonModel(T, nT, R, r, kappa, vBar, sigmaV, rho, x0, v0) af.sync() toc = time.time() - tic K = math.exp(k) zeroConstant = af.constant(0, R, dtype=af.Dtype.f32) C_CPU = math.exp(-r * T) * af.mean(af.maxof(af.exp(x) - K, zeroConstant)) print("Time elapsed = {} secs".format(toc)) print("Call price = {}".format(C_CPU)) print(af.mean(v))
def monte_carlo_options(N, K, t, vol, r, strike, steps, use_barrier=True, B=None, ty=af.Dtype.f32): payoff = af.constant(0, N, 1, dtype=ty) dt = t / float(steps - 1) s = af.constant(strike, N, 1, dtype=ty) randmat = af.randn(N, steps - 1, dtype=ty) randmat = af.exp((r - (vol * vol * 0.5)) * dt + vol * math.sqrt(dt) * randmat) S = af.product(af.join(1, s, randmat), 1) if (use_barrier): S = S * af.all_true(S < B, 1) payoff = af.maxof(0, S - K) return af.mean(payoff) * math.exp(-r * t)
def main(): T = 1 nT = 20 * T R_first = 1000 R = 5000000 x0 = 0 # initial log stock price v0 = 0.087**2 # initial volatility r = math.log(1.0319) # risk-free rate rho = -0.82 # instantaneous correlation between Brownian motions sigmaV = 0.14 # variance of volatility kappa = 3.46 # mean reversion speed vBar = 0.008 # mean variance k = math.log(0.95) # strike price # first run ( x, v ) = simulateHestonModel( T, nT, R_first, r, kappa, vBar, sigmaV, rho, x0, v0 ) # Price plain vanilla call option tic = time.time() ( x, v ) = simulateHestonModel( T, nT, R, r, kappa, vBar, sigmaV, rho, x0, v0 ) af.sync() toc = time.time() - tic K = math.exp(k) zeroConstant = af.constant(0, R, dtype=af.Dtype.f32) C_CPU = math.exp(-r * T) * af.mean(af.maxof(af.exp(x) - K, zeroConstant)) print("Time elapsed = {} secs".format(toc)) print("Call price = {}".format(C_CPU)) print(af.mean(v))
def forward(nn_np, data): """ Given a dictionary representing a feed forward neural net and an input data matrix compute the network's output and store it within the dictionary :param nn: neural network dictionary :param data: a numpy n by m matrix where m in the number of input units in nn :return: the output layer activations """ nn = nn_np nn['activations'] = [] #prct = [] #prct.append(data[0][0]) #prct.append(data[1][0]) #src = data.astype(float) nsrc = data#af.Array(prct) nn['activations'].append(nsrc) #(af.Array(src.ctypes.data, src.shape, src.dtype.char)) nn['zs'] = [] for w, s, b in map(None, nn['weights'], nn['nonlin'], nn['biases']): #:wq #print af.transpose(nn['activations'][-1]) #print(type(nn['activations'][0])) #print(nn['activations'][0]) z = af.matmul(w, nn['activations'][-1]) #for i in range(w.shape[1]-1): # newB = af.join(1,newB,b) p = z.T + b nn['zs'].append(p.T) if len(p.shape) == 2: maxVal = af.constant(1e-5,p.shape[0],p.shape[1]).T else: maxVal = af.constant(1e-5,p.shape[0]).T q = af.maxof(p.T,1e-5)#p(i) = 1e-5 nn['activations'].append(q) return nn['activations'][-1]
def simulateHestonModel(T, N, R, mu, kappa, vBar, sigmaV, rho, x0, v0): deltaT = T / (float)(N - 1) x = [ af.constant(x0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32) ] v = [ af.constant(v0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32) ] sqrtDeltaT = math.sqrt(deltaT) sqrtOneMinusRhoSquare = math.sqrt(1 - rho**2) m = af.constant(0, 2, dtype=af.Dtype.f32) m[0] = rho m[1] = sqrtOneMinusRhoSquare zeroArray = af.constant(0, R, 1, dtype=af.Dtype.f32) for t in range(1, N): tPrevious = (t + 1) % 2 tCurrent = t % 2 dBt = af.randn(R, 2, dtype=af.Dtype.f32) * sqrtDeltaT vLag = af.maxof(v[tPrevious], zeroArray) sqrtVLag = af.sqrt(vLag) x[tCurrent] = x[tPrevious] + ( mu - 0.5 * vLag) * deltaT + sqrtVLag * dBt[:, 0] v[tCurrent] = vLag + kappa * (vBar - vLag) * deltaT + sigmaV * ( sqrtVLag * af.matmul(dBt, m)) return (x[tCurrent], af.maxof(v[tCurrent], zeroArray))
def monte_carlo_options(N, K, t, vol, r, strike, steps, use_barrier = True, B = None, ty = af.Dtype.f32): payoff = af.constant(0, N, 1, dtype = ty) dt = t / float(steps - 1) s = af.constant(strike, N, 1, dtype = ty) randmat = af.randn(N, steps - 1, dtype = ty) randmat = af.exp((r - (vol * vol * 0.5)) * dt + vol * math.sqrt(dt) * randmat); S = af.product(af.join(1, s, randmat), 1) if (use_barrier): S = S * af.all_true(S < B, 1) payoff = af.maxof(0, S - K) return af.mean(payoff) * math.exp(-r * t)
def forward(nn_np, data): """ Given a dictionary representing a feed forward neural net and an input data matrix compute the network's output and store it within the dictionary :param nn: neural network dictionary :param data: a numpy n by m matrix where m in the number of input units in nn :return: the output layer activations """ nn = nn_np nn['activations'] = [] #prct = [] #prct.append(data[0][0]) #prct.append(data[1][0]) #src = data.astype(float) nsrc = data #af.Array(prct) nn['activations'].append(nsrc) #(af.Array(src.ctypes.data, src.shape, src.dtype.char)) nn['zs'] = [] for w, s, b in map(None, nn['weights'], nn['nonlin'], nn['biases']): #:wq #print af.transpose(nn['activations'][-1]) #print(type(nn['activations'][0])) #print(nn['activations'][0]) z = af.matmul(w, nn['activations'][-1]) #for i in range(w.shape[1]-1): # newB = af.join(1,newB,b) p = z.T + b nn['zs'].append(p.T) if len(p.shape) == 2: maxVal = af.constant(1e-5, p.shape[0], p.shape[1]).T else: maxVal = af.constant(1e-5, p.shape[0]).T q = af.maxof(p.T, 1e-5) #p(i) = 1e-5 nn['activations'].append(q) return nn['activations'][-1]
def mandelbrot(data, it, maxval): C = data Z = data mag = af.constant(0, *C.dims()) for ii in range(1, 1 + it): # Doing the calculation Z = Z * Z + C # Get indices where abs(Z) crosses maxval cond = ((af.abs(Z) > maxval)).as_type(af.Dtype.f32) mag = af.maxof(mag, cond * ii) C = C * (1 - cond) Z = Z * (1 - cond) af.eval(C) af.eval(Z) return mag / maxval
def simple_arith(verbose = False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(3,3,dtype=af.Dtype.u32) b = af.constant(4, 3, 3, dtype=af.Dtype.u32) display_func(a) display_func(b) c = a + b d = a d += b display_func(c) display_func(d) display_func(a + 2) display_func(3 + a) c = a - b d = a d -= b display_func(c) display_func(d) display_func(a - 2) display_func(3 - a) c = a * b d = a d *= b display_func(c * 2) display_func(3 * d) display_func(a * 2) display_func(3 * a) c = a / b d = a d /= b display_func(c / 2.0) display_func(3.0 / d) display_func(a / 2) display_func(3 / a) c = a % b d = a d %= b display_func(c % 2.0) display_func(3.0 % d) display_func(a % 2) display_func(3 % a) c = a ** b d = a d **= b display_func(c ** 2.0) display_func(3.0 ** d) display_func(a ** 2) display_func(3 ** a) display_func(a < b) display_func(a < 0.5) display_func(0.5 < a) display_func(a <= b) display_func(a <= 0.5) display_func(0.5 <= a) display_func(a > b) display_func(a > 0.5) display_func(0.5 > a) display_func(a >= b) display_func(a >= 0.5) display_func(0.5 >= a) display_func(a != b) display_func(a != 0.5) display_func(0.5 != a) display_func(a == b) display_func(a == 0.5) display_func(0.5 == a) display_func(a & b) display_func(a & 2) c = a c &= 2 display_func(c) display_func(a | b) display_func(a | 2) c = a c |= 2 display_func(c) display_func(a >> b) display_func(a >> 2) c = a c >>= 2 display_func(c) display_func(a << b) display_func(a << 2) c = a c <<= 2 display_func(c) display_func(-a) display_func(+a) display_func(~a) display_func(a) display_func(af.cast(a, af.Dtype.c32)) display_func(af.maxof(a,b)) display_func(af.minof(a,b)) display_func(af.rem(a,b)) a = af.randu(3,3) - 0.5 b = af.randu(3,3) - 0.5 display_func(af.abs(a)) display_func(af.arg(a)) display_func(af.sign(a)) display_func(af.round(a)) display_func(af.trunc(a)) display_func(af.floor(a)) display_func(af.ceil(a)) display_func(af.hypot(a, b)) display_func(af.sin(a)) display_func(af.cos(a)) display_func(af.tan(a)) display_func(af.asin(a)) display_func(af.acos(a)) display_func(af.atan(a)) display_func(af.atan2(a, b)) c = af.cplx(a) d = af.cplx(a,b) display_func(c) display_func(d) display_func(af.real(d)) display_func(af.imag(d)) display_func(af.conjg(d)) display_func(af.sinh(a)) display_func(af.cosh(a)) display_func(af.tanh(a)) display_func(af.asinh(a)) display_func(af.acosh(a)) display_func(af.atanh(a)) a = af.abs(a) b = af.abs(b) display_func(af.root(a, b)) display_func(af.pow(a, b)) display_func(af.pow2(a)) display_func(af.exp(a)) display_func(af.expm1(a)) display_func(af.erf(a)) display_func(af.erfc(a)) display_func(af.log(a)) display_func(af.log1p(a)) display_func(af.log10(a)) display_func(af.log2(a)) display_func(af.sqrt(a)) display_func(af.cbrt(a)) a = af.round(5 * af.randu(3,3) - 1) b = af.round(5 * af.randu(3,3) - 1) display_func(af.factorial(a)) display_func(af.tgamma(a)) display_func(af.lgamma(a)) display_func(af.iszero(a)) display_func(af.isinf(a/b)) display_func(af.isnan(a/a)) a = af.randu(5, 1) b = af.randu(1, 5) c = af.broadcast(lambda x,y: x+y, a, b) display_func(a) display_func(b) display_func(c) @af.broadcast def test_add(aa, bb): return aa + bb display_func(test_add(a, b))
def simple_arith(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(3, 3) b = af.constant(4, 3, 3) display_func(a) display_func(b) c = a + b d = a d += b display_func(c) display_func(d) display_func(a + 2) display_func(3 + a) c = a - b d = a d -= b display_func(c) display_func(d) display_func(a - 2) display_func(3 - a) c = a * b d = a d *= b display_func(c * 2) display_func(3 * d) display_func(a * 2) display_func(3 * a) c = a / b d = a d /= b display_func(c / 2.0) display_func(3.0 / d) display_func(a / 2) display_func(3 / a) c = a % b d = a d %= b display_func(c % 2.0) display_func(3.0 % d) display_func(a % 2) display_func(3 % a) c = a**b d = a d **= b display_func(c**2.0) display_func(3.0**d) display_func(a**2) display_func(3**a) display_func(a < b) display_func(a < 0.5) display_func(0.5 < a) display_func(a <= b) display_func(a <= 0.5) display_func(0.5 <= a) display_func(a > b) display_func(a > 0.5) display_func(0.5 > a) display_func(a >= b) display_func(a >= 0.5) display_func(0.5 >= a) display_func(a != b) display_func(a != 0.5) display_func(0.5 != a) display_func(a == b) display_func(a == 0.5) display_func(0.5 == a) a = af.randu(3, 3, dtype=af.Dtype.u32) b = af.constant(4, 3, 3, dtype=af.Dtype.u32) display_func(a & b) display_func(a & 2) c = a c &= 2 display_func(c) display_func(a | b) display_func(a | 2) c = a c |= 2 display_func(c) display_func(a >> b) display_func(a >> 2) c = a c >>= 2 display_func(c) display_func(a << b) display_func(a << 2) c = a c <<= 2 display_func(c) display_func(-a) display_func(+a) display_func(~a) display_func(a) display_func(af.cast(a, af.Dtype.c32)) display_func(af.maxof(a, b)) display_func(af.minof(a, b)) display_func(af.rem(a, b)) a = af.randu(3, 3) - 0.5 b = af.randu(3, 3) - 0.5 display_func(af.abs(a)) display_func(af.arg(a)) display_func(af.sign(a)) display_func(af.round(a)) display_func(af.trunc(a)) display_func(af.floor(a)) display_func(af.ceil(a)) display_func(af.hypot(a, b)) display_func(af.sin(a)) display_func(af.cos(a)) display_func(af.tan(a)) display_func(af.asin(a)) display_func(af.acos(a)) display_func(af.atan(a)) display_func(af.atan2(a, b)) c = af.cplx(a) d = af.cplx(a, b) display_func(c) display_func(d) display_func(af.real(d)) display_func(af.imag(d)) display_func(af.conjg(d)) display_func(af.sinh(a)) display_func(af.cosh(a)) display_func(af.tanh(a)) display_func(af.asinh(a)) display_func(af.acosh(a)) display_func(af.atanh(a)) a = af.abs(a) b = af.abs(b) display_func(af.root(a, b)) display_func(af.pow(a, b)) display_func(af.pow2(a)) display_func(af.sigmoid(a)) display_func(af.exp(a)) display_func(af.expm1(a)) display_func(af.erf(a)) display_func(af.erfc(a)) display_func(af.log(a)) display_func(af.log1p(a)) display_func(af.log10(a)) display_func(af.log2(a)) display_func(af.sqrt(a)) display_func(af.cbrt(a)) a = af.round(5 * af.randu(3, 3) - 1) b = af.round(5 * af.randu(3, 3) - 1) display_func(af.factorial(a)) display_func(af.tgamma(a)) display_func(af.lgamma(a)) display_func(af.iszero(a)) display_func(af.isinf(a / b)) display_func(af.isnan(a / a)) a = af.randu(5, 1) b = af.randu(1, 5) c = af.broadcast(lambda x, y: x + y, a, b) display_func(a) display_func(b) display_func(c) @af.broadcast def test_add(aa, bb): return aa + bb display_func(test_add(a, b))
# Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af af.info() ITERATIONS = 200 POINTS = int(10.0 * ITERATIONS) Z = 1 + af.range(POINTS) / ITERATIONS win = af.Window(800, 800, "3D Plot example using ArrayFire") t = 0.1 while not win.close(): X = af.cos(Z * t + t) / Z Y = af.sin(Z * t + t) / Z X = af.maxof(af.minof(X, 1), -1) Y = af.maxof(af.minof(Y, 1), -1) Pts = af.join(1, X, Y, Z) win.plot3(Pts) t = t + 0.01
c >>= 2 af.display(c) af.display(a << b) af.display(a << 2) c = a c <<= 2 af.display(c) af.display(-a) af.display(+a) af.display(~a) af.display(a) af.display(af.cast(a, af.c32)) af.display(af.maxof(a, b)) af.display(af.minof(a, b)) af.display(af.rem(a, b)) a = af.randu(3, 3) - 0.5 b = af.randu(3, 3) - 0.5 af.display(af.abs(a)) af.display(af.arg(a)) af.display(af.sign(a)) af.display(af.round(a)) af.display(af.trunc(a)) af.display(af.floor(a)) af.display(af.ceil(a)) af.display(af.hypot(a, b)) af.display(af.sin(a))
def advection_step(u, v): ''' done - Matching u_new and v_new ''' u_w_bc, v_w_bc = add_boundary_conditions(u, v) u = af.moddims(u_w_bc, params.n, params.n) v = af.moddims(v_w_bc, params.n, params.n) u_tile = u[1:-1, 1:-1] v_tile = v[1:-1, 1:-1] u_new = af.np_to_af_array(np.zeros([params.n, params.n])) v_new = af.np_to_af_array(np.zeros([params.n, params.n])) x0_tile = af.tile(af.np_to_af_array(np.linspace(0, 1, params.n)), 1, params.n)[1:-1, 1:-1] y0_tile = af.transpose(x0_tile) reference_0_tile = af.constant(0, params.n - 2, params.n - 2, dtype=af.Dtype.f64) reference_1_tile = af.constant(1, params.n - 2, params.n - 2, dtype=af.Dtype.f64) x1_tile = af.minof( af.maxof(x0_tile - params.delta_t * u_tile, reference_0_tile), reference_1_tile) y1_tile = af.minof( af.maxof(y0_tile - params.delta_t * v_tile, reference_0_tile), reference_1_tile) i_left_tile = af.minof(af.cast(x1_tile * (params.n - 1), af.Dtype.s64), (params.n - 2) * reference_1_tile) i_left_flat = af.flat(i_left_tile) i_right_tile = i_left_tile + 1 i_right_flat = af.flat(i_right_tile) j_bottom_tile = af.minof(af.cast(y1_tile * (params.n - 1), af.Dtype.s64), (params.n - 2) * reference_1_tile) j_bottom_flat = af.flat(j_bottom_tile * params.n) j_top_tile = j_bottom_tile + 1 j_top_flat = af.flat(j_top_tile * params.n) x_left_tile = i_left_tile / (params.n - 1) x_right_tile = i_right_tile / (params.n - 1) y_bottom_tile = j_bottom_tile / (params.n - 1) y_top_tile = j_top_tile / (params.n - 1) print(x_left_tile) flat_u = af.flat(u) flat_v = af.flat(v) u_top_left_tile = af.moddims(flat_u[i_left_flat + j_top_flat], params.n - 2, params.n - 2) u_top_right_tile = af.moddims(flat_u[i_right_flat + j_top_flat], params.n - 2, params.n - 2) u_bottom_left_tile = af.moddims(flat_u[i_left_flat + j_bottom_flat], params.n - 2, params.n - 2) u_bottom_right_tile = af.moddims(flat_u[i_right_flat + j_bottom_flat], params.n - 2, params.n - 2) v_top_left_tile = af.moddims(flat_v[i_left_flat + j_top_flat], params.n - 2, params.n - 2) v_top_right_tile = af.moddims(flat_v[i_right_flat + j_top_flat], params.n - 2, params.n - 2) v_bottom_left_tile = af.moddims(flat_v[i_left_flat + j_bottom_flat], params.n - 2, params.n - 2) v_bottom_right_tile = af.moddims(flat_v[i_right_flat + j_bottom_flat], params.n - 2, params.n - 2) u_upper_tile = u_top_left_tile\ + (u_top_right_tile - u_top_left_tile)\ * (x1_tile - x_left_tile) / params.delta_x u_lower_tile = u_bottom_right_tile\ + (u_bottom_left_tile - u_bottom_right_tile)\ * (x1_tile - x_left_tile) / params.delta_x u_new_tile = u_lower_tile + (u_upper_tile - u_lower_tile)\ * (y1_tile - y_bottom_tile) / params.delta_x v_upper_tile = v_top_left_tile + (v_top_right_tile - v_top_left_tile)\ * (x1_tile - x_left_tile) / params.delta_x v_lower_tile = v_bottom_right_tile + (v_bottom_left_tile - v_bottom_right_tile)\ * (x1_tile - x_left_tile) / params.delta_x v_new_tile = v_lower_tile + (v_upper_tile - v_lower_tile)\ * (y1_tile - y_bottom_tile) / params.delta_x u_new = af.flat(u_new_tile) v_new = af.flat(v_new_tile) return u_new, v_new
c >>= 2 af.display(c) af.display(a << b) af.display(a << 2) c = a c <<= 2 af.display(c) af.display(-a) af.display(+a) af.display(~a) af.display(a) af.display(af.cast(a, af.c32)) af.display(af.maxof(a,b)) af.display(af.minof(a,b)) af.display(af.rem(a,b)) a = af.randu(3,3) - 0.5 b = af.randu(3,3) - 0.5 af.display(af.abs(a)) af.display(af.arg(a)) af.display(af.sign(a)) af.display(af.round(a)) af.display(af.trunc(a)) af.display(af.floor(a)) af.display(af.ceil(a)) af.display(af.hypot(a, b)) af.display(af.sin(a))