예제 #1
0
파일: test_ir.py 프로젝트: zsoltc89/numba
            def foo(a, b, c=12, d=1j, e=None):
                f = a + b
                a += _FREEVAR
                g = np.zeros(c, dtype=np.complex64)
                h = f + g
                i = 1j / d
                if np.abs(i) > 0:
                    k = h / i
                    l = np.arange(1, c + 1)
                    with objmode():
                        print(e, k)
                    m = np.sqrt(l - g)
                    if np.abs(m[0]) < 1:
                        n = 0
                        for o in range(a):
                            n += 0
                            if np.abs(n) < 3:
                                break
                        n += m[2]
                    p = g / l
                    q = []
                    for r in range(len(p)):
                        q.append(p[r])
                        if r > 4 + 1:
                            with objmode(s='intp', t='complex128'):
                                s = 123
                                t = 5
                            if s > 122:
                                t += s
                        t += q[0] + _GLOBAL

                return f + o + r + t + r + a + n
예제 #2
0
 def do_scale(X, maxv, nthr):
     with numba.objmode(t0='f8'):
         t0 = time.time()
     #nthr = numba.get_num_threads()
     s = np.zeros((nthr, X.shape[1]))
     ss = np.zeros((nthr, X.shape[1]))
     mean = np.zeros(X.shape[1])
     std = np.zeros(X.shape[1])
     n = X.shape[0]
     for i in numba.prange(nthr):
         for r in range(i, n, nthr):
             for c in range(X.shape[1]):
                 v = X[r, c]
                 s[i, c] += v
                 ss[i, c] += v * v
     for c in numba.prange(X.shape[1]):
         s0 = s[:, c].sum()
         mean[c] = s0 / n
         std[c] = np.sqrt((ss[:, c].sum() - s0 * s0 / n) / (n - 1))
     with numba.objmode():
         print("finshed getting means, stddev", time.time() - t0)
     for (r, c) in numba.pndindex(X.shape):
         v = (X[r, c] - mean[c]) / std[c]
         X[r, c] = maxv if v > maxv else v
     with numba.objmode():
         print("finshed scaling values", time.time() - t0)
예제 #3
0
def issue_7356():
    with numba.objmode(before="intp"):
        DynClass.a = 100
        before = DynClass.a
    with numba.objmode(after="intp"):
        after = DynClass.a
    return before, after
예제 #4
0
def sqeqp_calculate(set_of_molecules, params, num_ats_types):
    multiplied_widths = np.empty((num_ats_types * 4, num_ats_types * 4),
                                 dtype=np.float64)
    for x in range(num_ats_types):
        for y in range(num_ats_types):
            multiplied_widths[x * 4][y *
                                     4] = np.sqrt(2 * params[x * 4 + 2]**2 +
                                                  2 * params[y * 4 + 2]**2)
    results = np.empty(set_of_molecules.num_of_ats, dtype=np.float64)
    index = 0
    for molecule in set_of_molecules.mols:
        with objmode(time1='f8'):
            time1 = time.perf_counter()
        num_of_at = molecule.num_of_ats
        new_index = index + num_of_at
        T = np.zeros((len(molecule.bonds), num_of_at))
        bonds = molecule.bonds
        for i in range(len(bonds)):
            at1, at2, _ = bonds[i]
            T[i, at1] += 1
            T[i, at2] -= 1
        matrix = np.zeros((num_of_at, num_of_at))
        vector = np.zeros(num_of_at)
        list_of_q0 = np.empty(num_of_at, dtype=np.float64)
        list_of_hardness = np.empty(num_of_at, dtype=np.float64)
        for i, par_index_i in enumerate(molecule.ats_ids):
            matrix[i, i] = params[par_index_i + 1]
            list_of_hardness[i] = params[par_index_i + 1]
            vector[i] = -params[par_index_i]
            list_of_q0[i] = params[par_index_i + 3]
            for j, (par_index_j, distance) in enumerate(
                    zip(molecule.ats_ids[i + 1:],
                        molecule.distance_matrix[i, i + 1:]), i + 1):
                d0 = multiplied_widths[par_index_i, par_index_j]

                matrix[i, j] = matrix[j, i] = erf(distance / d0) / distance

        list_of_q0 -= (np.sum(list_of_q0) -
                       molecule.total_chg) / len(list_of_q0)
        vector -= np.dot(matrix, list_of_q0)
        vector += list_of_hardness * list_of_q0
        A_sqe = np.dot(T, np.dot(matrix, T.T))
        B_sqe = np.dot(T, vector)
        for i, bond_params_index in enumerate(molecule.bonds_ids):
            A_sqe[i, i] += params[bond_params_index]
        results[index:new_index] = np.dot(np.linalg.solve(A_sqe, B_sqe),
                                          T) + list_of_q0
        index = new_index
        with objmode():
            print('name:{}  noa:{} time:{}'.format(
                molecule.name, molecule.num_of_ats,
                time.perf_counter() - time1))
    return results
예제 #5
0
def _fast_copy3(data, dataA, indices, indicesA, starts, ends, k, m):
    for i in numba.prange(k):
        for _ in range(m):
            with numba.objmode():
                _waitload(i)
            length = ends[i] - starts[i]
            data[starts[i]:ends[i]] = dataA[i * 1024 * 1024:i * 1024 * 1024 +
                                            length]
            indices[starts[i]:ends[i]] = indicesA[i * 1024 *
                                                  1024:i * 1024 * 1024 +
                                                  length]
            with numba.objmode():
                _signalcopy(i)
예제 #6
0
파일: SeqModel.py 프로젝트: bkrosenz/ipcoal
def jevolve_branch_probs(brlenQ):
    """
    jitted wrapper to allow scipy call within numba loop
    """
    with objmode(probs='float64[:,:]'):
        probs = expm(brlenQ)
    return probs
예제 #7
0
def unique_arrays(X):
    inds = np.zeros((X.shape[0], ), dtype=np.int64)
    with objmode(inds='i8[:]'):
        inds += argsort_arrays(X)
    print(inds)
    u = _unique_arrays(X[inds])
    return u
예제 #8
0
 def objmode_func():
     """
     Wrapper to call py_func from objmode. This tests
     large kws with objmode. If the definition for the
     call is not properly updated this test will fail.
     """
     with objmode(
             a='int64',
             b='int64',
             c='int64',
             d='int64',
             e='int64',
             f='int64',
             g='int64',
             h='int64',
             i='int64',
             j='int64',
             k='int64',
             l='int64',
             m='int64',
             n='int64',
             o='int64',
             p='int64',
     ):
         (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) = py_func()
     return (a + b + c + d + e + f + g + h + i + j + k + l + m + n + o +
             p)
예제 #9
0
 def moderror():
     with objmode(v1=types.intp, v2=types.THIS_DOES_NOT_EXIST,
                  v3=types.float32):
         v1 = 12.3
         v2 = 12.3
         v3 = 12.3
     return val
예제 #10
0
파일: nndescent.py 프로젝트: quinnhj/umap
def nn_descent_internal_high_memory(
    current_graph,
    data,
    n_neighbors,
    rng_state,
    tried,
    max_candidates=50,
    dist=dist.euclidean,
    n_iters=10,
    delta=0.001,
    rho=0.5,
    verbose=False,
):
    n_vertices = data.shape[0]

    for n in range(n_iters):
        with numba.objmode():
            # Call into object mode to temporarily sleep (and thus release GIL)
            logging.info("(obj mode) high mem nn descent iter.")
            time.sleep(0.05)

        if verbose:
            print("\t", n, " / ", n_iters)

        (new_candidate_neighbors, old_candidate_neighbors) = new_build_candidates(
            current_graph, n_vertices, n_neighbors, max_candidates, rng_state, rho
        )

        c = 0
        for i in range(n_vertices):
            for j in range(max_candidates):
                p = int(new_candidate_neighbors[0, i, j])
                if p < 0:
                    continue
                for k in range(j, max_candidates):
                    q = int(new_candidate_neighbors[0, i, k])
                    if q < 0 or (p, q) in tried:
                        continue

                    d = dist(data[p], data[q])
                    c += unchecked_heap_push(current_graph, p, d, q, 1)
                    tried.add((p, q))
                    if p != q:
                        c += unchecked_heap_push(current_graph, q, d, p, 1)
                        tried.add((q, p))

                for k in range(max_candidates):
                    q = int(old_candidate_neighbors[0, i, k])
                    if q < 0 or (p, q) in tried:
                        continue

                    d = dist(data[p], data[q])
                    c += unchecked_heap_push(current_graph, p, d, q, 1)
                    tried.add((p, q))
                    if p != q:
                        c += unchecked_heap_push(current_graph, q, d, p, 1)
                        tried.add((q, p))

        if c <= delta * n_neighbors * data.shape[0]:
            return
예제 #11
0
 def evolution_rate(state_data: np.ndarray,
                    t: float = 0) -> np.ndarray:
     out = np.empty(data_shape)
     with nb.objmode():
         data_tpl = get_data_tuple(state_data)
         wrap(data_tpl, t, out)
     return out
예제 #12
0
def find_nu(bleps, leptons, met, nu_array):
    for idx in range(bleps.shape[0]):
            # blep doesn't exist for this event
        if (bleps[idx, 3] == -999): continue
            ## run NS to get nschi2 to be used solver
        with objmode():
            pynusolver.run_nu_solver(leptons[idx], bleps[idx], met[idx], nu_array[idx]) # input order for nusolver is (lepton, jet, met, nu)

    return nu_array
예제 #13
0
 def foo():
     # t1 is a string
     # t2 is a global type
     # t3 is a non-local/freevar
     with objmode(t1="float64", t2=gv_type, t3=array_ty):
         t1 = 793856.5
         t2 = t1  # to observe truncation
         t3 = np.arange(5).astype(np.int32)
     return t1, t2, t3
예제 #14
0
파일: eks.py 프로젝트: RaymondSuTMY/kal-cal
def numpy_algorithm(m: np.ndarray, P: np.ndarray, Q: np.ndarray):

    # State dimensions
    n_time = m.shape[0]

    # Original State Shape
    gains_shape = m.shape[1:]

    # Smooth State Vectors
    ms = np.zeros_like(m)

    # Smooth Covariance matrices
    Ps = np.zeros_like(P)
    G_values = np.zeros_like(P)

    # Set Initial Smooth Values
    ms[-1] = m[-1]
    Ps[-1] = P[-1]

    # Run Extended Kalman Smoother with
    # Numpy matrices
    head = "==> Extended Kalman Smoother (NUMPY|JIT): "
    for k in range(-2, -(n_time + 1), -1):

        # Progress Bar in object-mode
        with objmode():
            bar_len = 100
            total = n_time - 1
            filled_len = int(round(bar_len * (-k - 1) / float(n_time - 1)))
            bar = u"\u2588" * filled_len + ' '\
                    * (bar_len - filled_len)
            print("\r%s%d%%|%s| %d/%d" %
                  (head, (-k - 1) / total * 100, bar, -k - 1, total),
                  end="")

        # Predict Step
        mp = gains_vector(m[k])
        Pt = P[k].astype(np.complex128)
        Pp = Pt + Q

        # Smooth Step
        Pinv = np.linalg.inv(Pp).astype(np.complex128)
        G = Pt @ Pinv

        # Record Posterior Smooth Values
        e = gains_vector(ms[k + 1]) - mp
        E = (Ps[k + 1] - Pp).astype(np.complex128)
        ms[k] = gains_reshape(mp + G @ e, gains_shape)
        Ps[k] = np.diag(np.diag(Pt + G @ E @ G.T).real)

        G_values[k] = G.real

    # Newline
    print()

    # Return Posterior smooth states and covariances
    return ms, Ps, G_values
예제 #15
0
def warn(msg, file, context=None, return_value=None):
    with numba.objmode():
        print(msg, file=sys.stderr)
        print("\tfile:", file, file=sys.stderr)
        if context is not None:
            print("\tcontext:", file=sys.stderr)
            for var in context:
                print("\t\t", var, file=sys.stderr)
    return return_value
예제 #16
0
 def solve(a, b):
     with numba.objmode(ret=ret_sig):
         ret = scipy.linalg.solve_triangular(
             a,
             b,
             lower=lower,
             # check_finite=check_finite
         )
     return ret
예제 #17
0
def _chunk_to_polar_njit(
    images,
    pimage_shape,
    delta_r,
    delta_theta,
    max_r,
    find_maximum,
    direct_beam_positions,
):
    polar_chunk = np.empty(
        (images.shape[0], images.shape[1], pimage_shape[0], pimage_shape[1]),
        dtype=np.float64,
    )
    # somewhat ugly solution because numba does not accept array of None
    if direct_beam_positions is not None:
        for idx in prange(images.shape[0]):
            for idy in prange(images.shape[1]):
                image = images[idx, idy]
                with objmode(polar_image="float64[:,:]"):
                    dbp = direct_beam_positions[idx, idy]
                    polar_image = image_to_polar(
                        image,
                        delta_r=delta_r,
                        delta_theta=delta_theta,
                        max_r=max_r,
                        find_direct_beam=find_maximum,
                        direct_beam_position=dbp,
                    )
                polar_chunk[idx, idy] = polar_image
    else:
        for idx in prange(images.shape[0]):
            for idy in prange(images.shape[1]):
                image = images[idx, idy]
                with objmode(polar_image="float64[:,:]"):
                    polar_image = image_to_polar(
                        image,
                        delta_r=delta_r,
                        delta_theta=delta_theta,
                        max_r=max_r,
                        find_direct_beam=find_maximum,
                        direct_beam_position=None,
                    )
                polar_chunk[idx, idy] = polar_image
    return polar_chunk
예제 #18
0
def numba_loop(fx, fy, fx_coord, fy_coord, xs, ys, pixelsize, force_shift,
               out_put_shape, h, E, sigma, u_out, v_out):

    for i, (f_x, f_y, x, y) in enumerate(zip(fx, fy, fx_coord, fy_coord)):
        dist_x = xs - x
        dist_y = ys - y

        # greens tensor, As are central elements of the tensor
        # makeing sure coordinates are shifted and distance is never exactly zero ... (maybe just exlude zero????)
        for i in range(dist_x.shape[0]):
            for j in range(dist_x.shape[1]):
                if dist_x[i, j] == 0:
                    dist_x[i, j] += force_shift

        for i in range(dist_y.shape[0]):
            for j in range(dist_y.shape[1]):
                if dist_y[i, j] == 0:
                    dist_y[i, j] += force_shift

        dist_x = dist_x * pixelsize
        dist_y = dist_y * pixelsize

        r = np.sqrt(dist_x**2 + dist_y**2)

        ### elements of the greens tensor
        # Usefull parts // this is just an approximation
        # /also only for sigma=0.49
        s = r / h
        mu = E / (2 * (1 + sigma))
        A1 = ((2 - sigma) /
              (4 * np.pi * mu * h * s)) * (0.12 * np.exp(-0.43 * s) +
                                           0.88 * np.exp(-0.83 * s))
        A2 = -(sigma /
               (4 * np.pi * mu * h * s)) * (1 + 1.22 * s + 1.31 *
                                            (s**2.23)) * np.exp(-1.25 * s)
        # A3_b = ((1-2*sigma)/(4*np.pi*mu*h*s))
        # A3 = -0.063 * ((np.exp(-0.44 * s) - np.exp(-2.79 * s)) ** 2)#*A3_b
        # A4 = ((2 * (1 - sigma)) / (4 * np.pi * mu * h * s)) * (1 + 0.46 * s - 2.50 * (s ** 2.13)) * np.exp(-2.18 * s)

        # components of the greens tensor
        K1 = A1 - ((dist_x**2 - dist_y**2) / (r**2)) * A2
        K2 = -(2 * dist_x * dist_y / (r**2)) * A2
        # K3 = -(dist_x / r) * A3
        K4 = -(2 * dist_x * dist_y / (r**2)) * A2  # is K2
        K5 = A1 + ((dist_x**2 - dist_y**2) / (r**2)) * A2

        def_u = f_x * K1 + f_y * K2
        def_v = f_x * K4 + f_y * K5
        u_out += def_u
        v_out += def_v
        # show_quiver(def_u,def_v)
        with objmode():
            if i % 100 == 0:
                print("###", i)

    return u_out, v_out
예제 #19
0
 def perform(*inputs):
     with numba.objmode(ret=ret_sig):
         outputs = [[None] for i in range(n_outputs)]
         op.perform(node, inputs, outputs)
         outputs = tuple([o[0] for o in outputs])
         if n_outputs == 1:
             ret = outputs[0]
         else:
             ret = outputs
     return ret
예제 #20
0
 def test_objmode():
     x = np.arange(5)
     y = np.zeros_like(x)
     try:
         with objmode(y='intp[:]'):  # annotate return type
             # this region is executed by object-mode.
             y += bar(x)
     except Exception:
         pass
     return y
def render(image, camera, details, start_time, thread_id=0):
    mempool = jit_core.MemoryPool(NUM_SAMPLES)
    random.seed(RANDOM_SEED)
    row_step = CPU_COUNT
    row_start = thread_id

    for j in range(row_start, camera.height, row_step):
        for i in range(camera.width):
            jj = camera.height - 1 - j
            ii = camera.width - 1 - i

            for sx in range(SUPERSAMPLING):
                for sy in range(SUPERSAMPLING):

                    # compute shade
                    c = np.zeros(3)
                    for _ in range(NUM_SAMPLES):
                        mempool.result[0:3] = 0.0
                        camera.get_ray(i, j, sx, sy, mempool)
                        start_trace(details, mempool)
                        mempool.result /= NUM_SAMPLES
                        c += mempool.result
                    clamp(c)
                    c /= (SUPERSAMPLING * SUPERSAMPLING)
                    image[jj, ii] += c

            gamma_correction(image[jj, ii])

        with numba.objmode():
            p = (j + 1) / camera.height
            print('. completed : %.2f' % (p * 100.0), ' %')
            if time.time() != start_time:
                t = time.time() - start_time
                estimated_time_left = (1.0 - p) / p * t
                print('    estimated time left: %.2f sec (threadId %d)' %
                      (estimated_time_left, thread_id))

    with numba.objmode():
        print('Total intersections : %d (threadId %d)' %
              (mempool.total_intersection, thread_id))

    return mempool.total_intersection
예제 #22
0
 def monopole_data(r, n, domain_index, result):
     with numba.objmode():
         result[0] = 0
         for i in range(len(self.q)):
             pos = np.linalg.norm(r - self.r0[i])
             val = self.q[i] * np.exp(
                 1j * k * pos) / (4 * np.pi * pos)
             result[0] += -(
                 1j * self.mu[domain_index][fi] * k * val - val /
                 (pos * pos) *
                 (1j * k * pos - 1) * np.dot(r - self.r0[i], n))
예제 #23
0
def beam_search(beam: Beam, conflicts: np.ndarray):
  """ Grows the search tree using beam """
  for level in range(1, beam.n):
    if level == 2:
      #####
      # Starting counting time after first iteration is done
      # to remove numba compilation time from measurements.
      # The loss in precision is negligble, the first iteration
      # contains only two possible child, so the computing of all children
      # is very cheap.
      #####
      # print("Starting time")
      with objmode(time_start='f8'):
        time_start = time.time()
    index_max = compute_all_children(beam, conflicts, level)
    commit_children(beam, index_max)
    clear_children(beam)
  with objmode(time_search='f8'):
    time_search = time.time() - time_start
  return time_search
예제 #24
0
def homomorphic_filter(image, cutoff_freq=10, a=0.75, b=1.0):
    """
    Performs homomorphic filter on image using gaussian high-frequency filter
    Implementation is adapted from https://github.com/glasgio/homomorphic-filter to be optimized with Numba
    :param image: uint8 ndarray to perform homomorphic filter on
    :param cutoff_freq: Cutoff frequency for Gaussian filter
    :param a, b: Floats to use on emphasis filter: H = a + b*H. Eg: a=0.5, b=1.5
    :return: Filtered image
    """

    # Replace values of 0 with the smallest >0 value, since log cannot be applied to 0.
    image.ravel()[image.ravel() == 0] = 1e-5
    # Take the image to log domain
    I_log = np.log1p(image)

    # Take image to frequency domain. Run in Object mode because numba does not support c-compiled np.fft functions.
    with nb.objmode(I_fft='complex128[:,:]'):
        I_fft = np.fft.fft2(I_log)

    # Apply Gaussian Mask
    P = I_fft.shape[0] / 2
    Q = I_fft.shape[1] / 2
    with nb.objmode(U='int32[:,:]', V='int32[:,:]'):
        U, V = np.meshgrid(range(I_fft.shape[0]),
                           range(I_fft.shape[1]),
                           sparse=False,
                           indexing='ij')
    Duv = (U - P)**2 + (V - Q)**2
    H = np.exp((-Duv / (2 * cutoff_freq**2)))

    # Obtain high-pass filter by taking 1 and subtracting the low pass filter.
    H = 1 - H

    # Apply filter on frequency domain then take the image back to spatial domain
    with nb.objmode(H='float64[:,:]'):
        H = np.fft.fftshift(H)
    I_fft_filt = (a + b * H) * I_fft
    with nb.objmode(I_filt='complex128[:,:]'):
        I_filt = np.fft.ifft2(I_fft_filt)
    I = np.exp(np.real(I_filt)) - 1
    return I
예제 #25
0
def generate_hash(tour: np.ndarray,
                  number=333667,
                  module=909090909090909091) -> int:
    """ Вычисления  хеша по туру
    tour: список вершин
    number: чьи степени будем искать
    module: по какому модулю
    return: хеш
    """
    with nb.objmode(h='int64'):
        h = generate_hash_from(rotate_zero(tour), number, module)
    return h
def _get_data(x, dt, a_s, s1, s2, r, normals, observations, true_states):
    for i, a in enumerate(a_s):
        with nb.objmode(x='float32[::1]'):
            F = np.array(
                [[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, a], [0, 0, -a, 0]],
                dtype=np.float32)
            x = linalg.expm(F * dt) @ x
        y1 = np.arctan2(x[1] - s1[1], x[0] - s1[0]) + r * normals[i, 0]
        y2 = np.arctan2(x[1] - s2[1], x[0] - s2[0]) + r * normals[i, 1]

        observations[i] = [y1, y2]
        observations[i] = [y1, y2]
        true_states[i] = np.concatenate((x, np.array([a])))
예제 #27
0
def _compute_bispectrum(k1bins, k2bins, kn, costheta, kcoords, nsamples,
                        sample_thresh, ndim, dim, shape, progress,
                        exclude, error, compute_point, *ffts):
    knyq = max(shape) // 2
    ntheta = costheta.size
    bispec = np.full((ntheta, dim, dim), np.nan+1.j*np.nan, dtype=np.complex128)
    binorm = np.full((ntheta, dim, dim), np.nan, dtype=np.float64)
    counts = np.full((ntheta, dim, dim), np.nan, dtype=np.float64)
    omega = np.zeros((dim, dim), dtype=np.int64)
    stderr = np.full((ntheta, dim, dim), np.nan, dtype=np.float64)
    for i in range(dim):
        k1 = kn[i]
        k1ind = k1bins[i]
        nk1 = k1ind.size
        for j in range(i+1):
            k2 = kn[j]
            if ntheta == 1 and (exclude and k1 + k2 > knyq):
                continue
            k2ind = k2bins[j]
            nk2 = k2ind.size
            nsamp = nsamples[i, j]
            nsamp = int(nsamp) if type(nsamp) is np.int64 \
                else max(int(nsamp*nk1*nk2), 1)
            if nsamp < nk1*nk2 or nsamp > sample_thresh:
                samp = np.random.randint(0, nk1*nk2, size=nsamp)
                count = nsamp
            else:
                samp = np.arange(nk1*nk2)
                count = nk1*nk2
            bispecbuf = np.zeros(count, dtype=np.complex128)
            binormbuf = np.zeros(count, dtype=np.float64)
            cthetabuf = np.zeros(count, dtype=np.float64) if ntheta > 1 \
                else np.array([0.], dtype=np.float64)
            countbuf = np.zeros(count, dtype=np.float64)
            compute_point(k1ind, k2ind, kcoords, ntheta,
                          nk1, nk2, shape, samp, count,
                          bispecbuf, binormbuf, cthetabuf, countbuf,
                          *ffts)
            if ntheta == 1:
                _fill_sum(i, j, bispec, binorm, counts, stderr,
                          bispecbuf, binormbuf, countbuf, error)
            else:
                binned = np.searchsorted(costheta, cthetabuf)
                _fill_binned_sum(i, j, ntheta, binned, bispec, binorm,
                                 counts, stderr, bispecbuf, binormbuf,
                                 countbuf, error)
            omega[i, j], omega[j, i] = nk1*nk2, nk1*nk2
        if progress:
            with nb.objmode():
                _printProgressBar(i, dim-1)
    return bispec, binorm, omega, counts, stderr
예제 #28
0
def numba_algorithm(m: np.ndarray, P: np.ndarray, Q: np.ndarray):

    # State dimensions
    n_time = m.shape[0]

    # Original State Shape
    gains_shape = m.shape[1:]

    # Smooth State Vectors
    ms = np.zeros_like(m)

    # Smooth Covariance matrices
    Ps = np.zeros_like(P)
    G_values = np.zeros_like(P)

    # Set Initial Smooth Values
    ms[-1] = m[-1]
    Ps[-1] = P[-1]

    # Run Extended Kalman Smoother with
    # Numpy matrices
    head = "==> Extended Kalman Smoother (NUMPY|JIT): "
    for k in range(-2, -(n_time + 1), -1):

        # Progress Bar in object-mode
        with objmode():
            progress_bar(head, n_time, -k - 1)

        # Predict Step
        mp = gains_vector(m[k])
        Pt = P[k].astype(np.complex128)
        Pp = Pt + Q

        # Smooth Step
        Pinv = np.diag(1.0 / np.diag(Pp))
        G = Pt @ Pinv

        # Record Posterior Smooth Values
        e = gains_vector(ms[k + 1]) - mp
        E = (Ps[k + 1] - Pp).astype(np.complex128)
        ms[k] = gains_reshape(mp + G @ e, gains_shape)
        Ps[k] = np.diag(np.diag(Pt + G @ E @ G.T).real)

        G_values[k] = G.real

    # Newline
    print()

    # Return Posterior smooth states and covariances
    return ms, Ps, G_values
예제 #29
0
    def get_normal_array(self, n):
        '''
            Get a normal distribuited 1D array with length 'n'
        '''

        x = self.get_array(n) * 2.0
        y = np.zeros_like(x)

        # The JIT has to be disabled because erfcinv is not recognized
        # by Numba
        with objmode(y='double[:]'):
            y = erfcinv(x)

        return y
예제 #30
0
def casa_fit(img_to_fit,npix_window,sampling,cutoff,delta):
    #ellipse_parms = np.zeros(img_to_fit.shape[2:5] + (3,))
    ellipse_parms = np.zeros(img_to_fit.shape[2:5] + (3,),dtype=numba.double)

    img_size = np.array(img_to_fit.shape[0:2])
    img_center = img_size//2
    start_window = img_center - npix_window//2
    end_window = img_center + npix_window//2 + 1
    img_to_fit = img_to_fit[start_window[0]:end_window[0],start_window[1]:end_window[1],:,:]

    d0 = np.arange(0, npix_window[0])*np.abs(delta[0])
    d1 = np.arange(0, npix_window[1])*np.abs(delta[1])
    interp_d0 = np.linspace(0, npix_window[0]-1, sampling[0])*np.abs(delta[0])
    interp_d1 = np.linspace(0, npix_window[1]-1, sampling[1])*np.abs(delta[1])
    #xp1, yp1 = np.meshgrid(interp_d0, interp_d1,indexing='ij')

    d0_shape = interp_d0.shape[0]
    d1_shape = interp_d1.shape[0]
    xp = np.repeat(interp_d0,d1_shape).reshape((d0_shape,d1_shape))
    yp = np.repeat(interp_d1,d0_shape).reshape((d1_shape,d0_shape)).T

    points = np.vstack((np.ravel(xp), np.ravel(yp))).T

    #img_to_fit = np.reshape(interpn((d0,d1),img_to_fit[:,:,0,0],points,method="splinef2d"),[sampling[1],sampling[0]]).T

    for time in range(img_to_fit.shape[2]):
        for chan in range(img_to_fit.shape[3]):
            for pol in range(img_to_fit.shape[4]):

                with objmode(res_x='f8[:]'):  # annotate return type
                    #if True:
                    # this region is executed by object-mode.
                    interp_img_to_fit = np.reshape(interpn((d0,d1),img_to_fit[:,:,time,chan,pol],points,method="splinef2d"),[sampling[1],sampling[0]]).T
                    interp_img_to_fit[interp_img_to_fit<cutoff] = np.nan
                    #print(interp_img_to_fit.shape)
                    # Fit a gaussian to the thresholded points
                    p0 = [2.5, 2.5, 0.]
                    res = optimize.minimize(beam_chi2, p0, args=(interp_img_to_fit, sampling//2))
                    res_x = res.x

                # convert to useful units
                phi = res_x[2] - 90.
                if phi < -90.:
                    phi += 180.

                ellipse_parms[time,chan,pol,0] = np.max(np.abs(res_x[0:2]))*np.abs(delta[0])*2.355/(sampling[0]/npix_window[0])
                ellipse_parms[time,chan,pol,1] = np.min(np.abs(res_x[0:2]))*np.abs(delta[1])*2.355/(sampling[1]/npix_window[1])
                ellipse_parms[time,chan,pol,2] = -phi

    return ellipse_parms
예제 #31
0
 def foo_nonglobal(x):
     with numba.objmode(y="float64"):
         y = inverse(x)
     return x, y
예제 #32
0
파일: test_pipeline.py 프로젝트: esc/numba
 def foo(x):
     with objmode(x="intp"):
         x += int(0x1)
     return x
예제 #33
0
 def foo():
     x = np.arange(5)
     with objmode(y='intp[:]'):  # annotate return type
         # this region is executed by object-mode.
         y = x + bar(x)
     return y