def setup_stage(): """docstring for setup_stage """ import ctypes e7xx = ctypes.windll.LoadLibrary('E7XX_GCS_DLL.dll') try: print "Connecting to stage" id = e7xx.E7XX_ConnectRS232(1, 57600) print "Initializing axes" e7xx.E7XX_INI(id, '134') print "initializing servos" err = e7xx.E7XX_SVO(id, '134', ctl.as_ctypes(ones(4, dtype=int32))) if err: print "Servos initialized OK" else: import sys sys.exit(e7xx.E7XX_GetError(id)) svo = ctl.as_ctypes(ones(4, dtype=int32)) err = e7xx.E7XX_qSVO(id, '134', svo) if err: print "Read servos OK" else: print e7xx.E7XX_GetError(id) time.sleep(5) while not(all(ctl.as_array(svo))): e7xx.E7XX_qSVO(id, '134', svo) print "Servo status: ", ctl.as_array(svo), ctl.as_array(svo).all() time.sleep(1) finally: return e7xx, id
def formal_integral_model(request, model): r = request.param['r'] model.no_of_shells_i = r.shape[0] - 1 model.inverse_time_explosion = c.c.cgs.value model.r_outer_i.contents = as_ctypes(r[1:]) model.r_inner_i.contents = as_ctypes(r[:-1]) return model
def dispose_gl(self): glDeleteTextures(self.texture_id) glDeleteRenderbuffers(1, as_ctypes(self.depth_buffer)) glDeleteFramebuffers(1, as_ctypes(self.fb)) self.fb = 0 if self.multisample > 0: glDeleteTextures(self.resolve_texture_id) glDeleteFramebuffers(1, as_ctypes(self.resolve_fb))
def do_some_task(): SIZE = 1e8 input_array = 1 * np.random.random(SIZE).astype(np.float32) output_array = np.empty_like(input_array) lib.do_some_omp_task(as_ctypes(input_array), as_ctypes(output_array), ct.c_size_t(input_array.size)) return output_array
def LUSolve(LU, b): """ Resolve LU = b. """ n = LU.shape[0] x = b.copy() lib.LUSolve(n, byref(ctypeslib.as_ctypes(LU)), byref(ctypeslib.as_ctypes(x)), byref(ctypeslib.as_ctypes(b))) return x
def LUCroutDecompose(A): """ Implementação do método de Crout para decomposição LU. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." L = zeros(A.shape) n = A.shape[0] U = L.copy() lib.LUDec(n, byref(ctypeslib.as_ctypes(A)), byref(ctypeslib.as_ctypes(L)), byref(ctypeslib.as_ctypes(U))) return L, U
def move_and_image(mmc, e7xx, id, coords, exptime, image_queue, **kwargs): """ move_and_image moves the stage to the given coordinates, takes an exposure for exptime seconds, then adds it to image_queue. """ DEBUG = False for key in kwargs: if key == "DEBUG": DEBUG = True else: raise TypeError, 'Unknown argument "%s"' % key if DEBUG: print "Moving to ", coords err = e7xx.E7XX_MOV(id, "14", ctl.as_ctypes(array(coords, dtype=float))) if err: print "Moved OK" else: err = e7xx.E7XX_GetError(id) print err time.sleep(0.03) if DEBUG: res = ctl.as_ctypes(empty(4, dtype=float)) e7xx.E7XX_qMOV(id, "14", res) print "Moved to ", ctl.as_array(res) noImage = True while noImage: try: if image_queue.qsize() < 1000: if DEBUG: print "Snapping Image" mmc.snapImage() im1 = mmc.getImage() if DEBUG: print "Got image" image_queue.put(im1) if DEBUG: print "Queueing image" noImage = False if DEBUG: print "Leaving Loop" except MemoryError: if DEBUG: print "Memory Error. Going to sleep" time.sleep(1) if DEBUG: print "Done"
def GaussSeidel(A, b, ks=50): """ Resolve Ax = b através do método iterativo de Jacobi. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." assert b.shape[0] == A.shape[0], "'b' deve ser compatível com A." n = A.shape[0] x = zeros(n) try: lib.SolveGaussSeidel(n, ks, byref(ctypeslib.as_ctypes(A)), byref(ctypeslib.as_ctypes(x)), byref(ctypeslib.as_ctypes(b))) except: raise return x
def GaussJordan(A, b): """ Resolve Ax = b através do método de eliminação de Gauss-Jordan com pivotação. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." assert b.shape[0] == A.shape[0], "'b' deve ser compatível com A." n = A.shape[0] x = zeros(n) try: lib.SolveGJ(n, byref(ctypeslib.as_ctypes(A)), byref(ctypeslib.as_ctypes(x)), byref(ctypeslib.as_ctypes(b))) except: raise return x
def allocate_memory(self) -> Contacts: """Allocate data according to the parameters with the "num_" prefix. The pointers are then set to the freshly allocated memory. The memory is owned by the Contacts instance which is returned by this method. Returns: Contacts: The object owning the allocated memory. """ mesh1d_indices = np.empty(self.num_contacts, dtype=np.int32) mesh2d_indices = np.empty(self.num_contacts, dtype=np.int32) self.mesh1d_indices = as_ctypes(mesh1d_indices) self.mesh2d_indices = as_ctypes(mesh2d_indices) return Contacts(mesh1d_indices, mesh2d_indices)
def getScreenRGB(self, screen_data=None): if screen_data is None: width = rle_lib.getScreenWidth(self.obj) height = rle_lib.getScreenHeight(self.obj) screen_data = np.empty((height, width, 4), dtype=np.uint8) rle_lib.getScreenRGB(self.obj, as_ctypes(screen_data[:])) return screen_data
def save_str(self): ''' Saves the game to a string. .. deprecated:: 2.3 Use :meth:`jericho.FrotzEnv.get_state` instead. :returns: String containing saved game. :raises RuntimeError: if unable to save. :Example: >>> from jericho import * >>> env = FrotzEnv(rom_path) >>> try: >>> save = env.save_str() >>> except RuntimeError: >>> print('Skipping Save') ''' warnings.warn('save_str is deprecated; use get_state instead.', DeprecationWarning) buff = np.zeros(8192, dtype=np.uint8) success = self.frotz_lib.save_str(as_ctypes(buff)) if success <= 0: raise RuntimeError('Unable to save.') return buff
def get_field_params(self) -> Dict[str, float]: ''' Returns the field parameters from the given field type. Parameters ---------- None Returns ------- dict length, width, penalty_length, penalty_width, goal_width, goal_depth, ball_radius, rbt_distance_center_kicker, rbt_kicker_thickness, rbt_kicker_width, rbt_wheel0_angle, rbt_wheel1_angle, rbt_wheel2_angle, rbt_wheel3_angle, rbt_radius, rbt_wheel_radius, rbt_motor_max_rpm ''' params = np.zeros(17, dtype=np.float64) keys = [ 'length', 'width', 'penalty_length', 'penalty_width', 'goal_width', 'goal_depth', 'ball_radius', 'rbt_distance_center_kicker', 'rbt_kicker_thickness', 'rbt_kicker_width', 'rbt_wheel0_angle', 'rbt_wheel1_angle', 'rbt_wheel2_angle', 'rbt_wheel3_angle', 'rbt_radius', 'rbt_wheel_radius', 'rbt_motor_max_rpm' ] robosim_lib.getFieldParams(self.world, as_ctypes(params)) return {key: param for key, param in zip(keys, params)}
def step(self, action: np.ndarray) -> None: ''' Steps the simulator given an action. Parameters ---------- action: np.ndarray Action of shape (n_robots, 7), [0] wheel_speeds if wheel_speeds: [1->4] v_wheel[0->3] else: [1] v_x [2] v_y [3] v_theta [4] unused [5] kick_v_x [6] kick_v_z [7] dribbler Returns ------- None ''' action = np.array(action, dtype=np.float64) action = action.flatten() robosim_lib.step(self.world, as_ctypes(action))
def do_some_task(): SIZE = 1000 np.random.seed(0) input_array = 100 * np.random.random(SIZE) input_array = np.round(input_array).astype(np.int64) output_array = np.empty_like(input_array) print("Starting openmp part...") start = timer() lib.do_some_omp_task(as_ctypes(input_array), as_ctypes(output_array), ct.c_size_t(input_array.size)) end = timer() print("End... Elapsed time: {:0>8}".format(datetime.timedelta(seconds=(end - start)))) return output_array
def get_state(self) -> np.ndarray: ''' Returns the state array. State: - Ball: x, y, z, v_x, v_y - Robots_blue: x, y, theta, v_x, v_y, v_theta, ir, v_wheel[0->3] - Robots_yellow: x, y, theta, v_x, v_y, v_theta, ir, v_wheel[0->3] Units: x, y, z -> meters theta -> degrees (0, 360) v_x, v_y -> meters/seconds v_theta -> degrees/seconds ir -> bool v_wheel -> rad/s State size: 5 + 11*n_robots_blue + 11*n_robots_yellow Parameters ---------- None Returns ------- np.ndarray State ''' state = np.zeros(self.state_size, dtype=np.float64) robosim_lib.getState(self.world, as_ctypes(state)) return state
def alterEmulatorRAM(self, ram): """This function changes the atari RAM in the emulator level. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size, dtype=uint8) """ assert (ram.size == ale_lib.getRAMSize(self.obj)) ale_lib.alterEmulatorRAM(self.obj, as_ctypes(ram))
def load_str(self, buff): ''' Loads the game from a string buffer given by save_str() .. deprecated:: 2.3 Use :meth:`jericho.FrotzEnv.set_state` instead. :param buff: Buffer to load the game from. :type buff: string :raises RuntimeError: if unable to load. >>> from jericho import * >>> env = FrotzEnv(rom_path) >>> try: >>> save = env.save_str() >>> env.step('attack troll') # Oops! 'You swing and miss. The troll neatly removes your head.' >>> env.load_str(save) # Whew, let's try something else >>> except RuntimeError: >>> print('Skipping Save') ''' warnings.warn('load_str is deprecated. Use set_state instead.', DeprecationWarning) success = self.frotz_lib.restore_str(as_ctypes(buff)) if success <= 0: raise RuntimeError('Unable to load.')
def save_str(self): # Saves the game and returns a string containing the saved game buff = np.zeros(8192, dtype=np.uint8) success = frotz_lib.save_str(as_ctypes(buff)) if success <= 0: raise RuntimeError('Unable to save.') return buff
def next_msg(self, buf=None): """ Returns the next message in core. This is an alias for calling ``next_msg_size`` followed by ``next_msg``. If `buf` is passed in, this will reallocate or resize buf as necessary to fill it, otherwise it will allocate a new buffer. Regardless, the buffer is returned. See the ``scaii-core`` documentation for more info. """ from numpy import ctypeslib assert self.core != None size = SCAII_CORE.next_msg_size(self.core) if buf is None: buf = np.empty(size, dtype=c_ubyte) else: buf.resize(size) SCAII_CORE.next_msg(self.core, ctypeslib.as_ctypes(buf[:]), size) return buf
def contacts_compute_boundary(self, node_mask: ndarray, polygons: GeometryList, search_radius: float) -> None: """Computes Mesh1d-Mesh2d contacts, where Mesh1d nodes are connected to the closest Mesh2d faces at the boundary Args: node_mask (ndarray): A boolean array describing whether Mesh1d nodes should or should not be connected points (GeometryList): The points selecting the Mesh2d faces to connect. search_radius (float): The radius used for searching neighboring Mesh2d faces. If it is equal to the missing value double, the search radius will be calculated internally. """ node_mask_int = node_mask.astype(np.int32) c_node_mask = as_ctypes(node_mask_int) c_polygons = CGeometryList.from_geometrylist(polygons) self._execute_function( self.lib.mkernel_contacts_compute_boundary, self._meshkernelid, c_node_mask, byref(c_polygons), c_double(search_radius), )
def Jacobi(A, b, ks=1000, cuda=CUDAcapable): """ Resolve Ax = b através do método iterativo de Jacobi. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." assert b.shape[0] == A.shape[0], "'b' deve ser compatível com A." n = A.shape[0] x = zeros(n) func = kernels.CUJacobi if cuda else lib.SolveJacobi try: func(n, ks, byref(ctypeslib.as_ctypes(A)), byref(ctypeslib.as_ctypes(x)), byref(ctypeslib.as_ctypes(b))) except: raise return x
def arrsort (arr): base_ptr = POINTER (as_ctypes (arr)._type_) functype = CFUNCTYPE (c_int, base_ptr, base_ptr) nmemb, = arr.shape size, = arr.strides cmpfun = functype (_cmpelem) _lib.qsort (arr, nmemb, size, cast (cmpfun, _cmptype))
def from_contacts(contacts: Contacts) -> CContacts: """Creates a new `CContacts` instance from the given Contacts instance. Args: contacts (Contacts): The contacts. Returns: CContacts: The created C-Structure for the given Contacts. """ c_contacts = CContacts() c_contacts.mesh1d_indices = as_ctypes(contacts.mesh1d_indices) c_contacts.mesh2d_indices = as_ctypes(contacts.mesh2d_indices) c_contacts.num_contacts = contacts.mesh1d_indices.size return c_contacts
def act(self, action): try: action = int(action) action = np.array([action], dtype=np.intc) except Exception: action = np.asarray(action, dtype=np.intc) len_action = len(action) len_expected = ale_lib.actMultiSize(self.obj) if len_action != len_expected: raise RuntimeError( "expected action of length {} for game mode, got action of length {}" .format(len_expected, len_action)) rewards = np.zeros_like(action) ale_lib.actMulti(self.obj, as_ctypes(action), as_ctypes(rewards)) return rewards
def run_filter(self, steps, input): """Run the filter""" if type(input[0]) != np.int64: print("Warning: type error") n_samples_output = np.int64(len(input) * (self.r)) steps_ct = ct.c_longlong(steps) input_ct = npct.as_ctypes(input) output_ct = npct.as_ctypes(np.zeros(n_samples_output, dtype=np.int64)) libhog.CICInterpolatorI64InOutSet(self.obj, input_ct, output_ct) libhog.CICInterpolatorRunFilter(self.obj, steps_ct) output = npct.as_array(output_ct) output = output.astype(np.int64) return output
def getBestPosition(self): ''' Return the best particle position of the swarm as a 1D NumPy array. The size of the array is self.getNumDimensions(). ''' iNumDims = self.getNumDimensions() aResult = np.zeros((iNumDims, ), np.float64) pLibDTSG.tsgParticleSwarmState_GetBestPosition(self.pStatePntr, as_ctypes(aResult)) return aResult
def getScreen(self, tbl): ''' Stores the list of pixels currently displayed in the given array. :param tbl: A numpy array that should be able to contain all the pixels. The size has to be set before hand so use getScreenWidth and getScreenHeight to create it. It should be defines as such : tbl = np.empty(getScreenWidth() * getScreenHeight(), dtype=np.uint32) ''' amle_lib.getRGBScreen(self.obj, as_ctypes(tbl))
def _get_ram(self): """ Returns a numpy array containing the contents of the Z-Machine's RAM. """ ram_size = self.frotz_lib.getRAMSize() ram = np.zeros(ram_size, dtype=np.uint8) self.frotz_lib.getRAM(as_ctypes(ram)) return ram
def getLegalActions(self, tbl): ''' Stores the set of legal actions of the current game in the given array. :param tbl: A numpy array that should be able to contain all the legal action. The size has to be set before hand so use getNbLegalActions to create it. It should be defines as such : tbl = np.empty(getNbLegalActions(), dtype=np.int32) ''' amle_lib.getLegalActions(self.obj, as_ctypes(tbl))
def _get_special_ram(self): """ Returns a numpy array containing the contents of the special ram addresses for the game. """ ram_size = self.frotz_lib.get_special_ram_size() ram = np.zeros(ram_size, dtype=np.uint8) self.frotz_lib.get_special_ram(as_ctypes(ram)) return ram
def dedisperse_gpu(self,output_dir=".",out_bits=32,gulp=160000): ndm = self.get_dm_count() delay = self.get_max_delay() if gulp-delay < 2*delay: gulp = 2*delay if out_bits == 32: dtype = "float32" elif out_bits == 8: dtype = "ubyte" else: raise ValueError("out_bits must be 8 or 32") outsamps = gulp-delay print outsamps,out_bits,dtype dms = self.get_dm_list() out_files = [] changes = {"refdm" :0, "nchans":1, "nbits" :out_bits} basename = self.header.basename.split("/")[-1] for dm in dms: changes["refdm"] = dm filename = "%s/%s_DM%08.2f.tim"%(output_dir,basename,dm) out_files.append(self.header.prepOutfile(filename,changes,nbits=out_bits)) out_size = outsamps * ndm * out_bits/8 output = np.empty(out_size,dtype=dtype) func = lib.dedisp_execute for nsamps,ii,data in self.readPlan(gulp=gulp,skipback=delay): error = func(self.plan, C.c_size_t(nsamps), as_ctypes(data), C.c_size_t(self.header.nbits), as_ctypes(output), C.c_size_t(out_bits), C.c_int(0)); error_check(error) for ii,out_file in enumerate(out_files): out_file.cwrite(output[ii*outsamps:(ii+1)*outsamps]) for out_file in out_files: out_file.close()
def LUCroutInplaceDecompose(A): """ Implementação do método de Crout para decomposição LU sobrescrevendo a matriz original. """ assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN." LU = A.copy() n = A.shape[0] lib.LUInDec(n, byref(ctypeslib.as_ctypes(LU))) return LU
def from_geometrylist(geometry_list: GeometryList) -> CGeometryList: """Creates a new `CGeometryList` instance from the given GeometryList instance. Args: geometry_list (GeometryList): The geometry list. Returns: CGeometryList: The created C-Structure for the given GeometryList. """ c_geometry_list = CGeometryList() c_geometry_list.geometry_separator = geometry_list.geometry_separator c_geometry_list.inner_outer_separator = geometry_list.inner_outer_separator c_geometry_list.n_coordinates = geometry_list.x_coordinates.size c_geometry_list.x_coordinates = as_ctypes(geometry_list.x_coordinates) c_geometry_list.y_coordinates = as_ctypes(geometry_list.y_coordinates) c_geometry_list.values = as_ctypes(geometry_list.values) return c_geometry_list
def getAudio(self, audio_data=None): """This function fills audio_data with the data audio_data MUST be a numpy array of uint8. This can be initialized like so: audio_data = np.empty(ale.getAudioSize()), dtype=np.uint8) If it is None, then this function will initialize it. """ if (audio_data is None): audio_buffer_size = ale_lib.getAudioSize(self.obj) audio_data = np.empty(audio_buffer_size, dtype=np.uint8) ale_lib.getAudio(self.obj, as_ctypes(audio_data)) return audio_data
def getRAM(self,ram=None): """This function grabs the atari RAM. ram MUST be a numpy array of uint8/int8. This can be initialized like so: ram = np.array(ram_size,dtype=uint8) Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function. If it is None, then this function will initialize it. """ if(ram is None): ram_size = ale_lib.getRAMSize(self.obj) ram = np.zeros(ram_size,dtype=np.uint8) ale_lib.getRAM(self.obj,as_ctypes(ram))
def getParticleVelocities(self): ''' Return the particle velocities as a 2D NumPy array. The shape of this array is (self.getNumParticles(), self.getNumDimensions()) and the i-th row if this array corresponds to the velocity of the i-th particle. ''' iNumDims = self.getNumDimensions() iNumPart = self.getNumParticles() aResult = np.zeros((iNumDims * iNumPart, ), np.float64) pLibDTSG.tsgParticleSwarmState_GetParticleVelocities( self.pStatePntr, as_ctypes(aResult)) return aResult.reshape((iNumPart, iNumDims))
def operation(Q): data = as_ctypes(numpy.zeros(512, 'd')) pid = os.getpid() for i in xrange(3): Q.put(data) for i in xrange(10000): Q.put(data) j = Q.get() print len(j), pid return True
def _construct_model_measure_params_1d(measure_params, i_elevation): """ :param measure_params: relative_hts, z_g, z_u, z_T, z_0 :param i_elevation: :return: """ return model_measure_params_1d( int(measure_params[0]), float(measure_params[1]), float(measure_params[2]), float(measure_params[3]), float(measure_params[4]), as_ctypes(i_elevation.astype(np.float64).flatten()))
def getScreenGrayscale(self, screen_data=None): """This function fills screen_data with the data in grayscale screen_data MUST be a numpy array of uint8. This can be initialized like so: screen_data = np.empty((height,width,1), dtype=np.uint8) If it is None, then this function will initialize it. """ if(screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.empty((height, width,1), dtype=np.uint8) ale_lib.getScreenGrayscale(self.obj, as_ctypes(screen_data[:])) return screen_data
def getScreenGrayscale(self, screen_data=None): """This function fills screen_data with the data in grayscale screen_data MUST be a numpy array of uint8. This can be initialized like so: screen_data = np.empty((height,width,1), dtype=np.uint8) If it is None, then this function will initialize it. """ if (screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.empty((height, width, 1), dtype=np.uint8) ale_lib.getScreenGrayscale(self.obj, as_ctypes(screen_data[:])) return screen_data
def getBestParticlePositions(self): ''' Return the best particle positions as a 2D NumPy array. The shape of this array is (self.getNumParticles()+1 , self.getNumDimensions()) and the i-th row if this array corresponds to the best position of the i-th particle for the first .getNumParticles() particles. The last row corresponds to the best particle position of the swarm. ''' iNumDims = self.getNumDimensions() iNumPart = self.getNumParticles() aResult = np.zeros((iNumDims * (iNumPart + 1), ), np.float64) pLibDTSG.tsgParticleSwarmState_GetBestParticlePositions( self.pStatePntr, as_ctypes(aResult)) return aResult.reshape((iNumPart + 1, iNumDims))
def getScreenRGB(self, screen_data=None): """This function fills screen_data with the data screen_data MUST be a numpy array of uint/int. This can be initialized like so: screen_data = np.array(w*h, dtype=np.intc) Notice, it must be width*height in size also If it is None, then this function will initialize it """ if(screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.zeros(width*height, dtype=np.intc) ale_lib.getScreenRGB(self.obj, as_ctypes(screen_data)) return screen_data
def getScreen(self, screen_data=None): """This function fills screen_data with the RAW Pixel data screen_data MUST be a numpy array of uint8/int8. This could be initialized like so: screen_data = np.empty(w*h, dtype=np.uint8) Notice, it must be width*height in size also If it is None, then this function will initialize it Note: This is the raw pixel values from the atari, before any RGB palette transformation takes place """ if(screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.zeros(width*height, dtype=np.uint8) ale_lib.getScreen(self.obj, as_ctypes(screen_data)) return screen_data
def getScreenRGB2(self, screen_data=None): """This function fills screen_data with the data in RGB format. screen_data MUST be a numpy array of uint8. This can be initialized like so: screen_data = np.empty((height,width,3), dtype=np.uint8) If it is None, then this function will initialize it. On all architectures, the channels are RGB order: screen_data[x, y, :] is [red, green, blue] There's not much error checking here: if you supply an array that's too small this function will produce undefined behavior. """ if(screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.empty((height, width, 3), dtype=np.uint8) assert screen_data.strides == (480, 3, 1) ale_lib.getScreenRGB2(self.obj, as_ctypes(screen_data[:])) return screen_data
def getScreenRGB(self, screen_data=None): """This function fills screen_data with the data in RGB format screen_data MUST be a numpy array of uint8. This can be initialized like so: screen_data = np.empty((height,width,3), dtype=np.uint8) If it is None, then this function will initialize it. On little-endian machines like x86, the channels are BGR order: screen_data[x, y, 0:3] is [blue, green, red] On big-endian machines (rare in 2017) the channels would be the opposite order. There's not much error checking here: if you supply an array that's too small this function will produce undefined behavior. """ if(screen_data is None): width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) screen_data = np.empty((height, width,3), dtype=np.uint8) ale_lib.getScreenRGB(self.obj, as_ctypes(screen_data[:])) return screen_data
def from_array(self, arr, _ctype=ctype): "set up a descriptor from a compatible numpy array, preferably a fortran-order numpy array" dims = arr.shape rank = len(dims) nelems = reduce(mul, dims, 1) assert(len(self.dim) == rank) ctarr = as_ctypes(arr) # compatibility sanity check assert(arr.dtype == _ctype) # ctype = _base_ctype(ctarr, arr.shape) ct = cast(ctarr, type(self.mem)) csize = sizeof(_ctype) self.mem = ct self.dtype_rank = rank self.dtype_size = csize self.dtype_type = GFC_DTYPE_TAB.get(_ctype, GFC_DTYPE_DERIVED) axes = list(self.dim) for width, axis, stride in zip(dims, axes, arr.strides): axis.stride = stride / csize axis.lbound = 1 axis.ubound = width
def from_ndarray(self, param): # return param.data_as(POINTER(c_double)) # the above older method does not work with # functions which take vectors of known size return numpc.as_ctypes(param.astype(numpy.float64, casting='same_kind', copy=False))
def decodeState(self, serialized): return ale_lib.decodeState(as_ctypes(serialized), len(serialized))
def encodeState(self, state, buf=None): if buf == None: length = ale_lib.encodeStateLen(state) buf = np.zeros(length, dtype=np.uint8) ale_lib.encodeState(state, as_ctypes(buf), c_int(len(buf))) return buf
def from_matrix(self, param): # cspice always uses a int size half as big as the float, ie int32 if a float64 system default return numpc.as_ctypes(param.astype(numpy.int32, casting='same_kind', copy=False))
def getMinimalActionSet(self): act_size = ale_lib.getMinimalActionSize(self.obj) act = np.zeros((act_size), dtype=np.intc) ale_lib.getMinimalActionSet(self.obj, as_ctypes(act)) return act
def getState(self, state_data=None): """ Returns the current state features """ if state_data is None: state_data = np.zeros(self.getStateSize(), dtype=np.float32) hfo_lib.getState(self.obj, as_ctypes(state_data)) return state_data
def from_matrix(self, param): return numpc.as_ctypes(param.astype(numpy.float64, casting='same_kind', copy=False))
def chromaLesserWrapper(chunk, N, sampleRate, fs): # downsample to 11025 Hz rateChange = fs / sampleRate sig.resample(chunk, len(chunk) * rateChange) return chromaFunc(npct.as_ctypes(np.ascontiguousarray(chunk[:,0], dtype=np.int16)), N, fmin_ctype, fmax_ctype, M, B, exp2_1_B, K, Q_ctype, fs)