def test_deferred_type(self): node_type = deferred_type() spec = OrderedDict() spec['data'] = float32 spec['next'] = optional(node_type) @njit def get_data(node): return node.data @jitclass(spec) class LinkedNode(object): def __init__(self, data, next): self.data = data self.next = next def get_next_data(self): # use deferred type as argument return get_data(self.next) def append_to_tail(self, other): cur = self while cur.next is not None: cur = cur.next cur.next = other node_type.define(LinkedNode.class_type.instance_type) first = LinkedNode(123, None) self.assertEqual(first.data, 123) self.assertIsNone(first.next) second = LinkedNode(321, first) first_meminfo = _get_meminfo(first) second_meminfo = _get_meminfo(second) self.assertEqual(first_meminfo.refcount, 3) self.assertEqual(second.next.data, first.data) self.assertEqual(first_meminfo.refcount, 3) self.assertEqual(second_meminfo.refcount, 2) # Test using deferred type as argument first_val = second.get_next_data() self.assertEqual(first_val, first.data) # Check setattr (issue #2606) self.assertIsNone(first.next) second.append_to_tail(LinkedNode(567, None)) self.assertIsNotNone(first.next) self.assertEqual(first.next.data, 567) self.assertIsNone(first.next.next) second.append_to_tail(LinkedNode(678, None)) self.assertIsNotNone(first.next.next) self.assertEqual(first.next.next.data, 678) # Check ownership self.assertEqual(first_meminfo.refcount, 3) del second, second_meminfo self.assertEqual(first_meminfo.refcount, 2)
def test_deferred_type(self): node_type = deferred_type() spec = OrderedDict() spec['data'] = float32 spec['next'] = optional(node_type) @njit def get_data(node): return node.data @jitclass(spec) class LinkedNode(object): def __init__(self, data, next): self.data = data self.next = next def get_next_data(self): # use deferred type as argument return get_data(self.next) node_type.define(LinkedNode.class_type.instance_type) first = LinkedNode(123, None) self.assertEqual(first.data, 123) self.assertIsNone(first.next) second = LinkedNode(321, first) first_meminfo = _get_meminfo(first) second_meminfo = _get_meminfo(second) self.assertEqual(first_meminfo.refcount, 3) self.assertEqual(second.next.data, first.data) self.assertEqual(first_meminfo.refcount, 3) self.assertEqual(second_meminfo.refcount, 2) # Test using deferred type as argument first_val = second.get_next_data() self.assertEqual(first_val, first.data) # Check ownership self.assertEqual(first_meminfo.refcount, 3) del second, second_meminfo self.assertEqual(first_meminfo.refcount, 2)
for m in range(-L, L + 1): yield L, m else: for m in range(L + 1): if not m: yield L, m else: for i in (m, -m): yield L, i ##################### # Basis set classes # ##################### shell_type = deferred_type() @jitclass([('L', int64), ('nprim', int64), ('ncont', int64), ('spherical', boolean), ('gaussian', boolean), ('alphas', float64[:]), ('_coef', float64[:]), ('rs', optional(int64[:])), ('ns', optional(int64[:]))]) class Shell(object): """The primary object used for all things basis set related. Due to limitations in numba, contraction coefficients are stored as a 1D-array and reshaped when calling contract methods. Args: coef (np.ndarray): 1D-array of contraction coefficients alphas (np.ndarray): 1D-array of primitive exponents nprim (int): number of primitives in the shell
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a more complicated jitclasses example. Here, we implement a binarytree and iterative preorder and inorder traversal function using a handwritten stack. """ from __future__ import print_function, absolute_import import random from collections import OrderedDict from numba import njit from numba import jitclass from numba import int32, deferred_type, optional from numba.runtime import rtsys node_type = deferred_type() spec = OrderedDict() spec['data'] = int32 spec['left'] = optional(node_type) spec['right'] = optional(node_type) @jitclass(spec) class TreeNode(object): def __init__(self, data): self.data = data self.left = None self.right = None
@numba.njit(fastmath=True) def func(x): if x > lbs[0] and x < ubs[-1]: ind = _get_ind(x, ubs) a = lbs[ind] b = ubs[ind] _x = 2*(x-a)/(b-a) - 1.0 return _numba_chbevl(_x, cs[ind]) else: return np.nan return func ################################################################################ # This is slow for now :( leaf_type = numba.deferred_type() leaf_spec = OrderedDict() leaf_spec['a'] = numba.float64 leaf_spec['b'] = numba.float64 leaf_spec['ancestor'] = numba.optional(leaf_type) leaf_spec['m'] = numba.float64 leaf_spec['ind'] = numba.int64 leaf_spec['parent'] = numba.boolean leaf_spec['left'] = numba.optional(leaf_type) leaf_spec['right'] = numba.optional(leaf_type) @numba.jitclass(leaf_spec) class Leaf(object): def __init__(self, a, b, ancestor, ind): self.a = a self.b = b
return self.get_misfit_incompatible(rffactor) if self.to[i] >= 0: temp += ((self.rfo[i] - self.rfp[i])**2 / (self.stdrfo[i]**2)) k += 1 if self.to[i] > 10: break self.misfit = np.sqrt(temp / k) tS = temp / rffactor if tS > 50.: tS = np.sqrt(tS * 50.) self.L = np.exp(-0.5 * tS) return True # define type of disp object disp_type = numba.deferred_type() disp_type.define(disp.class_type.instance_type) # define type of rf object rf_type = numba.deferred_type() rf_type.define(rf.class_type.instance_type) #################################################### # Predefine the parameters for the data1d object #################################################### spec_data = [ # Rayleigh/Love dispersion data ('dispR', disp_type), ('dispL', disp_type), # radial/transverse receiver function data ('rfr', rf_type), ('rft', rf_type),
from scipy import interpolate from utils import * #c = 2.998e8 # m/s #c = 1.0 # m/s spec_Dipole = [ ('r', float64[:]), ('k', float64[:]), ('E0', float64), ('phase', float64), ('wavelength', float64), ] Dipole_type = deferred_type() @jitclass(spec_Dipole) class Dipole(object): def __init__(self, r, k, E0, phase, wavelength): self.r = r self.k = unit_vector(k) * 2 * np.pi / wavelength self.E0 = E0 self.phase = phase self.wavelength = wavelength Dipole_type.define(Dipole.class_type.instance_type) spec_DipoleSet = [
:Copyright: Author: Lili Feng Graduate Research Assistant CIEI, Department of Physics, University of Colorado Boulder email: [email protected] """ import fast_surf import numba import numpy as np import vmodel import copy # define type of vmodel.model1d model_type = numba.deferred_type() model_type.define(vmodel.model1d.class_type.instance_type) #-------------------------------------------------------------------------------------------------- #- fundamental array manipulations #-------------------------------------------------------------------------------------------------- @numba.jit(numba.float32[:](numba.float32, numba.float32, numba.float32)) def _get_array(xmin, xmax, dx): xlst = [] Nx = int((xmax - xmin) / dx + 1) for i in xrange(Nx): xlst.append(dx * i + xmin) return np.array(xlst, dtype=np.float32)
@property def nx(self): return self.__nx @property def nu(self): return self.__nu @property def ny(self): return self.__ny NB_TYPE_DYNAMIC = nb.deferred_type() NB_TYPE_DYNAMIC.define(Dynamic.class_type.instance_type) class Simulate: def __init__(self,steps,nx,u,y,nbases,L,R=0.1,PFweightNum=30): # self.__dynamic = dynamic self.__u = u self.__y = y self.__nu = self.__u.shape[0] self.__ny = self.__y.shape[0] self.__nx = nx self.__steps = steps self.__nbases = nbases #assumed to be equal to all x and u self.__A = np.zeros((self.__nx,self.nbases**(self.__nx+self.__nu)),dtype=np.float64,order='C')
yield L, m else: for m in range(L + 1): if not m: yield L, m else: for i in (m, -m): yield L, i ##################### # Basis set classes # ##################### shell_type = deferred_type() @jitclass([('L', int64), ('nprim', int64), ('ncont', int64), ('spherical', boolean), ('gaussian', boolean), ('alphas', float64[:]), ('_coef', float64[:]), ('rs', optional(int64[:])), ('ns', optional(int64[:]))]) class Shell(object): """The primary object used for all things basis set related. Due to limitations in numba, contraction coefficients are stored as a 1D-array and reshaped when calling contract methods. Args: coef (np.ndarray): 1D-array of contraction coefficients alphas (np.ndarray): 1D-array of primitive exponents nprim (int): number of primitives in the shell ncont (int): number of contracted functions in the shell
] @jitclass(matSpec) class Material: def __init__(self, refractive_index, albedo, color, spec): self.albedo = np.array(albedo) self.difuse_color = np.array(color) self.specular_exponent = float(spec) self.refractive_index = float(refractive_index) if os.environ.get('NUMBA_DISABLE_JIT') == '1': material_type = None else: material_type = deferred_type() material_type.define(Material.class_type.instance_type) sphereSpec = [ ('center', numba.float64[:]), ('radius', numba.float64), ('radius2', numba.float64), ('material', material_type), ] @jitclass(sphereSpec) class Sphere: def __init__(self, center, radius, material): self.center = np.array(center) self.radius = float(radius)
lst.push_front(3) lst.show()#321 @nb.jit def sum_list(lst): result=0 node=lst.head while node is not None: result+=node.value node=node.next return result lst1=LinkedList() [lst1.push_front(i) for i in range(1000)] # print(sum_list(lst1))#无法推断类型 #可使用装饰器nb.jitclass 来编译Node和LinkedList类,装饰器接受一个参数,其中包含被装饰类的属性的类型。 #首先必须先声明属性,在定义类,使用nb.deferred_type()函数,其次属性next可以使NOne,也可以是一个Node实例,这被称为可选类型,nb.optional node_type=nb.deferred_type() node_spec=[('next',nb.optional(node_type)),('value',nb.int64)] @nb.jitclass(node_spec) class Node1: def __init__(self,value): self.next=None self.value=value node_type.define(Node.class_type.instance_type) ll_spec=[('head',nb.optional(Node.class_type.instance_type))] @nb.jitclass(ll_spec) class LinkedList1:#实现链表 def __init__(self): self.head=None def push_front(self,value): if self.head==None: self.head=Node(value)
import numba from numba import jit from numba import int32, float32, boolean, float64 from numba import jitclass, deferred_type @jitclass([('p_pos', float64[:]), ('p_vel', float64[:])]) class EntityState_nb(object): def __init__(self): # physical position self.p_pos # physical velocity self.p_vel EntityState_type = deferred_type() EntityState_type.define(EntityState_nb.class_type.instance_type) @jitclass([('size', float32), ('movable', boolean), ('collide', boolean), ('state', EntityState_type)]) class Entity_nb(object): def __init__(self): # state self.state = EntityState_nb() # entity collides with others self.collide = True self.size = 0.050 self.movable = False
import numpy as np import numba as nb import mcmc.util as util import mcmc.fourier as fourier # import mcmc.layer as layer import mcmc.randomGenerator as randomGenerator import mcmc.measurement as meas Rand_gen_type = nb.deferred_type() Rand_gen_type.define(randomGenerator.RandomGenerator.class_type.instance_type) meas_type = nb.deferred_type() meas_type.define(meas.Measurement.class_type.instance_type) fourier_type = nb.deferred_type() fourier_type.define(fourier.FourierAnalysis.class_type.instance_type) spec = [ ('n_layers',nb.int64), ('record_skip',nb.int64), ('record_count',nb.int64), ('max_record_history',nb.int64), ('beta',nb.float64), ('betaZ',nb.float64), ('random_gen',Rand_gen_type), ('measurement',meas_type), ('fourier',fourier_type), ('H',nb.complex128[:,::1]), ('I',nb.float64[:,::1]), ('H_t_H',nb.float64[:,::1]), ('H_dagger',nb.complex128[:,::1]), ('yBar',nb.float64[::1]),
import numpy as np import numba as nb import mcmc.util as util import mcmc.fourier as fourier import mcmc.L as L import mcmc.randomGenerator as randomGenerator L_matrix_type = nb.deferred_type() Rand_gen_type = nb.deferred_type() L_matrix_type.define(L.Lmatrix.class_type.instance_type) Rand_gen_type.define(randomGenerator.RandomGenerator.class_type.instance_type) spec = [ ('LMat', L_matrix_type), ('rand_gen', Rand_gen_type), ('uStdev', nb.complex128[:]), ('beta', nb.float64), ('betaZ', nb.float64), ('current_sample', nb.complex128[:]), ('norm_current_sample', nb.float64), ('current_log_det_L', nb.float64), ] @nb.jitclass(spec) class pCN(): def __init__(self, LMat, rg, uStdev, init_sample, beta=1): self.LMat = LMat self.rand_gen = rg self.uStdev = uStdev self.beta = beta self.betaZ = 1 - np.sqrt(beta**2)
""" This example demonstrates jitclasses and deferred types for writing a singly-linked-list. """ from __future__ import print_function, absolute_import from collections import OrderedDict import numpy as np from numba import njit from numba import jitclass from numba import int32, deferred_type, optional from numba.runtime import rtsys node_type = deferred_type() spec = OrderedDict() spec['data'] = int32 spec['next'] = optional(node_type) @jitclass(spec) class LinkedNode(object): def __init__(self, data, next): self.data = data self.next = next def prepend(self, data): return LinkedNode(data, self) @njit def make_linked_node(data):
# -*- coding: utf-8 -*- """ This is a more complicated jitclasses example. Here, we implement a binarytree and iterative preorder and inorder traversal function using a handwritten stack. """ from __future__ import print_function, absolute_import import random from collections import OrderedDict from numba import njit from numba import jitclass from numba import int32, deferred_type, optional from numba.runtime import rtsys node_type = deferred_type() spec = OrderedDict() spec['data'] = int32 spec['left'] = optional(node_type) spec['right'] = optional(node_type) @jitclass(spec) class TreeNode(object): def __init__(self, data): self.data = data self.left = None self.right = None
Class for tracking the result of selection to allow for chaining. """ import numba import numpy as np from .flags import * from .indexset import IndexSet from .sel import _sel from .omit import _omit from collections import OrderedDict sel_result_spec = OrderedDict() indexset_type = numba.deferred_type() sel_result_spec['start'] = numba.int64 sel_result_spec['stop'] = numba.int64 sel_result_spec['indexset'] = indexset_type sel_result_spec['flags'] = numba.boolean[:] sel_result_spec['_num_flags'] = numba.int64 sel_result_spec['has_flags'] = numba.bool_ @numba.jitclass(sel_result_spec) class SelResult_: def __init__(self, indexset): self.indexset = indexset self.start = 0 self.stop = indexset.n
class OrientationSpaceExplorer(object): def __init__( self, minimum_radius=0.2, maximum_radius=2.96, # 2.5 minimum_clearance=1.02, neighbors=32, maximum_curvature=0.2, timeout=1.0, overlap_rate=0.5): self.minimum_radius = minimum_radius self.maximum_radius = maximum_radius self.minimum_clearance = minimum_clearance self.neighbors = neighbors self.maximum_curvature = maximum_curvature self.timeout = timeout self.overlap_rate = overlap_rate # planning related self.start = None self.goal = None self.grid_ori = None self.grid_map = None self.grid_res = None self.grid_pad = None self.obstacle = 255 def exploring(self, plotter=None): close_set, open_set = numba.typed.List(), [(self.start.f, self.start)] close_set.append((0., 0., 0., 0.)), close_set.pop() while open_set: circle = self.pop_top(open_set) if self.goal.f < circle.f: return True if not self.exist(circle, close_set): expansion = self.expand(circle) self.merge(expansion, open_set) if self.overlap(circle, self.goal) and circle.f < self.goal.g: self.goal.g = circle.f self.goal.f = self.goal.g + self.goal.h self.goal.set_parent(circle) close_set.append((circle.x, circle.y, circle.a, circle.r)) if plotter: plotter([circle]) return False @property def circle_path(self): if self.goal: path, parent = [self.goal], self.goal.parent while parent: path.append(parent) parent = parent.parent path.reverse() return path return [] def path(self): circles = self.circle_path if circles: return [(p.x, p.y, p.a, p.r) for p in circles] return [] def initialize(self, start, goal, grid_map, grid_res, grid_ori, obstacle=255): # type: (CircleNode, CircleNode, np.ndarray, float, CircleNode, int) -> OrientationSpaceExplorer """ :param start: start circle-node :param goal: goal circle-node :param grid_map: occupancy map(0-1), 2d-square, with a certain resolution: gird_res :param grid_res: resolution of occupancy may (m/pixel) :param grid_ori: :param obstacle: value of the pixels of obstacles region on occupancy map. """ self.start, self.goal = start, goal self.grid_map, self.grid_res, self.grid_ori, self.obstacle = grid_map, grid_res, grid_ori, obstacle # padding grid map for clearance calculation s = int( np.ceil((self.maximum_radius + self.minimum_clearance) / self.grid_res)) self.grid_pad = np.pad(self.grid_map, ((s, s), (s, s)), 'constant', constant_values=((self.obstacle, self.obstacle), (self.obstacle, self.obstacle))) # complete the start and goal self.start.r, self.start.g = self.clearance( self.start) - self.minimum_clearance, 0 self.start.h = reeds_shepp.path_length( (start.x, start.y, start.a), (self.goal.x, self.goal.y, self.goal.a), 1. / self.maximum_curvature) self.goal.r, self.goal.h, self.goal.g = self.clearance( self.goal) - self.minimum_clearance, 0, np.inf self.start.f, self.goal.f = self.start.g + self.start.h, self.goal.g + self.goal.h return self @staticmethod def merge(expansion, open_set): """ :param expansion: expansion is a set in which items are unordered. :param open_set: we define the open set as a set in which items are sorted from Large to Small by cost. """ open_set.extend(zip(map(lambda x: x.f, expansion), expansion)) open_set.sort(reverse=True) @staticmethod def pop_top(open_set): """ :param open_set: we define the open set as a set in which items are sorted from Large to Small by cost. """ return open_set.pop()[-1] def exist(self, circle, close_set): state = (circle.x, circle.y, circle.a) return self.jit_exist(state, close_set, self.maximum_curvature) @staticmethod @njit def jit_exist(state, close_set, maximum_curvature): def distance(one, another, curvature): euler = np.sqrt((one[0] - another[0])**2 + (one[1] - another[1])**2) angle = np.abs(one[2] - another[2]) angle = (angle + np.pi) % (2 * np.pi) - np.pi # angle = np.pi - angle if angle > np.pi / 2 else angle heuristic = angle / curvature return euler if euler > heuristic else heuristic for item in close_set: if distance(state, item, maximum_curvature) < item[-1] - 0.1: return True return False def overlap(self, circle, goal): """ check if two circles overlap with each other in a certain margin (overlap_rate[e.g., 50%] of the radius of the smaller circle), which guarantees enough space for a transition motion. """ return self.jit_overlap((circle.x, circle.y, circle.r), (goal.x, goal.y, goal.r), self.overlap_rate) @staticmethod @njit def jit_overlap(circle, goal, rate): euler = np.sqrt((circle[0] - goal[0])**2 + (circle[1] - goal[1])**2) r1, r2 = min([circle[2], goal[2]]), max([circle[2], goal[2]]) return euler < r1 * rate + r2 def expand(self, circle): def buildup(state): child = self.CircleNode(state[0], state[1], state[2], state[3]) # build the child child.set_parent(circle) # child.h = self.distance(child, self.goal) child.h = reeds_shepp.path_length( (child.x, child.y, child.a), (self.goal.x, self.goal.y, self.goal.a), 1. / self.maximum_curvature) child.g = circle.g + reeds_shepp.path_length( (circle.x, circle.y, circle.a), (child.x, child.y, child.a), 1. / self.maximum_curvature) child.f = child.g + child.h # add the child to expansion set return child neighbors = self.jit_neighbors((circle.x, circle.y, circle.a), circle.r, self.neighbors) children = self.jit_children( neighbors, (self.grid_ori.x, self.grid_ori.y, self.grid_ori.a), self.grid_pad, self.grid_map, self.grid_res, self.maximum_radius, self.minimum_radius, self.minimum_clearance, self.obstacle) return map(buildup, children) @staticmethod @njit def jit_children(neighbors, origin, grid_pad, grid_map, grid_res, maximum_radius, minimum_radius, minimum_clearance, obstacle): def clearance(state): s_x, s_y, s_a = origin[0], origin[1], origin[2] c_x, c_y, c_a = state[0], state[1], state[2] x = (c_x - s_x) * np.cos(s_a) + (c_y - s_y) * np.sin(s_a) y = -(c_x - s_x) * np.sin(s_a) + (c_y - s_y) * np.cos(s_a) u = int(np.floor(y / grid_res + grid_map.shape[0] / 2)) v = int(np.floor(x / grid_res + grid_map.shape[0] / 2)) size = int(np.ceil( (maximum_radius + minimum_clearance) / grid_res)) subspace = grid_pad[u:u + 2 * size + 1, v:v + 2 * size + 1] rows, cols = np.where(subspace >= obstacle) if len(rows): row, col = np.fabs(rows - size) - 1, np.fabs(cols - size) - 1 rs = np.sqrt(row**2 + col**2) * grid_res return rs.min() else: return size * grid_res children = numba.typed.List() children.append((0., 0., 0., 0.)), children.pop() for neighbor in neighbors: r = min([clearance(neighbor) - minimum_clearance, maximum_radius]) if r > minimum_radius: children.append((neighbor[0], neighbor[1], neighbor[2], r)) return children @staticmethod @njit def jit_neighbors(state, radius, number): def lcs2gcs(point): x, y, a = point xo, yo, ao = state x1 = x * np.cos(ao) - y * np.sin(ao) + xo y1 = x * np.sin(ao) + y * np.cos(ao) + yo a1 = a + ao return x1, y1, a1 neighbors = numba.typed.List() neighbors.append((0., 0., 0.)), neighbors.pop() for n in np.radians(np.linspace(-90, 90, number / 2)): neighbor = (radius * np.cos(n), radius * np.sin(n), n) opposite = (radius * np.cos(n + np.pi), radius * np.sin(n + np.pi), n) neighbor = lcs2gcs(neighbor) opposite = lcs2gcs(opposite) neighbors.extend([neighbor, opposite]) return neighbors def clearance(self, circle): origin, coord = (self.grid_ori.x, self.grid_ori.y, self.grid_ori.a), (circle.x, circle.y, circle.a) return self.jit_clearance(coord, origin, self.grid_pad, self.grid_map, self.grid_res, self.maximum_radius, self.minimum_clearance, self.obstacle) @staticmethod @njit def jit_clearance(coord, origin, grid_pad, grid_map, grid_res, maximum_radius, minimum_clearance, obstacle): s_x, s_y, s_a = origin[0], origin[1], origin[2] c_x, c_y, c_a = coord[0], coord[1], coord[2] x = (c_x - s_x) * np.cos(s_a) + (c_y - s_y) * np.sin(s_a) y = -(c_x - s_x) * np.sin(s_a) + (c_y - s_y) * np.cos(s_a) u = int(np.floor(y / grid_res + grid_map.shape[0] / 2)) v = int(np.floor(x / grid_res + grid_map.shape[0] / 2)) size = int(np.ceil((maximum_radius + minimum_clearance) / grid_res)) subspace = grid_pad[u:u + 2 * size + 1, v:v + 2 * size + 1] rows, cols = np.where(subspace >= obstacle) if len(rows): row, col = np.fabs(rows - size) - 1, np.fabs(cols - size) - 1 rs = np.sqrt(row**2 + col**2) * grid_res return rs.min() else: return size * grid_res circle_node = numba.deferred_type() spec = [('x', numba.float64), ('y', numba.float64), ('a', numba.float64), ('r', numba.optional(numba.float64)), ('h', numba.float64), ('g', numba.float64), ('f', numba.float64), ("parent", numba.optional(circle_node)), ('children', numba.optional(numba.types.List(circle_node)))] # @numba.jitclass(spec) class CircleNode(object): def __init__(self, x=None, y=None, a=None, r=None): self.x = x self.y = y self.a = a self.r = r self.h = np.inf # cost from here to goal, heuristic distance or actual one self.g = np.inf # cost from start to here, actual distance self.f = self.h + self.g self.parent = None self.children = None def set_parent(self, circle): self.parent = circle def lcs2gcs(self, circle): # type: (OrientationSpaceExplorer.CircleNode) -> OrientationSpaceExplorer.CircleNode """ transform self's coordinate from local coordinate system (LCS) to global coordinate system (GCS) :param circle: the circle-node contains the coordinate (in GCS) of the origin of LCS. """ xo, yo, ao = circle.x, circle.y, circle.a x = self.x * np.cos(ao) - self.y * np.sin(ao) + xo y = self.x * np.sin(ao) + self.y * np.cos(ao) + yo a = self.a + ao self.x, self.y, self.a = x, y, a return self def gcs2lcs(self, circle): # type: (OrientationSpaceExplorer.CircleNode) -> OrientationSpaceExplorer.CircleNode """ transform self's coordinate from global coordinate system (LCS) to local coordinate system (GCS) :param circle: the circle-node contains the coordinate (in GCS) of the origin of LCS. """ xo, yo, ao = circle.x, circle.y, circle.a x = (self.x - xo) * np.cos(ao) + (self.y - yo) * np.sin(ao) y = -(self.x - xo) * np.sin(ao) + (self.y - yo) * np.cos(ao) a = self.a - ao self.x, self.y, self.a = x, y, a return self
import numba from collections import OrderedDict linked_node_spec = OrderedDict() node_type = numba.deferred_type() linked_node_spec["parent"] = node_type linked_node_spec["child"] = node_type linked_node_spec["depth"] = numba.int32 linked_node_spec["start"] = numba.int32 linked_node_spec["end"] = numba.int32 linked_node_spec["index"] = numba.int32 linked_node_spec["node_mean"] = numba.float32 linked_node_spec["node_impurity"] = numba.float32 linked_node_spec["right_child_mean"] = numba.float32 linked_node_spec["right_child_impurity"] = numba.float32 linked_node_spec["sorted_dim"] = numba.int32 @numba.jitclass(linked_node_spec) class LinkedNode: def __init__(self, depth): self.parent = self self.child = self self.depth = depth
return np.array([x, y, z], dtype=np.float64) @numba.njit def vec(x, y, z): return np.array([x, y, z], dtype=np.float64) @numba.njit def unit(v): return v / np.linalg.norm(v) # fast primitives ray_type = numba.deferred_type() tree_box_type = numba.deferred_type() @numba.experimental.jitclass([ ('origin', numba.types.Array(numba.float64, 1, layout='C')), ('direction', numba.types.Array(numba.float64, 1, layout='C')), ('inv_direction', numba.types.Array(numba.float64, 1, layout='C')), ('sign', numba.uint8[:]), ('color', numba.types.Array(numba.float64, 1, layout='C')), ('local_color', numba.types.Array(numba.float64, 1, layout='C')), ('i', numba.int32), ('j', numba.int32), ('bounces', numba.int32), ('p', numba.float64), ('local_p', numba.float64),
Numba is used for speeding up of the code. :Copyright: Author: Lili Feng Graduate Research Assistant CIEI, Department of Physics, University of Colorado Boulder email: [email protected] """ import numpy as np import math import numba import random import vmodel, modparam, data, eigenkernel model1d_type = numba.deferred_type() model1d_type.define(vmodel.model1d.class_type.instance_type) data_type = numba.deferred_type() data_type.define(data.data1d.class_type.instance_type) eigk_type = numba.deferred_type() eigk_type.define(eigenkernel.eigkernel.class_type.instance_type) #################################################### # Predefine the parameters for the ttisolver object #################################################### spec_ttisolver = [('model', model1d_type), ('indata', data_type), ('eigkR', eigk_type), ('eigkL', eigk_type), ('hArr', numba.float32[:])]
import numpy as np import numba as nb import mcmc.util as util import mcmc.fourier as fourier import mcmc.L as L import mcmc.pCN as pCN L_matrix_type = nb.deferred_type() L_matrix_type.define(L.Lmatrix.class_type.instance_type) pCN_type = nb.deferred_type() pCN_type.define(pCN.pCN.class_type.instance_type) fourier_type = nb.deferred_type() fourier_type.define(fourier.FourierAnalysis.class_type.instance_type) spec = [ ('is_stationary', nb.boolean), ('sqrt_beta', nb.float64), ('order_number', nb.int64), ('n_samples', nb.int64), ('pcn', pCN_type), ('i_record', nb.int64), ('stdev', nb.complex128[::1]), ('stdev_sym', nb.complex128[::1]), ('samples_history', nb.complex128[:, ::1]), ('current_sample', nb.complex128[::1]), ('current_sample_sym', nb.complex128[::1]), ('current_sample_scaled_norm', nb.float64), ('current_log_L_det', nb.float64), ('new_sample', nb.complex128[::1]), ('new_sample_sym', nb.complex128[::1]), ('new_sample_scaled_norm', nb.float64), ('new_log_L_det', nb.float64),
import numpy as np from numba import intc, float64, deferred_type from numba import types from numba.experimental import jitclass from numba.extending import register_jitable from numba.core.errors import TypingError from numba import types, typeof from kalmantv.numba.kalmantv import KalmanTV, _mvn_sim, _quad_form from rodeo.utils import rand_mat kalman_type = deferred_type() kalman_type.define(KalmanTV.class_type.instance_type) @register_jitable def _fempty(shape): """ Create an empty ndarray with the given shape in fortran order. Numba cannot create fortran arrays directly, so this is done by transposing a C order array, as explained [here](https://numba.pydata.org/numba-doc/dev/user/faq.html#how-can-i-create-a-fortran-ordered-array). """ return np.empty(shape[::-1]).T @register_jitable def _interrogate_chkrebtii(x_meas, var_meas, fun, t, theta, wgt_meas, mu_state_pred, var_state_pred, z_state, tx_state, twgt_meas, tchol_state): """ Interrogate method of Chkrebtii et al (2016).
import numpy as np from . import BiQuad import numba from tqdm import tqdm BiQuad_type = numba.deferred_type() BiQuad_type.define(BiQuad.BiQuad.class_type.instance_type) spec = [ ('filters', BiQuad_type[:]), ] # simple LF-Rd wavetable oscillator based on Fant 1985, Fant 1995 class SerialFilterBank: def tick(self, x, verbose=False): if np.isscalar(x): y = x for filter in self.filters: y = filter.tick(y) return y else: y = x for i in tqdm(range(len(y)), disable=(not verbose)): for filter in self.filters: y[i] = filter.tick(y[i]) return y
import numpy as np from Weno import Weno from numba import jitclass from numba import int32, float64, deferred_type #------------------------------------------------------ Weno_type = deferred_type() Weno_type.define(Weno.class_type.instance_type) spec = [('c21', float64), ('c22', float64), ('c31', float64), ('c32', float64), ('size', int32), ('u1', float64[:]), ('u2', float64[:]), ("W", Weno_type)] #------------------------------------------------------- @jitclass(spec) class RK3TVD: def __init__(self, size, L): self.c21 = 3. / 4. self.c22 = 1. / 4. self.c31 = 1. / 3. self.c32 = 2. / 3. self.size = size self.u1 = np.empty(self.size) self.u2 = np.empty(self.size) self.W = Weno(size, L) def op(self, Meth, InOut, dt): self.W.weno(Meth, InOut, self.u1) self.u1 = InOut + dt * self.u1
This is an extension to the simpler singly-linked-list example in ``linkedlist.py``. Here, we make a better interface in the Stack class that encapsuate the underlying linked-list. """ from __future__ import print_function, absolute_import from numba.utils import OrderedDict from numba import njit from numba import jitclass from numba import deferred_type, intp, optional from numba.runtime import rtsys linkednode_spec = OrderedDict() linkednode_type = deferred_type() linkednode_spec['data'] = data_type = deferred_type() linkednode_spec['next'] = optional(linkednode_type) @jitclass(linkednode_spec) class LinkedNode(object): def __init__(self, data): self.data = data self.next = None linkednode_type.define(LinkedNode.class_type.instance_type) stack_spec = OrderedDict() stack_spec['head'] = optional(linkednode_type)
def fourierTransformHalf(self, z): return u2.rfft2(z, self.basis_number) def constructU(self, uHalf2D): """ Construct Toeplitz Matrix """ return u2.constructU(uHalf2D, self.Index) def constructMatexplicit(self, uHalf2D, fun): temp = fun(self.inverseFourierLimited(uHalf2D).T) temp2 = self.fourierTransformHalf(temp) return self.constructU(temp2) fourier_type = nb.deferred_type() fourier_type.define(FourierAnalysis_2D.class_type.instance_type) specL = [ ('fourier', fourier_type), ('sqrt_beta', nb.float64), ('current_L', nb.complex128[:, ::1]), ('latest_computed_L', nb.complex128[:, ::1]), ] @nb.jitclass(specL) class Lmatrix_2D: def __init__(self, f, sqrt_beta): self.fourier = f self.sqrt_beta = sqrt_beta
import numpy as np import numba as nb import mcmc.util as util import mcmc.fourier as fourier import mcmc.L as L import mcmc.randomGenerator as randomGenerator import mcmc.pCN as pCN import mcmc.measurement as meas import mcmc.simulationResults as simRes # import scipy as scp import time fourier_type = nb.deferred_type() fourier_type.define(fourier.FourierAnalysis.class_type.instance_type) L_matrix_type = nb.deferred_type() L_matrix_type.define(L.Lmatrix.class_type.instance_type) Rand_gen_type = nb.deferred_type() Rand_gen_type.define(randomGenerator.RandomGenerator.class_type.instance_type) pCN_type = nb.deferred_type() pCN_type.define(pCN.pCN.class_type.instance_type) meas_type = nb.deferred_type() meas_type.define(meas.Measurement.class_type.instance_type) sim_result_type = nb.deferred_type() sim_result_type.define(simRes.SimulationResult.class_type.instance_type) spec = [ ('fourier', fourier_type), ('random_gen', Rand_gen_type), ('pcn', pCN_type), ('sim_result', sim_result_type), # ('LMat',L_matrix_type), ('measurement', meas_type),
return np.array([x, y, z], dtype=np.float64) @numba.njit def vec(x, y, z): return np.array([x, y, z], dtype=np.float64) @numba.njit def unit(v): return v / np.linalg.norm(v) # fast primitives ray_type = numba.deferred_type() node_type = numba.deferred_type() box_type = numba.deferred_type() @numba.experimental.jitclass([ ('origin', numba.float64[3::1]), ('direction', numba.float64[3::1]), ('inv_direction', numba.float64[3::1]), ('sign', numba.uint8[3::1]), ('color', numba.float64[3::1]), ('local_color', numba.float64[3::1]), ('i', numba.int32), ('j', numba.int32), ('bounces', numba.int32), ('p', numba.float64),
This example demonstrates jitclasses and deferred type. This is an extension to the simpler singly-linked-list example in ``linkedlist.py``. Here, we make a better interface in the Stack class that encapsuate the underlying linked-list. """ from __future__ import print_function, absolute_import from collections import OrderedDict from numba import njit from numba import deferred_type, intp, optional from numba.core.runtime import rtsys from numba.experimental import jitclass linkednode_spec = OrderedDict() linkednode_type = deferred_type() linkednode_spec['data'] = data_type = deferred_type() linkednode_spec['next'] = optional(linkednode_type) @jitclass(linkednode_spec) class LinkedNode(object): def __init__(self, data): self.data = data self.next = None linkednode_type.define(LinkedNode.class_type.instance_type) stack_spec = OrderedDict() stack_spec['head'] = optional(linkednode_type)
point_spec = [('x', nb.float32), ('y', nb.float32)] @nb.jitclass(point_spec) class Point(object): def __init__(self, x, y): self.x = x self.y = y # def __str__(self): # return "(%s, %s)" % (self.x, self.y) point_type = nb.deferred_type() point_type.define(Point.class_type.instance_type) ################ Just for tests ###################### @nb.njit(nb.float32(nb.float32[2], nb.float32[2])) def get_distance_to_4(p1, p2): dx = p1[0] - p2[0] dy = p1[1] - p2[1] return m.hypot(dx, dy) @nb.njit def get_distance_to(from_object, to_object): dx = to_object.x - from_object.x
class MoveType(IntEnum): Standard, Double, Prime = range(3) class Pieces(IntEnum): UR, UF, UL, UB, DF, DB = range(6) def convert_move_to_string(move, move_type): return ("U" if move == MoveSet.U else "M") + ("" if move_type == MoveType.Standard else "2" if move_type == MoveType.Double else "'") lse_type = deferred_type() '''@jitclass([ # Constructor variables ('lse_state', lse_type),#LSE_State.class_type.instance_type) ('edge_orientation_state', typeof([True])), ('edge_permutation_state', typeof(numpy.zeros(1, dtype = int))), ('center_AUF_state', typeof(numpy.zeros(1, dtype = int))), ('misoriented_centers_orientation_state', typeof([True])), ('edge_orientation_state_replacement', typeof([True])), ('edge_permutation_state_in_place', typeof(numpy.zeros(1, dtype = int))), # toString variables ('data', typeof("")), # Equality variables ('other', lse_type), # swap_pieces_permutation method ('piece1', typeof(Pieces.UR)),
import numpy as np from Weno import Weno from numba import jitclass from numba import int32, float64,deferred_type #------------------------------------------------------ Weno_type = deferred_type() Weno_type.define(Weno.class_type.instance_type) spec = [ ('c21', float64), ('c22', float64), ('c31', float64), ('c32', float64), ('size',int32), ('u1', float64[:]), ('u2', float64[:]), ("W", Weno_type) ] #------------------------------------------------------- @jitclass(spec) class RK3TVD: def __init__(self,size,L): self.c21=3./4. self.c22=1./4. self.c31=1./3. self.c32=2./3. self.size=size self.u1=np.empty(self.size) self.u2=np.empty(self.size) self.W=Weno(size,L) def op(self,Meth,InOut,dt):