def log_loss(y_true, y_prob):
    """Compute Logistic loss for classification.
    Parameters
    ----------
    y_true : array-like or label indicator matrix
        Ground truth (correct) labels.
    y_prob : array-like of float, shape = (n_samples, n_classes)
        Predicted probabilities, as returned by a classifier's
        predict_proba method.
    Returns
    -------
    loss : float
        The degree to which the samples are correctly predicted.
    """
#    eps = np.finfo(y_prob.dtype).eps
#    y_prob = np.clip(y_prob, eps, 1 - eps)
#    if y_prob.shape[1] == 1:
#        y_prob = np.append(1 - y_prob, y_prob, axis=1)
#
#    if y_true.shape[1] == 1:
#        y_true = np.append(1 - y_true, y_true, axis=1)
#
#    return - xlogy(y_true, y_prob).sum() / y_prob.shape[0]

    eps = numpy.finfo(typemap(y_prob.dtype())).eps
    y_prob[y_prob < eps] = eps
    y_prob[y_prob > (1.0 - eps)] = 1.0 - eps

    if y_prob.numdims() == 1:
        y_prob = af.join(1, (1.0 - y_prob).as_type(y_prob.dtype()), y_prob)

    if y_true.numdims() == 1:
        y_true = af.join(1, (1.0 - y_true).as_type(y_true.dtype()), y_true)

    return - af.sum(af.flat(xlogy(y_true, y_prob))) / y_prob.shape[0]
Example #2
0
    def _initialize(self, rho_initial):

        # If option is given as user-defined:
        if (self.params.fields_initialize == 'user-defined'):

            E1, E2, E3 = self.initialize_E(self.q1, self.q2, self.params)
            B1, B2, B3 = self.initialize_B(self.q1, self.q2, self.params)

            # Scaling Appropriately
            self.E1_hat = 2 * fft2(E1) / (self.N_q1 * self.N_q2)
            self.E2_hat = 2 * fft2(E2) / (self.N_q1 * self.N_q2)
            self.E3_hat = 2 * fft2(E3) / (self.N_q1 * self.N_q2)
            self.B1_hat = 2 * fft2(B1) / (self.N_q1 * self.N_q2)
            self.B2_hat = 2 * fft2(B2) / (self.N_q1 * self.N_q2)
            self.B3_hat = 2 * fft2(B3) / (self.N_q1 * self.N_q2)

        # Initializing EM fields using Poisson Equation:
        else:
            compute_electrostatic_fields(self, rho_initial)

        self.fields_hat = af.join(
            0, af.join(0, self.E1_hat, self.E2_hat, self.E3_hat), self.B1_hat,
            self.B2_hat, self.B3_hat)

        af.eval(self.fields_hat)
        return
Example #3
0
def simple_data(verbose=False):
    display_func = _util.display_func(verbose)
    print_func   = _util.print_func(verbose)

    display_func(af.constant(100, 3,3, dtype=af.Dtype.f32))
    display_func(af.constant(25, 3,3, dtype=af.Dtype.c32))
    display_func(af.constant(2**50, 3,3, dtype=af.Dtype.s64))
    display_func(af.constant(2+3j, 3,3))
    display_func(af.constant(3+5j, 3,3, dtype=af.Dtype.c32))

    display_func(af.range(3, 3))
    display_func(af.iota(3, 3, tile_dims=(2,2)))

    display_func(af.identity(3, 3, 1, 2, af.Dtype.b8))
    display_func(af.identity(3, 3, dtype=af.Dtype.c32))

    a = af.randu(3, 4)
    b = af.diag(a, extract=True)
    c = af.diag(a, 1, extract=True)

    display_func(a)
    display_func(b)
    display_func(c)

    display_func(af.diag(b, extract = False))
    display_func(af.diag(c, 1, extract = False))

    display_func(af.join(0, a, a))
    display_func(af.join(1, a, a, a))

    display_func(af.tile(a, 2, 2))


    display_func(af.reorder(a, 1, 0))

    display_func(af.shift(a, -1, 1))

    display_func(af.moddims(a, 6, 2))

    display_func(af.flat(a))

    display_func(af.flip(a, 0))
    display_func(af.flip(a, 1))

    display_func(af.lower(a, False))
    display_func(af.lower(a, True))

    display_func(af.upper(a, False))
    display_func(af.upper(a, True))

    a = af.randu(5,5)
    display_func(af.transpose(a))
    af.transpose_inplace(a)
    display_func(a)

    display_func(af.select(a > 0.3, a, -0.3))

    af.replace(a, a > 0.3, -0.3)
    display_func(a)
Example #4
0
def simple_data(verbose=False):
    display_func = _util.display_func(verbose)

    display_func(af.constant(100, 3, 3, dtype=af.Dtype.f32))
    display_func(af.constant(25, 3, 3, dtype=af.Dtype.c32))
    display_func(af.constant(2**50, 3, 3, dtype=af.Dtype.s64))
    display_func(af.constant(2+3j, 3, 3))
    display_func(af.constant(3+5j, 3, 3, dtype=af.Dtype.c32))

    display_func(af.range(3, 3))
    display_func(af.iota(3, 3, tile_dims=(2, 2)))

    display_func(af.identity(3, 3, 1, 2, af.Dtype.b8))
    display_func(af.identity(3, 3, dtype=af.Dtype.c32))

    a = af.randu(3, 4)
    b = af.diag(a, extract=True)
    c = af.diag(a, 1, extract=True)

    display_func(a)
    display_func(b)
    display_func(c)

    display_func(af.diag(b, extract=False))
    display_func(af.diag(c, 1, extract=False))

    display_func(af.join(0, a, a))
    display_func(af.join(1, a, a, a))

    display_func(af.tile(a, 2, 2))

    display_func(af.reorder(a, 1, 0))

    display_func(af.shift(a, -1, 1))

    display_func(af.moddims(a, 6, 2))

    display_func(af.flat(a))

    display_func(af.flip(a, 0))
    display_func(af.flip(a, 1))

    display_func(af.lower(a, False))
    display_func(af.lower(a, True))

    display_func(af.upper(a, False))
    display_func(af.upper(a, True))

    a = af.randu(5, 5)
    display_func(af.transpose(a))
    af.transpose_inplace(a)
    display_func(a)

    display_func(af.select(a > 0.3, a, -0.3))

    af.replace(a, a > 0.3, -0.3)
    display_func(a)

    display_func(af.pad(a, (1, 1, 0, 0), (2, 2, 0, 0)))
Example #5
0
def arrayfire_perceptron_demo(dataset, num_classes=None):
    # Determine number of classes if not provided
    if num_classes is None:
        num_classes = np.amax(dataset[1] + 1)

    # Convert numpy array to af array (and convert labels/targets from ints to
    # one-hot encodings)
    train_feats = af.from_ndarray(dataset[0])
    train_targets = af.from_ndarray(ints_to_onehots(dataset[1], num_classes))
    test_feats = af.from_ndarray(dataset[2])
    test_targets = af.from_ndarray(ints_to_onehots(dataset[3], num_classes))

    num_train = train_feats.dims()[0]
    num_test = test_feats.dims()[0]

    # Add bias
    train_bias = af.constant(1, num_train, 1)
    test_bias = af.constant(1, num_test, 1)
    train_feats = af.join(1, train_bias, train_feats)
    test_feats = af.join(1, test_bias, test_feats)

    print('arrayfire perceptron classifier implementation')

    clf = AfPerceptron(alpha=0.1, maxerr=0.01, maxiter=1000, verbose=False)
    # Initial run to avoid overhead in training
    clf.train(train_feats, train_targets)
    clf.init_weights(train_feats, train_targets)

    # Benchmark training
    t0 = time.time()
    clf.train(train_feats, train_targets)
    clf.eval()
    t1 = time.time()
    dt_train = t1 - t0
    print('Training time: {0:4.4f} s'.format(dt_train))

    # Benchmark prediction
    iters = 100
    test_outputs = None
    t0 = time.time()
    for i in range(iters):
        test_outputs = clf.predict_proba(test_feats)
        af.eval(test_outputs)
        af.sync()
    t1 = time.time()
    dt = t1 - t0
    print('Prediction time: {0:4.4f} s'.format(dt / iters))

    print('Accuracy (test data): {0:2.2f}'.format(
        accuracy(test_outputs, test_targets)))

    # print('Accuracy on training data: {0:2.2f}'.format(accuracy(train_outputs, train_targets)))
    # print('Accuracy on testing data: {0:2.2f}'.format(accuracy(test_outputs, test_targets)))
    # print('Maximum error on testing data: {0:2.2f}'.format(abserr(test_outputs, test_targets)))

    return clf, dt_train
    def _train(self, X: af.Array, Y: af.Array, alpha: float,
               lambda_param: float, penalty: str, maxerr: float,
               maxiter: int) -> af.Array:
        # Add bias feature
        bias = af.constant(1, X.dims()[0], 1)
        X_biased = af.join(1, bias, X)

        # Initialize parameters to 0
        Weights = af.constant(0, X_biased.dims()[1], Y.dims()[1])

        for i in range(maxiter):
            # Get the cost and gradient
            J, dJ = self._cost(Weights, X_biased, Y, lambda_param, penalty)
            err = af.max(af.abs(J))
            if err < maxerr:
                Weights = Weights[1:]  # Remove bias weights
                return Weights

            # Update the weights via gradient descent
            Weights = Weights - alpha * dJ

        # Remove bias weights
        Weights = Weights[1:]

        return Weights
Example #7
0
def dump_coordinate_info(self, arrays, name, file_name):

    self._da_coord_arrays = PETSc.DMDA().create(
        [self.N_q1, self.N_q2],
        dof=len(arrays),
        proc_sizes=(self._nproc_in_q1, self._nproc_in_q2),
        ownership_ranges=self._ownership_ranges,
        comm=self._comm)
    self._glob_coord = self._da_coord_arrays.createGlobalVec()
    self._glob_coord_array = self._glob_coord.getArray()

    N_g = self.N_ghost

    for i in range(len(arrays)):
        if (i == 0):
            array_to_dump = arrays[0][:, :, N_g:-N_g, N_g:-N_g]
        else:
            array_to_dump = af.join(0, array_to_dump, arrays[i][:, :, N_g:-N_g,
                                                                N_g:-N_g])
    af.flat(array_to_dump).to_ndarray(self._glob_coord_array)
    PETSc.Object.setName(self._glob_coord, name)
    viewer = PETSc.Viewer().createBinary(file_name + '.bin',
                                         'w',
                                         comm=self._comm)
    viewer(self._glob_coord)
Example #8
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m_e = params.mass[0, 0]
    m_p = params.mass[0, 1]

    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk_electron = params.v1_bulk_electron
    v1_bulk_positron = params.v1_bulk_positron

    n = n_b + 0.01 * af.exp(-10 * (q1 - 5)**2)

    f_e = n * (m_e / (2 * np.pi * k * T_b))**(1 / 2) \
            * af.exp(-m_e * (v1[:, 0] - v1_bulk_electron)**2 / (2 * k * T_b)) \

    f_p = n * (m_p / (2 * np.pi * k * T_b))**(1 / 2) \
            * af.exp(-m_p * (v1[:, 1] - v1_bulk_positron)**2 / (2 * k * T_b)) \

    f = af.join(1, f_e, f_p)

    af.eval(f)
    return (f)
Example #9
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m_e = params.mass[0, 0]
    m_i = params.mass[0, 1]

    k = params.boltzmann_constant
    n = params.n_background * q1**0

    u_be = params.u_be
    u_bi = params.u_bi
    T = params.T_background

    f_e = n * (m_e / (2 * np.pi * k * T))**(3 / 2) \
            * 0.5 * (  af.exp(-m_e * (v1[:, 0] - u_be)**2 / (2 * k * T))
                     + af.exp(-m_e * (v1[:, 0] + u_be)**2 / (2 * k * T))
                    ) \
            * af.exp(-m_e * v2[:, 0]**2 / (2 * k * T)) \
            * af.exp(-m_e * v3[:, 0]**2 / (2 * k * T))

    f_i = n * (m_i / (2 * np.pi * k * T))**(3 / 2) \
            * 0.5 * (  af.exp(-m_i * (v1[:, 1] - u_bi)**2 / (2 * k * T))
                     + af.exp(-m_i * (v1[:, 1] + u_bi)**2 / (2 * k * T))
                    ) \
            * af.exp(-m_i * v2[:, 1]**2 / (2 * k * T)) \
            * af.exp(-m_i * v3[:, 1]**2 / (2 * k * T))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #10
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b1 = params.temperature_background_1
    T_b2 = params.temperature_background_2
    T_b3 = params.temperature_background_3

    k = params.boltzmann_constant

    n = n_b + params.amplitude * af.cos(params.k_q1 * q1)

    f1 = n * (m[0, 0] / (2 * np.pi * k * T_b1))**(1 / 2) \
           * af.exp(-m[0, 0] * v1[:, 0]**2 / (2 * k * T_b1))

    f2 = n * (m[0, 1] / (2 * np.pi * k * T_b2))**(1 / 2) \
           * af.exp(-m[0, 1] * v1[:, 1]**2 / (2 * k * T_b2))

    f3 = n * (m[0, 2] / (2 * np.pi * k * T_b3))**(1 / 2) \
           * af.exp(-m[0, 2] * v1[:, 2]**2 / (2 * k * T_b3))

    f = af.join(1, f1, f2, f3)

    af.eval(f)
    return (f)
Example #11
0
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)
Example #12
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m_e = params.mass[0, 0]
    m_i = params.mass[0, 1]

    k = params.boltzmann_constant

    n_b_e = params.n_background_e
    T_b_e = params.temperature_background_e

    n_b_i = params.n_background_i
    T_b_i = params.temperature_background_i

    n_e = n_b_e + params.alpha * af.cos(q1)
    n_i = n_b_i + 0 * q1
    T_e = T_b_e
    T_i = T_b_i

    f_e = n_e * np.sqrt(1 / (2 * np.pi)) * af.sqrt(m_e * T_i/m_i * T_e) \
              * af.exp(-0.5 * (m_e * T_i/m_i * T_e) * (v1[:, 0])**2)

    f_i = n_i * np.sqrt(1 / (2 * np.pi)) \
              * af.exp(-0.5 * (v1[:, 1])**2)

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
def histogram_deposition(current_indices_flat, currents_flat, grid_elements):
    '''
    function: histogram_deposition(current_indices_flat, currents_flat, grid)
    
    inputs: current_indices_flat, currents_flat, grid_elements
    
    current_indices_flat, currents_flat: They denote the indices and the currents
    to be deposited on the flattened current vector.
    
    grid_elements: The number of elements present the matrix/vector representing the 
    currents.   
    
    
    '''

    # setting default indices and current for histogram deposition
    indices_fix = af.data.range(grid_elements + 1, dtype=af.Dtype.s64)
    currents_fix = 0 * af.data.range(grid_elements + 1, dtype=af.Dtype.f64)

    # Concatenating the indices and currents in a single vector

    combined_indices_flat = af.join(0, indices_fix, current_indices_flat)
    combined_currents_flat = af.join(0, currents_fix, currents_flat)

    # Sort by key operation
    indices, currents = af.sort_by_key(combined_indices_flat,
                                       combined_currents_flat,
                                       dim=0)

    # scan by key operation with default binary addition operation which sums up currents
    # for the respective indices

    Histogram_scan = af.scan_by_key(indices, currents)

    # diff1 operation to determine the uniques indices in the current
    diff1_op = af.diff1(indices, dim=0)

    # Determining the uniques indices for current deposition
    indices_unique = af.where(diff1_op > 0)

    # Determining the current vector

    J_flat = Histogram_scan[indices_unique]

    af.eval(J_flat)

    return J_flat
Example #14
0
    def initialize_electric_fields(self):

        if('initialize_E' in dir(self.initialize)):
            
            E1 = self.initialize.initialize_E(self.q1_left_center,
                                              self.q2_left_center,
                                              self.params
                                             )[0]

            E2 = self.initialize.initialize_E(self.q1_center_bot,
                                              self.q2_center_bot,
                                              self.params
                                             )[1]

            E3 = self.initialize.initialize_E(self.q1_center,
                                              self.q2_center,
                                              self.params
                                             )[2]

        elif('initialize_A_phi' in dir(self.initialize)):

            A1 = self.initialize.initialize_A_phi(self.q1_center_bot,
                                                  self.q2_center_bot,
                                                  self.params
                                                 )[0]

            A2 = self.initialize.initialize_A_phi(self.q1_left_center,
                                                  self.q2_left_center,
                                                  self.params
                                                 )[1]

            A3 = self.initialize.initialize_A_phi(self.q1_left_bot,
                                                  self.q2_left_bot,
                                                  self.params
                                                 )[2]

            phi = self.initialize.initialize_A_phi(self.q1_center,
                                                   self.q2_center,
                                                   self.params
                                                  )[3]

            dA3_dq2 = (af.shift(A3, 0, 0,  0, -1) - A3) / self.dq2
            dA3_dq1 = (af.shift(A3, 0, 0, -1,  0) - A3) / self.dq1
            dA2_dq1 = (af.shift(A2, 0, 0, -1,  0) - A2) / self.dq1
            dA1_dq2 = (af.shift(A1, 0, 0,  0, -1) - A1) / self.dq2

            dphi_dq1 = -(af.shift(phi, 0, 0, 1, 0) - phi) / self.dq1
            dphi_dq2 = -(af.shift(phi, 0, 0, 0, 1) - phi) / self.dq2

            E1 =  dA3_dq2 - dphi_dq1
            E2 = -dA3_dq1 - dphi_dq2
            E3 = dA2_dq1 - dA1_dq2

        else:
            raise NotImplementedError('Initialization method for electric fields not valid/found')

        self.yee_grid_EM_fields[:3] = af.join(0, E1, E2, E3)
        af.eval(self.yee_grid_EM_fields)
        return
Example #15
0
def concatenate(arrays, axis=0):
    arrays = tuple(arrays)
    if len(arrays) == 0:
        raise ValueError('need at least one array to concatenate')
    base = arrays[0]
    if len(arrays) == 1:
        return base.copy()
    # arrayfire accepts at most 4 arrays to concatenate at once so we'll have
    # to chunk the arrays
    # The first case is special as we don't want to create unnecessary copies
    i = 0
    a = arrays[i].d_array
    if i+1 < len(arrays):
        b = arrays[i+1].d_array
    else:
        b = None
    if i+2 < len(arrays):
        c = arrays[i+2].d_array
    else:
        c = None
    if i+3 < len(arrays):
        d = arrays[i+3].d_array
    else:
        d = None            
    ret = arrayfire.join(pu.c2f(arrays[0].shape, axis), a, b, c, d)

    for i in range(4,len(arrays),4):
        a = ret.d_array
        if i < len(arrays):
            b = arrays[i].d_array
        else:
            b = None
        if i+1 < len(arrays):
            c = arrays[i+1].d_array
        else:
            c = None
        if i+2 < len(arrays):
            d = arrays[i+2].d_array
        else:
            d = None
            
        ret = arrayfire.join(pu.c2f(arrays[0].shape, axis), a, b, c, d)
    
    return ret
Example #16
0
File: dump.py Project: brryan/Bolt
def dump_moments(self, file_name):
    """
    This function is used to dump variables to a file for later usage.

    Parameters
    ----------

    file_name : str
                The variables will be dumped to this provided file name.

    Returns
    -------

    This function returns None. However it creates a file 'file_name.h5',
    containing all the moments that were defined under moments_defs in
    physical_system.

    Examples
    --------

    >> solver.dump_variables('boltzmann_moments_dump')

    The above set of statements will create a HDF5 file which contains the
    all the moments which have been defined in the physical_system object.
    The data is always stored with the key 'moments' inside the HDF5 file.
    Suppose 'density' and 'energy' are two these moments, and are declared
    the first and second in the moment_exponents object:

    These variables can then be accessed from the file using
    
    >> import h5py
    
    >> h5f = h5py.File('boltzmann_moments_dump.h5', 'r')
    
    >> rho = h5f['moments'][:][:, :, 0]
    
    >> E   = h5f['moments'][:][:, :, 1]
    
    >> h5f.close()
    """
    N_g = self.N_ghost

    i = 0
    for key in self.physical_system.moment_exponents:
        if (i == 0):
            array_to_dump = self.compute_moments(key)[:, N_g:-N_g, N_g:-N_g]
        else:
            array_to_dump = af.join(
                0, array_to_dump,
                self.compute_moments(key)[:, N_g:-N_g, N_g:-N_g])
        i += 1

    af.flat(array_to_dump).to_ndarray(self._glob_moments_array)
    PETSc.Object.setName(self._glob_moments, 'moments')
    viewer = PETSc.Viewer().createHDF5(file_name + '.h5', 'w', comm=self._comm)
    viewer(self._glob_moments)
Example #17
0
def concatenate(arrays, axis=0):
    if(len(arrays) < 1):
        raise ValueError('need at least one array to concatenate')
    if(axis > 3):
        raise NotImplementedError('only up to 4 axis as currently supported')
    arr = arrays[0].d_array.copy()
    axis = pu.c2f(arrays[0].shape, axis)
    for a in arrays[1:]:
        arr = arrayfire.join(axis, arr, a.d_array)
    return afnumpy.ndarray(pu.af_shape(arr), dtype=arrays[0].dtype, af_array=arr)
Example #18
0
def dct1(arr, norm=None):
    N = arr.dims()[0]
    out = 2 * af.real(
        af.exp(-0.5j * np.pi / N *
               af.range(*arr.dims(), dim=0, dtype=arr.dtype())) *
        af.fft(af.join(0, arr[0:N:2], af.flip(arr[1:N:2]))))
    if norm == 'ortho':
        out /= np.sqrt(2 * N)
        out[0] /= np.sqrt(2)
    return out
Example #19
0
    def update_user_defined_fields(self, time_elapsed):
        """
        Updates the cell-centered EM fields value using the value that is 
        returned by the user defined function at that particular time.

        Parameters
        ----------

        time_elapsed : double
                       Time at which the field values are to be evaluated.
        """

        E1, E2, E3 = self.params.user_defined_E(self.q1, self.q2, time_elapsed)

        B1, B2, B3 = self.params.user_defined_B(self.q1, self.q2, time_elapsed)

        self.cell_centered_EM_fields = af.join(0, E1, E2, E3,
                                               af.join(0, B1, B2, B3))

        return
Example #20
0
def concatenate(arrays, axis=0):
    if (len(arrays) < 1):
        raise ValueError('need at least one array to concatenate')
    if (axis > 3):
        raise NotImplementedError('only up to 4 axis as currently supported')
    arr = arrays[0].d_array.copy()
    axis = pu.c2f(arrays[0].shape, axis)
    for a in arrays[1:]:
        arr = arrayfire.join(axis, arr, a.d_array)
    return afnumpy.ndarray(pu.af_shape(arr),
                           dtype=arrays[0].dtype,
                           af_array=arr)
Example #21
0
def Verlet(initial_conditions,dt):

  x = initial_conditions[0:no_of_particles]
  y = initial_conditions[no_of_particles:2*no_of_particles]
  
  v_x = initial_conditions[2*no_of_particles:3*no_of_particles]
  v_y = initial_conditions[3*no_of_particles:4*no_of_particles]
  
  x_new   = x + v_x*dt
  v_x_new = v_x
  y_new   = y + v_y*dt
  v_y_new = v_y
  
  nextstep = af.join(0,x_new,y_new,v_x,v_y)
  return(nextstep)
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)
Example #23
0
def concatenate(arrays: tp.Tuple[ndarray, ...], axis: int = 0) -> ndarray:
    if len(arrays) < 2 or len(arrays) > 4:
        raise ValueError("the number of arrays to be concatenated is supposed "
                         "to be between two and four")

    first = arrays[0]._af_array
    second = arrays[1]._af_array
    third = None
    fourth = None

    if len(arrays) > 2:
        third = arrays[2]._af_array
        if len(arrays) > 3:
            fourth = arrays[3]._af_array

    af_array = af.join(axis, first, second, third, fourth)

    return ndarray(af_array)
Example #24
0
def initialize_f(q1, q2, v1, v2, v3, params):
    
    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk   = 0


    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * -5.745404152435185e-15 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.45462729344290764 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * -5.88418203051333e-15 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.2722586144213775 * af.sin(params.k_q1 * q1)
    
    v3_bulk_i =   params.amplitude * 0.4546272934429093 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 2.220446049250313e-16  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0.2722586144213809 * af.cos(params.k_q1 * q1) \
                - params.amplitude * -2.7755575615628914e-16 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #25
0
def initialize_f(q1, q2, v1, v2, v3, params):
    
    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk   = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * -2.7044279698172115e-17 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.5272181185265511 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * -1.2414728973845785e-16 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.21327009745028128 * af.sin(params.k_q1 * q1)
    
    v3_bulk_i =   params.amplitude * 0.5272181185265513 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0.21327009745028208 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #26
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * -8.677632316054021e-16 * af.cos(params.k_q1 * q1) \
       - params.amplitude * - 0.2853625652083089 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * -1.0205323999062932e-15  * af.cos(params.k_q1 * q1) \
                - params.amplitude * - 0.3876714549109159 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0.28536256520831227 * af.cos(params.k_q1 * q1) \
       - params.amplitude * 1.71364929624912e-16  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0.3876714549109187 * af.cos(params.k_q1 * q1) \
                - params.amplitude * -2.7755575615628914e-16 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #27
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * 0.07845711202586898 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * 0.5583486611611699 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.07845711202586896 * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.5583486611611693 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #28
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * -5.745404152435185e-15 * af.cos(params.k_q1 * q1) \
       - params.amplitude * - 0.16281859014475286 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * -5.88418203051333e-15 * af.cos(params.k_q1 * q1) \
                - params.amplitude * - 0.47061042449268503 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0.16281859014475358 * af.cos(params.k_q1 * q1) \
       - params.amplitude * 2.220446049250313e-16  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0.4706104244926854 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #29
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * 0.18699852141220014 * af.cos(params.k_q1 * q1) \
       - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * 0.4525906297083754 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
       - params.amplitude * 0.18699852141220033  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.4525906297083753 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #30
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * 0.6504875697582941 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * 0.08496465162562208 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * -0.6504875697582938  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * -0.08496465162562145 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #31
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * 0.5807459530914606 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * 0.1633005468170238 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * - 0.5807459530914602  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0 * af.cos(params.k_q1 * q1) \
                - params.amplitude * - 0.16330054681702416 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #32
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m1 = params.mass[0, 0]
    m2 = params.mass[0, 1]

    k = params.boltzmann_constant

    n1 = 1 + 0.01 * af.cos(2 * np.pi * q1)
    n2 = 1 + 0.02 * af.cos(4 * np.pi * q1)

    T1 = 1 + 0.02 * af.sin(2 * np.pi * q1)
    T2 = 100 + 0.01 * af.sin(4 * np.pi * q1)

    f1 = n1 * (1 / (2 * np.pi * k * T1))**(1 / 2) \
            * af.exp(-m1 * v1[:, 0]**2 / (2 * k * T1)) \

    f2 = n2 * (1 / (2 * np.pi * k * T2))**(1 / 2) \
            * af.exp(-m2 * v1[:, 1]**2 / (2 * k * T2)) \

    f = af.join(1, f1, f2)
    af.eval(f)
    return (f)
Example #33
0
def initialize_f(q1, q2, v1, v2, v3, params):

    m = params.mass
    k = params.boltzmann_constant

    n_b = params.density_background
    T_b = params.temperature_background

    k = params.boltzmann_constant

    v1_bulk = 0

    # Assigning separate bulk velocities
    v2_bulk_i =   params.amplitude * -4.801714581503802e-15 * af.cos(params.k_q1 * q1) \
                - params.amplitude *  0.6363571202013185 * af.sin(params.k_q1 * q1)

    v2_bulk_e =   params.amplitude * -4.85722573273506e-15 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 0.10249033165518363 * af.sin(params.k_q1 * q1)

    v3_bulk_i =   params.amplitude * 0.6363571202013188 * af.cos(params.k_q1 * q1) \
                - params.amplitude * 1.8041124150158794e-16  * af.sin(params.k_q1 * q1)

    v3_bulk_e =   params.amplitude * 0.10249033165518295 * af.cos(params.k_q1 * q1) \
                - params.amplitude * -3.885780586188048e-16 * af.sin(params.k_q1 * q1)

    n = n_b + 0 * q1**0

    f_e = n * (m[0, 0] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 0] * (v2[:, 0] - v2_bulk_e)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 0] * (v3[:, 0] - v3_bulk_e)**2 / (2 * k * T_b))

    f_i = n * (m[0, 1] / (2 * np.pi * k * T_b)) \
            * af.exp(-m[0, 1] * (v2[:, 1] - v2_bulk_i)**2 / (2 * k * T_b)) \
            * af.exp(-m[0, 1] * (v3[:, 1] - v3_bulk_i)**2 / (2 * k * T_b))

    f = af.join(1, f_e, f_i)

    af.eval(f)
    return (f)
Example #34
0
while (not simple_win.close()) and (not pretty_win.close()):
    delay = time()
    if (not simple_win.close()): simple_win.image(state)
    if (not pretty_win.close()): pretty_win.image(display)

    frame_count += 1
    if (frame_count % reset == 0):
        state = (af.randu(game_h, game_w) > 0.4).as_type(af.Dtype.f32)

    neighborhood = af.convolve(state, kernel)

    # state == 1 && neighborhood <  2 --> state = 0
    # state == 1 && neighborhood >  3 --> state = 0
    # state == 0 && neighborhood == 3 --> state = 1
    # else state remains un changed

    C0 = neighborhood == 2
    C1 = neighborhood == 3
    A0 = (state == 1) & (neighborhood < 2)
    A1 = (state != 0) & (C0 | C1)
    A2 = (state == 0) & C1
    A3 = (state == 1) & (neighborhood > 3)

    display = af.join(2, A0 + A1, A1 + A2, A3).as_type(af.Dtype.f32)

    state = state * C0 + C1

    while(time() - delay < (1.0 / fps)):
        pass
Example #35
0
# 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