text
stringlengths
1.18k
92.5k
lang
stringclasses
39 values
# cython: language_level=3 # Copyright (c) 2014-2023, Dr Alex Meakins, Raysect Project # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the Raysect Project nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from raysect.optical.colour import d65_white from raysect.optical cimport World, Primitive, Ray, Spectrum, Point3D, AffineMatrix3D, Normal3D, Intersection from libc.math cimport round, fabs cimport cython cdef class Checkerboard(NullVolume): """ Isotropic checkerboard surface emitter Defines a plane of alternating squares of emission forming a checkerboard pattern. Useful in debugging and as a light source in test scenes. :param float width: The width of the squares in metres. :param SpectralFunction emission_spectrum1: Emission spectrum for square one. :param SpectralFunction emission_spectrum2: Emission spectrum for square two. :param float scale1: Intensity of square one emission. :param float scale2: Intensity of square two emission. .. code-block:: pycon >>> from raysect.primitive import Box >>> from raysect.optical import World, rotate, Point3D, d65_white >>> from raysect.optical.material import Checkerboard >>> >>> world = World() >>> >>> # checker board wall that acts as emitter >>> emitter = Box(lower=Point3D(-10, -10, 10), upper=Point3D(10, 10, 10.1), parent=world, transform=rotate(45, 0, 0)) >>> emitter.material=Checkerboard(4, d65_white, d65_white, 0.1, 2.0) """ def __init__(self, double width=1.0, SpectralFunction emission_spectrum1=d65_white, SpectralFunction emission_spectrum2=d65_white, double scale1=0.25, double scale2=0.5): super().__init__() self._width = width self._rwidth = 1.0 / width self.emission_spectrum1 = emission_spectrum1 self.emission_spectrum2 = emission_spectrum2 self.scale1 = scale1 self.scale2 = scale2 self.importance = 1.0 @property def width(self): """ The width of the squares in metres. :rtype: float """ return self._width @width.setter @cython.cdivision(True) def width(self, double v): self._width = v self._rwidth = 1.0 / v @cython.boundscheck(False) @cython.wraparound(False) @cython.initializedcheck(False) cpdef Spectrum evaluate_surface(self, World world, Ray ray, Primitive primitive, Point3D hit_point, bint exiting, Point3D inside_point, Point3D outside_point, Normal3D normal, AffineMatrix3D world_to_primitive, AffineMatrix3D primitive_to_world, Intersection intersection): cdef: Spectrum spectrum double[::1] emission bint v int index double scale v = False # generate check pattern v = self._flip(v, hit_point.x) v = self._flip(v, hit_point.y) v = self._flip(v, hit_point.z) # select emission spectrum = ray.new_spectrum() if v: emission = self.emission_spectrum1.sample_mv(spectrum.min_wavelength, spectrum.max_wavelength, spectrum.bins) scale = self.scale1 else: emission = self.emission_spectrum2.sample_mv(spectrum.min_wavelength, spectrum.max_wavelength, spectrum.bins) scale = self.scale2 for index in range(spectrum.bins): spectrum.samples_mv[index] = emission[index] * scale return spectrum @cython.cdivision(True) cdef bint _flip(self, bint v, double p) nogil: # round to avoid numerical precision issues (rounds to nearest nanometer) p = round(p * 1e9) / 1e9 # generates check pattern from [0, inf] if fabs(self._rwidth * p) % 2 >= 1.0: v = not v # invert pattern for negative if p < 0: v = not v return v <|end_of_text|># cython: c_string_type=unicode, c_string_encoding=ascii # ------------------------------------------------------------------------------------------------- # Imports # ------------------------------------------------------------------------------------------------- from functools import wraps, partial import logging import traceback import sys cimport numpy as np import numpy as np from cpython.ref cimport Py_INCREF from libc.string cimport memcpy from libc.stdio cimport printf cimport datoviz.cydatoviz as cv logger = logging.getLogger('datoviz') # ------------------------------------------------------------------------------------------------- # Types # ------------------------------------------------------------------------------------------------- ctypedef np.float32_t FLOAT ctypedef np.double_t DOUBLE ctypedef np.uint8_t CHAR ctypedef np.uint8_t[4] CVEC4 ctypedef np.int16_t SHORT ctypedef np.uint16_t USHORT ctypedef np.int32_t INT ctypedef np.uint32_t UINT ctypedef np.uint32_t[3] TEX_SHAPE # ------------------------------------------------------------------------------------------------- # Constants # ------------------------------------------------------------------------------------------------- # region # folding in VSCode DEFAULT_WIDTH = 800 DEFAULT_HEIGHT = 600 cdef TEX_SHAPE DVZ_ZERO_OFFSET = (0, 0, 0) # TODO: add more keys _KEYS = { cv.DVZ_KEY_LEFT: 'left', cv.DVZ_KEY_RIGHT: 'right', cv.DVZ_KEY_UP: 'up', cv.DVZ_KEY_DOWN: 'down', cv.DVZ_KEY_HOME: 'home', cv.DVZ_KEY_END: 'end', cv.DVZ_KEY_KP_ADD: '+', cv.DVZ_KEY_KP_SUBTRACT: '-', cv.DVZ_KEY_F: 'f', cv.DVZ_KEY_R: 'r', cv.DVZ_KEY_G: 'g', } # HACK: these keys do not raise a Python key event _EXCLUDED_KEYS = ( cv.DVZ_KEY_NONE, cv.DVZ_KEY_LEFT_SHIFT, cv.DVZ_KEY_LEFT_CONTROL, cv.DVZ_KEY_LEFT_ALT, cv.DVZ_KEY_LEFT_SUPER, cv.DVZ_KEY_RIGHT_SHIFT, cv.DVZ_KEY_RIGHT_CONTROL, cv.DVZ_KEY_RIGHT_ALT, cv.DVZ_KEY_RIGHT_SUPER, ) _BUTTONS = { cv.DVZ_MOUSE_BUTTON_LEFT: 'left', cv.DVZ_MOUSE_BUTTON_MIDDLE:'middle', cv.DVZ_MOUSE_BUTTON_RIGHT: 'right', } _MODIFIERS = { cv.DVZ_KEY_MODIFIER_SHIFT:'shift', cv.DVZ_KEY_MODIFIER_CONTROL: 'control', cv.DVZ_KEY_MODIFIER_ALT: 'alt', cv.DVZ_KEY_MODIFIER_SUPER:'super', } _BUTTONS_INV = {v: k for k, v in _BUTTONS.items()} _EVENTS ={ 'mouse_press': cv.DVZ_EVENT_MOUSE_PRESS, 'mouse_release': cv.DVZ_EVENT_MOUSE_RELEASE, 'mouse_move': cv.DVZ_EVENT_MOUSE_MOVE, 'mouse_wheel': cv.DVZ_EVENT_MOUSE_WHEEL, 'mouse_drag_begin': cv.DVZ_EVENT_MOUSE_DRAG_BEGIN, 'mouse_drag_end': cv.DVZ_EVENT_MOUSE_DRAG_END, 'mouse_click': cv.DVZ_EVENT_MOUSE_CLICK, 'mouse_double_click': cv.DVZ_EVENT_MOUSE_DOUBLE_CLICK, 'key_press': cv.DVZ_EVENT_KEY_PRESS, 'key_release': cv.DVZ_EVENT_KEY_RELEASE, 'frame': cv.DVZ_EVENT_FRAME, 'timer': cv.DVZ_EVENT_TIMER, 'gui': cv.DVZ_EVENT_GUI, } _VISUALS =
Cython
{ 'point': cv.DVZ_VISUAL_POINT, 'marker': cv.DVZ_VISUAL_MARKER, 'mesh': cv.DVZ_VISUAL_MESH, 'path': cv.DVZ_VISUAL_PATH, 'text': cv.DVZ_VISUAL_TEXT, 'polygon': cv.DVZ_VISUAL_POLYGON, 'image': cv.DVZ_VISUAL_IMAGE, 'image_cmap': cv.DVZ_VISUAL_IMAGE_CMAP, 'volume': cv.DVZ_VISUAL_VOLUME, 'volume_slice': cv.DVZ_VISUAL_VOLUME_SLICE, 'line_strip': cv.DVZ_VISUAL_LINE_STRIP, 'rectangle': cv.DVZ_VISUAL_RECTANGLE, } _CONTROLLERS = { 'panzoom': cv.DVZ_CONTROLLER_PANZOOM, 'axes': cv.DVZ_CONTROLLER_AXES_2D, 'arcball': cv.DVZ_CONTROLLER_ARCBALL, 'camera': cv.DVZ_CONTROLLER_CAMERA, } _TRANSPOSES = { None: cv.DVZ_CDS_TRANSPOSE_NONE, 'xfyrzu': cv.DVZ_CDS_TRANSPOSE_XFYRZU, 'xbydzl': cv.DVZ_CDS_TRANSPOSE_XBYDZL, 'xlybzd': cv.DVZ_CDS_TRANSPOSE_XLYBZD, } _COORDINATE_SYSTEMS = { 'data': cv.DVZ_CDS_DATA, 'scene': cv.DVZ_CDS_SCENE, 'vulkan': cv.DVZ_CDS_VULKAN, 'framebuffer': cv.DVZ_CDS_FRAMEBUFFER, 'window': cv.DVZ_CDS_WINDOW, } _PROPS = { 'pos': cv.DVZ_PROP_POS, 'color': cv.DVZ_PROP_COLOR, 'alpha': cv.DVZ_PROP_ALPHA, 'ms': cv.DVZ_PROP_MARKER_SIZE, 'marker': cv.DVZ_PROP_MARKER_TYPE, 'normal': cv.DVZ_PROP_NORMAL, 'texcoords': cv.DVZ_PROP_TEXCOORDS, 'index': cv.DVZ_PROP_INDEX, 'range': cv.DVZ_PROP_RANGE, 'length': cv.DVZ_PROP_LENGTH, 'text': cv.DVZ_PROP_TEXT, 'glyph': cv.DVZ_PROP_GLYPH, 'text_size': cv.DVZ_PROP_TEXT_SIZE, 'scale': cv.DVZ_PROP_SCALE, 'cap_type': cv.DVZ_PROP_CAP_TYPE, 'light_params': cv.DVZ_PROP_LIGHT_PARAMS, 'light_pos': cv.DVZ_PROP_LIGHT_POS, 'texcoefs': cv.DVZ_PROP_TEXCOEFS, 'linewidth': cv.DVZ_PROP_LINE_WIDTH, 'colormap': cv.DVZ_PROP_COLORMAP, 'transferx': cv.DVZ_PROP_TRANSFER_X, 'transfery': cv.DVZ_PROP_TRANSFER_Y, 'clip': cv.DVZ_PROP_CLIP, } _DTYPES = { cv.DVZ_DTYPE_CHAR: (np.uint8, 1), cv.DVZ_DTYPE_CVEC2: (np.uint8, 2), cv.DVZ_DTYPE_CVEC3: (np.uint8, 3), cv.DVZ_DTYPE_CVEC4: (np.uint8, 4), cv.DVZ_DTYPE_USHORT: (np.uint16, 1), cv.DVZ_DTYPE_USVEC2: (np.uint16, 2), cv.DVZ_DTYPE_USVEC3: (np.uint16, 3), cv.DVZ_DTYPE_USVEC4: (np.uint16, 4), cv.DVZ_DTYPE_SHORT: (np.int16, 1), cv.DVZ_DTYPE_SVEC2: (np.int16, 2), cv.DVZ_DTYPE_SVEC3: (np.int16, 3), cv.DVZ_DTYPE_SVEC4: (np.int16, 4), cv.DVZ_DTYPE_UINT: (np.uint32, 1), cv.DVZ_DTYPE_UVEC2: (np.uint32, 2), cv.DVZ_DTYPE_UVEC3: (np.uint32, 3), cv.DVZ_DTYPE_UVEC4: (np.uint32, 4), cv.DVZ_DTYPE_INT: (np.int32, 1), cv.DVZ_DTYPE_IVEC2: (np.int32, 2), cv.DVZ_DTYPE_IVEC3: (np.int32, 3), cv.DVZ_DTYPE_IVEC4: (np.int32, 4), cv.DVZ_DTYPE_FLOAT: (np.float32, 1), cv.DVZ_DTYPE_VEC2: (np.float32, 2), cv.DVZ_DTYPE_VEC3: (np.float32, 3), cv.DVZ_DTYPE_VEC4: (np.float32, 4), cv.DVZ_DTYPE_DOUBLE: (np.double, 1), cv.DVZ_DTYPE_DVEC2: (np.double, 2), cv.DVZ_DTYPE_DVEC3: (np.double, 3), cv.DVZ_DTYPE_DVEC4: (np.double, 4), cv.DVZ_DTYPE_MAT2: (np.float32, (2, 2)), cv.DVZ_DTYPE_MAT3: (np.float32, (3, 3)), cv.DVZ_DTYPE_MAT4: (np.float32, (4, 4)), cv.DVZ_DTYPE_STR: (np.dtype('S1'), 1), } _TRANSFORMS = { 'earth': cv.DVZ_TRANSFORM_EARTH_MERCATOR_WEB, } _CONTROLS = { 'slider_float': cv.DVZ_GUI_CONTROL_SLIDER_FLOAT, 'slider_float2': cv.DVZ_GUI_CONTROL_SLIDER_FLOAT2, 'slider_int': cv.DVZ_GUI_CONTROL_SLIDER_INT, 'input_float': cv.DVZ_GUI_CONTROL_INPUT_FLOAT, 'checkbox': cv.DVZ_GUI_CONTROL_CHECKBOX, 'button': cv.DVZ_GUI_CONTROL_BUTTON, 'label': cv.DVZ_GUI_CONTROL_LABEL, } _COLORMAPS = { 'binary': cv.DVZ_CMAP_BINARY, 'hsv': cv.DVZ_CMAP_HSV, 'cividis': cv.DVZ_CMAP_CIVIDIS, 'inferno': cv.DVZ_CMAP_INFERNO, 'magma': cv.DVZ_CMAP_MAGMA, 'plasma': cv.DVZ_CMAP_PLASMA, 'viridis': cv.DVZ_CMAP_VIRIDIS, 'blues': cv.DVZ_CMAP_BLUES, 'bugn': cv.DVZ_CMAP_BUGN, 'bupu': cv.DVZ_CMAP_BUPU, 'gnbu': cv.DVZ_CMAP_GNBU, 'greens': cv.DVZ_CMAP_GREENS, 'greys': cv.DVZ_CMAP_GREYS, 'oranges': cv.DVZ_CMAP_ORANGES, 'orrd': cv.DVZ_CMAP_ORRD, 'pubu': cv.DVZ_CMAP_PUBU, 'pubugn': cv.DVZ_CMAP_PUBUGN, 'purples': cv.DVZ_CMAP_PURPLES, 'rdpu': cv.DVZ_CMAP_RDPU, 'reds': cv.DVZ_CMAP_REDS, 'ylgn': cv.DVZ_CMAP_YLGN, 'ylgnbu': cv.DVZ_CMAP_YLGNBU, 'ylorbr': cv.DVZ_CMAP_YLORBR, 'ylorrd': cv.DVZ_CMAP_YLORRD, 'afmhot': cv.DVZ_CMAP_AFMHOT, 'autumn': cv.DVZ_CMAP_AUTUMN, 'bone': cv.DVZ_CMAP_BONE, 'cool': cv.DVZ_CMAP_COOL, 'copper': cv.DVZ_CMAP_COPPER, 'gist_heat': cv.DVZ_CMAP_GIST_HEAT, 'gray': cv.DVZ_CMAP_GRAY, 'hot': cv.DVZ_CMAP_HOT, 'pink': cv.DVZ_CMAP_PINK, 'spring': cv.DVZ_CMAP_SPRING, 'summer': cv.DVZ_CMAP_SUMMER, 'winter': cv.DVZ_CMAP_WINTER, 'wistia': cv.DVZ_CMAP_WISTIA, 'brbg': cv.DVZ_CMAP_BRBG, 'bwr': cv.DVZ_CMAP_BWR, 'coolwarm': cv.DVZ_CMAP_COOLWARM, 'piyg': cv.DVZ_CMAP_PIYG, 'prgn': cv.DVZ_CMAP_PRGN, 'puor': cv.DVZ_CMAP_PUOR, 'rdbu': cv.DVZ_CMAP_RDBU, 'rdgy': cv.DVZ_CMAP_RDGY, 'rd
Cython
ylbu': cv.DVZ_CMAP_RDYLBU, 'rdylgn': cv.DVZ_CMAP_RDYLGN, 'seismic': cv.DVZ_CMAP_SEISMIC, 'spectral': cv.DVZ_CMAP_SPECTRAL, 'twilight_shifted': cv.DVZ_CMAP_TWILIGHT_SHIFTED, 'twilight': cv.DVZ_CMAP_TWILIGHT, 'brg': cv.DVZ_CMAP_BRG, 'cmrmap': cv.DVZ_CMAP_CMRMAP, 'cubehelix': cv.DVZ_CMAP_CUBEHELIX, 'flag': cv.DVZ_CMAP_FLAG, 'gist_earth': cv.DVZ_CMAP_GIST_EARTH, 'gist_ncar': cv.DVZ_CMAP_GIST_NCAR, 'gist_rainbow': cv.DVZ_CMAP_GIST_RAINBOW, 'gist_stern': cv.DVZ_CMAP_GIST_STERN, 'gnuplot2': cv.DVZ_CMAP_GNUPLOT2, 'gnuplot': cv.DVZ_CMAP_GNUPLOT, 'jet': cv.DVZ_CMAP_JET, 'nipy_spectral': cv.DVZ_CMAP_NIPY_SPECTRAL, 'ocean': cv.DVZ_CMAP_OCEAN, 'prism': cv.DVZ_CMAP_PRISM, 'rainbow': cv.DVZ_CMAP_RAINBOW, 'terrain': cv.DVZ_CMAP_TERRAIN, 'bkr': cv.DVZ_CMAP_BKR, 'bky': cv.DVZ_CMAP_BKY, 'cet_d10': cv.DVZ_CMAP_CET_D10, 'cet_d11': cv.DVZ_CMAP_CET_D11, 'cet_d8': cv.DVZ_CMAP_CET_D8, 'cet_d13': cv.DVZ_CMAP_CET_D13, 'cet_d3': cv.DVZ_CMAP_CET_D3, 'cet_d1a': cv.DVZ_CMAP_CET_D1A, 'bjy': cv.DVZ_CMAP_BJY, 'gwv': cv.DVZ_CMAP_GWV, 'bwy': cv.DVZ_CMAP_BWY, 'cet_d12': cv.DVZ_CMAP_CET_D12, 'cet_r3': cv.DVZ_CMAP_CET_R3, 'cet_d9': cv.DVZ_CMAP_CET_D9, 'cwr': cv.DVZ_CMAP_CWR, 'cet_cbc1': cv.DVZ_CMAP_CET_CBC1, 'cet_cbc2': cv.DVZ_CMAP_CET_CBC2, 'cet_cbl1': cv.DVZ_CMAP_CET_CBL1, 'cet_cbl2': cv.DVZ_CMAP_CET_CBL2, 'cet_cbtc1': cv.DVZ_CMAP_CET_CBTC1, 'cet_cbtc2': cv.DVZ_CMAP_CET_CBTC2, 'cet_cbtl1': cv.DVZ_CMAP_CET_CBTL1, 'bgy': cv.DVZ_CMAP_BGY, 'bgyw': cv.DVZ_CMAP_BGYW, 'bmw': cv.DVZ_CMAP_BMW, 'cet_c1': cv.DVZ_CMAP_CET_C1, 'cet_c1s': cv.DVZ_CMAP_CET_C1S, 'cet_c2': cv.DVZ_CMAP_CET_C2, 'cet_c4': cv.DVZ_CMAP_CET_C4, 'cet_c4s': cv.DVZ_CMAP_CET_C4S, 'cet_c5': cv.DVZ_CMAP_CET_C5, 'cet_i1': cv.DVZ_CMAP_CET_I1, 'cet_i3': cv.DVZ_CMAP_CET_I3, 'cet_l10': cv.DVZ_CMAP_CET_L10, 'cet_l11': cv.DVZ_CMAP_CET_L11, 'cet_l12': cv.DVZ_CMAP_CET_L12, 'cet_l16': cv.DVZ_CMAP_CET_L16, 'cet_l17': cv.DVZ_CMAP_CET_L17, 'cet_l18': cv.DVZ_CMAP_CET_L18, 'cet_l19': cv.DVZ_CMAP_CET_L19, 'cet_l4': cv.DVZ_CMAP_CET_L4, 'cet_l7': cv.DVZ_CMAP_CET_L7, 'cet_l8': cv.DVZ_CMAP_CET_L8, 'cet_l9': cv.DVZ_CMAP_CET_L9, 'cet_r1': cv.DVZ_CMAP_CET_R1, 'cet_r2': cv.DVZ_CMAP_CET_R2, 'colorwheel': cv.DVZ_CMAP_COLORWHEEL, 'fire': cv.DVZ_CMAP_FIRE, 'isolum': cv.DVZ_CMAP_ISOLUM, 'kb': cv.DVZ_CMAP_KB, 'kbc': cv.DVZ_CMAP_KBC, 'kg': cv.DVZ_CMAP_KG, 'kgy': cv.DVZ_CMAP_KGY, 'kr': cv.DVZ_CMAP_KR, 'black_body': cv.DVZ_CMAP_BLACK_BODY, 'kindlmann': cv.DVZ_CMAP_KINDLMANN, 'extended_kindlmann': cv.DVZ_CMAP_EXTENDED_KINDLMANN, 'glasbey': cv.DVZ_CPAL256_GLASBEY, 'glasbey_cool': cv.DVZ_CPAL256_GLASBEY_COOL, 'glasbey_dark': cv.DVZ_CPAL256_GLASBEY_DARK, 'glasbey_hv': cv.DVZ_CPAL256_GLASBEY_HV, 'glasbey_light': cv.DVZ_CPAL256_GLASBEY_LIGHT, 'glasbey_warm': cv.DVZ_CPAL256_GLASBEY_WARM, 'accent': cv.DVZ_CPAL032_ACCENT, 'dark2': cv.DVZ_CPAL032_DARK2, 'paired': cv.DVZ_CPAL032_PAIRED, 'pastel1': cv.DVZ_CPAL032_PASTEL1, 'pastel2': cv.DVZ_CPAL032_PASTEL2, 'set1': cv.DVZ_CPAL032_SET1, 'set2': cv.DVZ_CPAL032_SET2, 'set3': cv.DVZ_CPAL032_SET3, 'tab10': cv.DVZ_CPAL032_TAB10, 'tab20': cv.DVZ_CPAL032_TAB20, 'tab20b': cv.DVZ_CPAL032_TAB20B, 'tab20c': cv.DVZ_CPAL032_TAB20C, 'category10_10': cv.DVZ_CPAL032_CATEGORY10_10, 'category20_20': cv.DVZ_CPAL032_CATEGORY20_20, 'category20b_20': cv.DVZ_CPAL032_CATEGORY20B_20, 'category20c_20': cv.DVZ_CPAL032_CATEGORY20C_20, 'colorblind8': cv.DVZ_CPAL032_COLORBLIND8, } _TEXTURE_FILTERS = { None: cv.VK_FILTER_NEAREST, 'nearest': cv.VK_FILTER_NEAREST, 'linear': cv.VK_FILTER_LINEAR, # 'cubic': cv.VK_FILTER_CUBIC_EXT, # requires extension VK_EXT_filter_cubic } _SOURCE_TYPES = { 1: cv.DVZ_SOURCE_TYPE_TRANSFER, 2: cv.DVZ_SOURCE_TYPE_IMAGE, 3: cv.DVZ_SOURCE_TYPE_VOLUME, } _FORMATS = { (np.dtype(np.uint8), 1): cv.VK_FORMAT_R8_UNORM, (np.dtype(np.uint8), 3): cv.VK_FORMAT_R8G8B8_UNORM, (np.dtype(np.uint8), 4): cv.VK_FORMAT_R8G8B8A8_UNORM, (np.dtype(np.uint16), 1): cv.VK_FORMAT_R16_UNORM, (np.dtype(np.int16), 1): cv.VK_FORMAT_R16_SNORM, (np.dtype(np.uint32), 1): cv.VK_FORMAT_R32_UINT, (np.dtype(np.int32), 1): cv.VK_FORMAT_R32_SINT, (np.dtype(np.float32), 1): cv.VK_FORMAT_R32_SFLOAT, } _MARKER_TYPES = { 'disc': cv.DVZ_MARKER_DISC, 'vbar': cv.DVZ_MARKER_VBAR, 'cross': cv.DVZ_MARKER_CROSS, } _CUSTOM_COLORMAPS = {} #endregion
Cython
# ------------------------------------------------------------------------------------------------- # Constant utils # ------------------------------------------------------------------------------------------------- def _key_name(key): """From key code used by Datoviz to key name.""" return _KEYS.get(key, key) def _button_name(button): """From button code used by Datoviz to button name.""" return _BUTTONS.get(button, None) def _get_modifiers(mod): """From modifier flag to a tuple of strings.""" mods_py = [] for c_enum, name in _MODIFIERS.items(): if mod & c_enum: mods_py.append(name) return tuple(mods_py) def _c_modifiers(*mods): cdef int mod, c_enum mod = 0 for c_enum, name in _MODIFIERS.items(): if name in mods: mod |= c_enum return mod def _get_prop(name): """From prop name to prop enum for Datoviz.""" return _PROPS[name] # ------------------------------------------------------------------------------------------------- # Python event callbacks # ------------------------------------------------------------------------------------------------- cdef _get_event_args(cv.DvzEvent c_ev): """Prepare the arguments to the Python event callbacks from the Datoviz DvzEvent struct.""" cdef float* fvalue cdef int* ivalue cdef bint* bvalue dt = c_ev.type # GUI events. if dt == cv.DVZ_EVENT_GUI: if c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_SLIDER_FLOAT: fvalue = <float*>c_ev.u.g.control.value return (fvalue[0],), {} elif c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_SLIDER_FLOAT2: fvalue = <float*>c_ev.u.g.control.value return (fvalue[0], fvalue[1]), {} elif c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_SLIDER_INT: ivalue = <int*>c_ev.u.g.control.value return (ivalue[0],), {} elif c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_INPUT_FLOAT: fvalue = <float*>c_ev.u.g.control.value return (fvalue[0],), {} elif c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_CHECKBOX: bvalue = <bint*>c_ev.u.g.control.value return (bvalue[0],), {} elif c_ev.u.g.control.type == cv.DVZ_GUI_CONTROL_BUTTON: bvalue = <bint*>c_ev.u.g.control.value return (bvalue[0],), {} # Key events. elif dt == cv.DVZ_EVENT_KEY_PRESS or dt == cv.DVZ_EVENT_KEY_RELEASE: key = _key_name(c_ev.u.k.key_code) modifiers = _get_modifiers(c_ev.u.k.modifiers) return (key, modifiers), {} # Mouse button events. elif dt == cv.DVZ_EVENT_MOUSE_PRESS or dt == cv.DVZ_EVENT_MOUSE_RELEASE: button = _button_name(c_ev.u.b.button) modifiers = _get_modifiers(c_ev.u.b.modifiers) return (button, modifiers), {} # Mouse button events. elif dt == cv.DVZ_EVENT_MOUSE_CLICK or dt == cv.DVZ_EVENT_MOUSE_DOUBLE_CLICK: x = c_ev.u.c.pos[0] y = c_ev.u.c.pos[1] button = _button_name(c_ev.u.c.button) modifiers = _get_modifiers(c_ev.u.c.modifiers) dbl = c_ev.u.c.double_click return (x, y), dict(button=button, modifiers=modifiers) #, double_click=dbl) # Mouse move event. elif dt == cv.DVZ_EVENT_MOUSE_MOVE: x = c_ev.u.m.pos[0] y = c_ev.u.m.pos[1] modifiers = _get_modifiers(c_ev.u.m.modifiers) return (x, y), dict(modifiers=modifiers) # Mouse wheel event. elif dt == cv.DVZ_EVENT_MOUSE_WHEEL: x = c_ev.u.w.pos[0] y = c_ev.u.w.pos[1] dx = c_ev.u.w.dir[0] dy = c_ev.u.w.dir[1] modifiers = _get_modifiers(c_ev.u.w.modifiers) return (x, y, dx, dy), dict(modifiers=modifiers) # Frame event. elif dt == cv.DVZ_EVENT_FRAME: idx = c_ev.u.f.idx return (idx,), {} return (), {} cdef _wrapped_callback(cv.DvzCanvas* c_canvas, cv.DvzEvent c_ev): """C callback function that wraps a Python callback function.""" # NOTE: this function may run in a background thread if using async callbacks # It should not acquire the GIL. cdef object tup if c_ev.user_data!= NULL: # The Python function and its arguments are wrapped in this Python object. tup = <object>c_ev.user_data # For each type of event, get the arguments to the function ev_args, ev_kwargs = _get_event_args(c_ev) # Recover the Python function and arguments. f, args = tup # This is the control type the callback was registered for. name = args[0] if args else None # NOTE: we only call the callback if the raised GUI event is for that control. dt = c_ev.type if dt == cv.DVZ_EVENT_GUI: if c_ev.u.g.control.name!= name: return # We run the registered Python function on the event arguments. try: f(*ev_args, **ev_kwargs) except Exception as e: print(traceback.format_exc()) cdef _add_event_callback( cv.DvzCanvas* c_canvas, cv.DvzEventType evtype, double param, f, args, cv.DvzEventMode mode=cv.DVZ_EVENT_MODE_SYNC): """Register a Python callback function using the Datoviz C API.""" # Create a tuple with the Python function, and the arguments. cdef void* ptr_to_obj tup = (f, args) # IMPORTANT: need to either keep a reference of this tuple object somewhere in the class, # or increase the ref, otherwise this tuple will be deleted by the time we call it in the # C callback function. Py_INCREF(tup) # Call the Datoviz C API to register the C-wrapped callback function. ptr_to_obj = <void*>tup cv.dvz_event_callback( c_canvas, evtype, param, mode, <cv.DvzEventCallback>_wrapped_callback, ptr_to_obj) # ------------------------------------------------------------------------------------------------- # Public functions # ------------------------------------------------------------------------------------------------- def colormap(np.ndarray[DOUBLE, ndim=1] values, vmin=None, vmax=None, cmap=None, alpha=None): """Apply a colormap to a 1D array of values.""" N = values.size if cmap in _COLORMAPS: cmap_ = _COLORMAPS[cmap] elif cmap in _CUSTOM_COLORMAPS: cmap_ = _CUSTOM_COLORMAPS[cmap] else: cmap_ = cv.DVZ_CMAP_VIRIDIS # TODO: ndarrays cdef np.ndarray out = np.zeros((N, 4), dtype=np.uint8) if vmin is None: vmin = values.min() if vmax is None: vmax = values.max() if vmin >= vmax: logger.warn("colormap vmin is larger than or equal to vmax") vmax = vmin + 1 cv.dvz_colormap_array(cmap_, N, <double*>&values.data[0], vmin, vmax, <cv.cvec4*>&out.data[0]) if alpha is not None: if not isinstance(alpha, np.ndarray): alpha = np.array(alpha) alpha = (alpha * 255).astype(np.uint8) out[:, 3] = alpha return out def colorpal(np.ndarray[INT, ndim=1] values, cpal=None, alpha=None): """Apply a colormap to a 1D array of values.""" N = values.size if cpal in _COLORMAPS: cpal_ = _COLORMAPS[cpal] elif cpal in _CUSTOM_COLORMAPS: cpal_ = _CUSTOM_COLORMAPS[cpal] else: cpal_ = cv.DVZ_CPAL256_GLASBEY # TODO: ndarrays cdef np.ndarray out = np.zeros((N, 4), dtype=np.uint8) cv.dvz_colorpal_array(cpal_, N, <cv.int32_t*>&values.data[0], <cv.cvec4*>&out.data[0]) if alpha is not None: if not isinstance(alpha, np.ndarray): alpha = np.array(alpha) alpha = (alpha * 255).astype(np.uint8) out[:, 3] = alpha return out def demo(): cv.dvz_demo_standalone() # ------------------------------------------------------------------------------------------------- # Util functions # ------------------------------------------------------------------------------------------------- def _validate_data(dt, nc, data): """Ensure a NumPy array has a given dtype and shape and is contiguous.""" data = data.astype(dt) if not data.flags['C_CONTIGUOUS']: data = np.ascontiguousarray(data)
Cython
if not hasattr(nc, '__len__'): nc = (nc,) nd = len(nc) # expected dimension of the data - 1 if nc[0] == 1 and data.ndim == 1: data = data.reshape((-1, 1)) if data.ndim < nd + 1: data = data[np.newaxis, :] assert data.ndim == nd + 1, f"Incorrect array dimension {data.shape}, nc={nc}" assert data.shape[1:] == nc, f"Incorrect array shape {data.shape} instead of {nc}" assert data.dtype == dt, f"Array dtype is {data.dtype} instead of {dt}" return data cdef _canvas_flags(show_fps=None, pick=None, high_dpi=None, offscreen=None): """Make the canvas flags from the Python keyword arguments to the canvas creation function.""" cdef int flags = 0 flags |= cv.DVZ_CANVAS_FLAGS_IMGUI if show_fps: flags |= cv.DVZ_CANVAS_FLAGS_FPS if pick: flags |= cv.DVZ_CANVAS_FLAGS_PICK if high_dpi: flags |= cv.DVZ_CANVAS_FLAGS_DPI_SCALE_200 if offscreen: flags |= cv.DVZ_CANVAS_FLAGS_OFFSCREEN return flags # ------------------------------------------------------------------------------------------------- # App # ------------------------------------------------------------------------------------------------- cdef class App: """Singleton object that gives access to the GPUs.""" cdef cv.DvzApp* _c_app _gpus = {} def __cinit__(self): """Create a Datoviz app.""" # TODO: selection of the backend self._c_app = cv.dvz_app(cv.DVZ_BACKEND_GLFW) if self._c_app is NULL: raise MemoryError() def __dealloc__(self): self.destroy() def destroy(self): """Destroy the app.""" if self._c_app is not NULL: # # Destroy all GPUs. # for gpu in self._gpus.values(): # gpu.destroy() # self._gpus.clear() cv.dvz_app_destroy(self._c_app) self._c_app = NULL def gpu(self, idx=None): """Get a GPU, identified by its index, or the "best" one by default.""" if idx in self._gpus: return self._gpus[idx] g = GPU() if idx is None: g.create_best(self._c_app) else: assert idx >= 0 g.create(self._c_app, idx) self._gpus[idx] = g return g def run( self, int n_frames=0, unicode screenshot=None, unicode video=None, bint offscreen=False): """Start the rendering loop.""" # Autorun struct. cdef cv.DvzAutorun autorun = [0, 0] if screenshot or video: logger.debug("Enabling autorun") autorun.enable = True autorun.n_frames = n_frames autorun.offscreen = offscreen if screenshot: ss = screenshot.encode('UTF-8') autorun.screenshot[:len(ss) + 1] = ss logger.debug(f"Autorun screenshot: {ss}") autorun.video[0] = 0 if video: sv = video.encode('UTF-8') autorun.video[:len(sv) + 1] = sv autorun.screenshot[0] = 0 logger.debug(f"Autorun video: {sv}") cv.dvz_autorun_setup(self._c_app, autorun) cv.dvz_app_run(self._c_app, n_frames) def next_frame(self): """Run a single frame for all canvases.""" return cv.dvz_app_run(self._c_app, 1) def _set_running(self, bint running): """Manually set whether the app is running or not.""" self._c_app.is_running = running def __repr__(self): return "<Datoviz App>" # ------------------------------------------------------------------------------------------------- # GPU # ------------------------------------------------------------------------------------------------- cdef class GPU: """The GPU object allows to create GPU objects and canvases.""" cdef cv.DvzApp* _c_app cdef cv.DvzGpu* _c_gpu cdef object _context # _canvases = [] cdef create(self, cv.DvzApp* c_app, int idx): """Create a GPU.""" assert c_app is not NULL self._c_app = c_app self._c_gpu = cv.dvz_gpu(self._c_app, idx); if self._c_gpu is NULL: raise MemoryError() cdef create_best(self, cv.DvzApp* c_app): """Create the best GPU found.""" assert c_app is not NULL self._c_app = c_app self._c_gpu = cv.dvz_gpu_best(self._c_app); if self._c_gpu is NULL: raise MemoryError() @property def name(self): return self._c_gpu.name def canvas( self, int width=DEFAULT_WIDTH, int height=DEFAULT_HEIGHT, bint show_fps=False, bint pick=False, bint high_dpi=False, bint offscreen=False, clear_color=None, ): """Create a new canvas.""" # Canvas flags. cdef int flags = 0 flags = _canvas_flags(show_fps=show_fps, pick=pick, high_dpi=high_dpi, offscreen=offscreen) # Create the canvas using the Datoviz C API. c_canvas = cv.dvz_canvas(self._c_gpu, width, height, flags) # Canvas clear color. if clear_color == 'white': cv.dvz_canvas_clear_color(c_canvas, 1, 1, 1) if c_canvas is NULL: raise MemoryError() # Create and return the Canvas Cython wrapper. c = Canvas() c.create(self, c_canvas) # self._canvases.append(c) return c def context(self): """Return the GPU context object, used to create GPU buffers and textures.""" if self._context is not None: return self._context c = Context() assert self._c_gpu is not NULL # If the context has not been created, it means we must create the GPU in offscreen mode. if self._c_gpu.context is NULL: logger.debug("Automatically creating a GPU context with no surface (offscreen only)") # Create the GPU without a surface. cv.dvz_gpu_default(self._c_gpu, NULL) # Create the context. cv.dvz_context(self._c_gpu) c.create(self._c_app, self._c_gpu, self._c_gpu.context) self._context = c return c def __repr__(self): return f"<GPU \"{self.name}\">" # ------------------------------------------------------------------------------------------------- # Context # ------------------------------------------------------------------------------------------------- cdef class Context: """A Context is attached to a GPU and allows to create GPU buffers and textures.""" cdef cv.DvzApp* _c_app cdef cv.DvzGpu* _c_gpu cdef cv.DvzContext* _c_context cdef create(self, cv.DvzApp* c_app, cv.DvzGpu* c_gpu, cv.DvzContext* c_context): assert c_app is not NULL assert c_gpu is not NULL assert c_context is not NULL self._c_app = c_app self._c_gpu = c_gpu self._c_context = c_context def texture( self, int height, int width=1, int depth=1, int ncomp=4, np.dtype dtype=None, int ndim=2): """Create a 1D, 2D, or 3D texture.""" dtype = np.dtype(dtype or np.uint8) tex = Texture() # Texture shape. assert width > 0 assert height > 0 assert depth > 0 if depth > 1: ndim = 3 cdef TEX_SHAPE shape # NOTE: shape is in Vulkan convention. shape[0] = width shape[1] = height shape[2] = depth # Create the texture. tex.create(self._c_context, ndim, ncomp, shape, dtype) logger.debug(f"Create a {str(tex)}") return tex def colormap(self, unicode name, np.ndarray[CHAR, ndim=2] colors): """Create a custom colormap""" assert colors.shape[1] == 4 color_count = colors.shape[0] assert color_count > 0 assert color_count <= 256 colors = colors.astype(np.uint8) if not colors.flags['C_CONTIGUOUS']: colors = np.ascontiguousarray(colors) # TODO: use constant CMAP_CUSTOM instead of hard-coded value cmap = 160 + len(_CUSTOM_COLORMAPS) _CUSTOM_COLORMAPS[name] = cmap cv.dvz_colormap_custom(cmap, color_count, <cv.cvec4*>&colors.data[0]) cv
Cython
.dvz_context_colormap(self._c_context) def __repr__(self): return f"<Context for GPU \"{self._c_gpu.name}\">" # ------------------------------------------------------------------------------------------------- # Texture # ------------------------------------------------------------------------------------------------- cdef class Texture: """A 1D, 2D, or 3D GPU texture.""" cdef cv.DvzContext* _c_context cdef cv.DvzTexture* _c_texture cdef TEX_SHAPE _c_shape # always 3 values: width, height, depth (WARNING, reversed in NumPy) cdef np.dtype dtype cdef int ndim # 1D, 2D, or 3D texture cdef int ncomp # 1-4 (eg 3 for RGB, 4 for RGBA) cdef cv.DvzSourceType _c_source_type cdef create(self, cv.DvzContext* c_context, int ndim, int ncomp, TEX_SHAPE shape, np.dtype dtype): """Create a texture.""" assert c_context is not NULL self._c_context = c_context assert 1 <= ndim <= 3 assert 1 <= ncomp <= 4 self.ndim = ndim self.ncomp = ncomp self._update_shape(shape) # Find the source type. assert ndim in _SOURCE_TYPES self._c_source_type = _SOURCE_TYPES[ndim] # Find the Vulkan format. cdef cv.VkFormat c_format self.dtype = dtype assert (dtype, ncomp) in _FORMATS c_format = _FORMATS[dtype, ncomp] # Create the Datoviz texture. self._c_texture = cv.dvz_ctx_texture(self._c_context, ndim, &shape[0], c_format) cdef _update_shape(self, TEX_SHAPE shape): # Store the shape. for i in range(self.ndim): self._c_shape[i] = shape[i] for i in range(self.ndim, 3): self._c_shape[i] = 1 @property def item_size(self): """Size, in bytes, of every value.""" return np.dtype(self.dtype).itemsize @property def size(self): """Total number of values in the texture (including the number of color components).""" return np.prod(self.shape) @property def shape(self): """Shape (NumPy convention: height, width, depth). Also, the last dimension is the number of color components.""" shape = [1, 1, 1] for i in range(3): shape[i] = self._c_shape[i] if self.ndim > 1: # NOTE: Vulkan considers textures as (width, height, depth) whereas NumPy # considers them as (height, width, depth), hence the need to transpose here. shape[0], shape[1] = shape[1], shape[0] return tuple(shape[:self.ndim]) + (self.ncomp,) def set_filter(self, name): """Change the filtering of the texture.""" cv.dvz_texture_filter(self._c_texture, cv.DVZ_FILTER_MIN, _TEXTURE_FILTERS[name]) cv.dvz_texture_filter(self._c_texture, cv.DVZ_FILTER_MAG, _TEXTURE_FILTERS[name]) def resize(self, w=1, h=1, d=1): cdef TEX_SHAPE shape shape[0] = h shape[1] = w shape[2] = d cv.dvz_texture_resize(self._c_texture, &shape[0]) self._update_shape(shape) def upload(self, np.ndarray arr): """Set the texture data from a NumPy array.""" assert arr.dtype == self.dtype for i in range(self.ndim): assert arr.shape[i] == self.shape[i] logger.debug(f"Upload NumPy array to {self}.") cv.dvz_upload_texture( self._c_context, self._c_texture, &DVZ_ZERO_OFFSET[0], &DVZ_ZERO_OFFSET[0], self.size * self.item_size, &arr.data[0]) def download(self): """Download the texture data to a NumPy array.""" cdef np.ndarray arr arr = np.empty(self.shape, dtype=self.dtype) logger.debug(f"Download {self}.") cv.dvz_download_texture( self._c_context, self._c_texture, &DVZ_ZERO_OFFSET[0], &DVZ_ZERO_OFFSET[0], self.size * self.item_size, &arr.data[0]) cv.dvz_process_transfers(self._c_context) return arr def __repr__(self): """The shape axes are in the following order: height, width, depth, ncomp.""" return f"<Texture {self.ndim}D {'x'.join(map(str, self.shape))} ({self.dtype})>" # ------------------------------------------------------------------------------------------------- # Canvas # ------------------------------------------------------------------------------------------------- cdef class Canvas: """A canvas.""" cdef cv.DvzCanvas* _c_canvas cdef object _gpu cdef bint _video_recording cdef object _scene cdef create(self, gpu, cv.DvzCanvas* c_canvas): """Create a canvas.""" self._c_canvas = c_canvas self._gpu = gpu self._scene = None def gpu(self): return self._gpu def scene(self, rows=1, cols=1): """Create a scene, which allows to use subplots, controllers, visuals, and so on.""" if self._scene is not None: logger.debug("reusing existing Scene object, discarding rows and cols") return self._scene else: logger.debug("creating new scene") s = Scene() s.create(self, self._c_canvas, rows, cols) self._scene = s return s def screenshot(self, unicode path): """Make a screenshot and save it to a PNG file.""" cdef char* _c_path = path cv.dvz_screenshot_file(self._c_canvas, _c_path); def video(self, unicode path, int fps=30, int bitrate=10000000): """Start a high-quality video recording.""" cdef char* _c_path = path cv.dvz_canvas_video(self._c_canvas, fps, bitrate, _c_path, False) self._video_recording = False def record(self): """Start or restart the video recording.""" self._video_recording = True cv.dvz_canvas_pause(self._c_canvas, self._video_recording) def pause(self): """Pause the video recording.""" self._video_recording = not self._video_recording cv.dvz_canvas_pause(self._c_canvas, self._video_recording) def stop(self): """Stop the video recording and save the video to disk.""" cv.dvz_canvas_stop(self._c_canvas) def pick(self, cv.uint32_t x, cv.uint32_t y): """If the canvas was created with picking support, get the color value at a given pixel.""" cdef cv.uvec2 xy cdef cv.ivec4 rgba xy[0] = x xy[1] = y cv.dvz_canvas_pick(self._c_canvas, xy, rgba) cdef cv.int32_t r, g, b, a r = rgba[0] g = rgba[1] b = rgba[2] a = rgba[3] return (r, g, b, a) def gui(self, unicode title): """Create a new GUI.""" c_gui = cv.dvz_gui(self._c_canvas, title, 0) gui = Gui() gui.create(self._c_canvas, c_gui) return gui def gui_demo(self): """Show the Dear ImGui demo.""" cv.dvz_imgui_demo(self._c_canvas) def close(self): if self._c_canvas is not NULL: logger.debug("Closing canvas") cv.dvz_canvas_destroy(self._c_canvas) # cv.dvz_canvas_to_close(self._c_canvas) # cv.dvz_app_run(self._c_canvas.app, 1) self._c_canvas = NULL def _connect(self, evtype_py, f, param=0, cv.DvzEventMode mode=cv.DVZ_EVENT_MODE_SYNC): # NOTE: only SYNC callbacks for now. cdef cv.DvzEventType evtype evtype = _EVENTS.get(evtype_py, 0) _add_event_callback(self._c_canvas, evtype, param, f, (), mode=mode) def connect(self, f): """Add an event callback function.""" assert f.__name__.startswith('on_') ev_name = f.__name__[3:] self._connect(ev_name, f) return f def click(self, float x, float y, button='left', modifiers=()): """Simulate a mouse click at a given position.""" cdef cv.vec2 pos cdef int mod cdef cv.DvzMouseButton c_button pos[0] = x pos[1] = y c_button
Cython
= _BUTTONS_INV.get(button, 0) mod = _c_modifiers(*modifiers) cv.dvz_event_mouse_click(self._c_canvas, pos, c_button, mod) # ------------------------------------------------------------------------------------------------- # Scene # ------------------------------------------------------------------------------------------------- cdef class Scene: """The Scene is attached to a canvas, and provides high-level scientific plotting facilities.""" cdef cv.DvzCanvas* _c_canvas cdef cv.DvzScene* _c_scene cdef cv.DvzGrid* _c_grid cdef object _canvas _panels = [] cdef create(self, canvas, cv.DvzCanvas* c_canvas, int rows, int cols): """Create the scene.""" self._canvas = canvas self._c_canvas = c_canvas self._c_scene = cv.dvz_scene(c_canvas, rows, cols) self._c_grid = &self._c_scene.grid def destroy(self): """Destroy the scene.""" if self._c_scene is not NULL: cv.dvz_scene_destroy(self._c_scene) self._c_scene = NULL def panel(self, int row=0, int col=0, controller='axes', transform=None, transpose=None, **kwargs): """Add a new panel with a controller.""" cdef int flags flags = 0 if controller == 'axes': if kwargs.pop('hide_minor_ticks', False): flags |= cv.DVZ_AXES_FLAGS_HIDE_MINOR if kwargs.pop('hide_grid', False): flags |= cv.DVZ_AXES_FLAGS_HIDE_GRID ctl = _CONTROLLERS.get(controller, cv.DVZ_CONTROLLER_NONE) trans = _TRANSPOSES.get(transpose, cv.DVZ_CDS_TRANSPOSE_NONE) transf = _TRANSFORMS.get(transform, cv.DVZ_TRANSFORM_CARTESIAN) c_panel = cv.dvz_scene_panel(self._c_scene, row, col, ctl, flags) if c_panel is NULL: raise MemoryError() c_panel.data_coords.transform = transf cv.dvz_panel_transpose(c_panel, trans) p = Panel() p.create(self._c_scene, c_panel) self._panels.append(p) return p def panel_at(self, x, y): """Find the panel at a given pixel position.""" cdef cv.vec2 pos pos[0] = x pos[1] = y c_panel = cv.dvz_panel_at(self._c_grid, pos) cdef Panel panel for p in self._panels: panel = p if panel._c_panel == c_panel: return panel # ------------------------------------------------------------------------------------------------- # Panel # ------------------------------------------------------------------------------------------------- cdef class Panel: """The Panel is a subplot in the Scene.""" cdef cv.DvzScene* _c_scene cdef cv.DvzPanel* _c_panel _visuals = [] cdef create(self, cv.DvzScene* c_scene, cv.DvzPanel* c_panel): """Create the panel.""" self._c_panel = c_panel self._c_scene = c_scene @property def row(self): """Get the panel's row index.""" return self._c_panel.row @property def col(self): """Get the panel's column index.""" return self._c_panel.col def visual(self, vtype, depth_test=None, transform='auto'): """Add a visual to the panel.""" visual_type = _VISUALS.get(vtype, 0) if not visual_type: raise ValueError("unknown visual type") flags = 0 if depth_test: flags |= cv.DVZ_GRAPHICS_FLAGS_DEPTH_TEST if transform is None: flags |= cv.DVZ_VISUAL_FLAGS_TRANSFORM_NONE # This keyword means that the panel box will NOT be recomputed every time the POS prop # changes elif transform == 'init': flags |= cv.DVZ_VISUAL_FLAGS_TRANSFORM_BOX_INIT c_visual = cv.dvz_scene_visual(self._c_panel, visual_type, flags) if c_visual is NULL: raise MemoryError() v = Visual() v.create(self._c_panel, c_visual, vtype) self._visuals.append(v) return v def size(self, axis, float value): cdef cv.DvzGridAxis c_axis if axis == 'x': c_axis = cv.DVZ_GRID_HORIZONTAL else: c_axis = cv.DVZ_GRID_VERTICAL cv.dvz_panel_size(self._c_panel, c_axis, value) def span(self, axis, int n): cdef cv.DvzGridAxis c_axis if axis == 'x': c_axis = cv.DVZ_GRID_HORIZONTAL else: c_axis = cv.DVZ_GRID_VERTICAL cv.dvz_panel_span(self._c_panel, c_axis, n) def pick(self, x, y, target_cds='data'): """Convert a position in pixels to the data coordinate system, or another coordinate system.""" cdef cv.dvec3 pos_in cdef cv.dvec3 pos_out pos_in[0] = x pos_in[1] = y pos_in[2] = 0 source = cv.DVZ_CDS_WINDOW target = _COORDINATE_SYSTEMS[target_cds] cv.dvz_transform(self._c_panel, source, pos_in, target, pos_out) return pos_out[0], pos_out[1] def get_lim(self): cdef cv.vec4 out cv.dvz_panel_lim_get(self._c_panel, out); return (out[0], out[1], out[2], out[3]) def set_lim(self, lim): cdef cv.vec4 clim clim[0] = lim[0] clim[1] = lim[1] clim[2] = lim[2] clim[3] = lim[3] cv.dvz_panel_lim_set(self._c_panel, clim); def link_to(self, Panel panel): cv.dvz_panel_link(&self._c_scene.grid, self._c_panel, panel._c_panel) def camera_pos(self, float x, float y, float z): cdef cv.vec3 pos pos[0] = x pos[1] = y pos[2] = z cv.dvz_camera_pos(self._c_panel, pos) def arcball_rotate(self, float u, float v, float w, float a): cdef cv.vec3 axis axis[0] = u axis[1] = v axis[2] = w cdef float angle angle = a cv.dvz_arcball_rotate(self._c_panel, angle, axis) # ------------------------------------------------------------------------------------------------- # Visual # ------------------------------------------------------------------------------------------------- cdef class Visual: """A visual is added to a given panel.""" cdef cv.DvzPanel* _c_panel cdef cv.DvzVisual* _c_visual cdef cv.DvzContext* _c_context cdef unicode vtype _textures = {} cdef create(self, cv.DvzPanel* c_panel, cv.DvzVisual* c_visual, unicode vtype): """Create a visual.""" self._c_panel = c_panel self._c_visual = c_visual self._c_context = c_visual.canvas.gpu.context self.vtype = vtype def data(self, name, np.ndarray value, idx=0, mode=None, drange=None): """Set the data of the visual associated to a given property.""" prop_type = _get_prop(name) c_prop = cv.dvz_prop_get(self._c_visual, prop_type, idx) dtype, nc = _DTYPES[c_prop.dtype] value = _validate_data(dtype, nc, value) N = value.shape[0] if mode == 'append': cv.dvz_visual_data_append(self._c_visual, prop_type, idx, N, &value.data[0]) elif mode == 'partial' and drange is not None: first_item, n_items = drange assert first_item >= 0, "first item should be positive" assert n_items > 0, "n_items should be strictly positive" cv.dvz_visual_data_partial( self._c_visual, prop_type, idx, first_item, n_items, N, &value.data[0]) else: cv.dvz_visual_data(self._c_visual, prop_type, idx, N, &value.data[0]) def append(self, *args, **kwargs): """Add some data to a visual prop's data.""" return self.data(*args, **kwargs, mode='append') def partial(self, *args, **kwargs): """Make a partial data update.""" return self.data(*args, **kwargs, mode='partial') def texture(self, Texture tex, idx=0): """Attach a texture to a visual.""" # Bind the texture with the visual for the specified source. cv.dvz_visual_texture( self._c_visual, tex._c_source_type, idx, tex._c_texture) def load
Cython
_obj(self, unicode path, compute_normals=False): """Load a mesh from an OBJ file.""" # TODO: move to subclass Mesh? cdef cv.DvzMesh mesh = cv.dvz_mesh_obj(path); if compute_normals: print("computing normals") cv.dvz_mesh_normals(&mesh) nv = mesh.vertices.item_count; ni = mesh.indices.item_count; cv.dvz_visual_data_source(self._c_visual, cv.DVZ_SOURCE_TYPE_VERTEX, 0, 0, nv, nv, mesh.vertices.data); cv.dvz_visual_data_source(self._c_visual, cv.DVZ_SOURCE_TYPE_INDEX, 0, 0, ni, ni, mesh.indices.data); # ------------------------------------------------------------------------------------------------- # GUI # ------------------------------------------------------------------------------------------------- cdef class GuiControl: """A GUI control.""" cdef cv.DvzGui* _c_gui cdef cv.DvzCanvas* _c_canvas cdef cv.DvzGuiControl* _c_control cdef unicode name cdef unicode ctype cdef bytes str_ascii cdef object _callback cdef create(self, cv.DvzGui* c_gui, cv.DvzGuiControl* c_control, unicode name, unicode ctype): """Create a GUI control.""" self._c_gui = c_gui self._c_canvas = c_gui.canvas assert self._c_canvas is not NULL self._c_control = c_control self.ctype = ctype self.name = name def get(self): """Get the current value.""" cdef void* ptr ptr = cv.dvz_gui_value(self._c_control) if self.ctype == 'input_float' or self.ctype =='slider_float': return (<float*>ptr)[0] def set(self, obj): """Set the control's value.""" cdef void* ptr cdef char* c_str ptr = cv.dvz_gui_value(self._c_control) if self.ctype == 'input_float' or self.ctype =='slider_float': (<float*>ptr)[0] = <float>float(obj) elif self.ctype =='slider_float2': (<float*>ptr)[0] = <float>float(obj[0]) (<float*>ptr)[1] = <float>float(obj[1]) elif self.ctype == 'label': self.str_ascii = obj.encode('ascii') if len(self.str_ascii) >= 1024: self.str_ascii = self.str_ascii[:1024] c_str = self.str_ascii # HACK: +1 for string null termination memcpy(ptr, c_str, len(self.str_ascii) + 1) else: raise NotImplementedError( f"Setting the value for a GUI control `{self.ctype}` is not implemented yet.") def connect(self, f): """Bind a callback function to the control.""" self._callback = f _add_event_callback(self._c_canvas, cv.DVZ_EVENT_GUI, 0, f, (self.name,)) return f def press(self): """For buttons only: simulate a press.""" if self.ctype == 'button' and self._callback: self._callback(False) @property def pos(self): """The x, y coordinates of the widget, in screen coordinates.""" cdef float x, y x = self._c_control.pos[0] y = self._c_control.pos[1] return (x, y) @property def size(self): """The width and height of the widget, in screen coordinates.""" cdef float w, h w = self._c_control.size[0] h = self._c_control.size[1] return (w, h) cdef class Gui: """A GUI dialog.""" cdef cv.DvzCanvas* _c_canvas cdef cv.DvzGui* _c_gui cdef create(self, cv.DvzCanvas* c_canvas, cv.DvzGui* c_gui): """Create a GUI.""" self._c_canvas = c_canvas self._c_gui = c_gui def control(self, unicode ctype, unicode name, **kwargs): """Add a GUI control.""" ctrl = _CONTROLS.get(ctype, 0) cdef char* c_name = name cdef cv.DvzGuiControl* c cdef cv.vec2 vec2_value if (ctype =='slider_float'): c_vmin = kwargs.get('vmin', 0) c_vmax = kwargs.get('vmax', 1) c_value = kwargs.get('value', (c_vmin + c_vmax) / 2.0) c = cv.dvz_gui_slider_float(self._c_gui, c_name, c_vmin, c_vmax, c_value) elif (ctype =='slider_float2'): c_vmin = kwargs.get('vmin', 0) c_vmax = kwargs.get('vmax', 1) c_value = kwargs.get('value', (c_vmin, c_vmax)) c_force = kwargs.get('force_increasing', False) vec2_value[0] = c_value[0] vec2_value[1] = c_value[1] c = cv.dvz_gui_slider_float2(self._c_gui, c_name, c_vmin, c_vmax, vec2_value, c_force) elif (ctype =='slider_int'): c_vmin = kwargs.get('vmin', 0) c_vmax = kwargs.get('vmax', 1) c_value = kwargs.get('value', c_vmin) c = cv.dvz_gui_slider_int(self._c_gui, c_name, c_vmin, c_vmax, c_value) elif (ctype == 'input_float'): c_step = kwargs.get('step',.1) c_step_fast = kwargs.get('step_fast', 1) c_value = kwargs.get('value', 0) c = cv.dvz_gui_input_float(self._c_gui, c_name, c_step, c_step_fast, c_value) elif (ctype == 'checkbox'): c_value = kwargs.get('value', 0) c = cv.dvz_gui_checkbox(self._c_gui, c_name, c_value) elif (ctype == 'button'): c = cv.dvz_gui_button(self._c_gui, c_name, 0) elif (ctype == 'label'): c_value = kwargs.get('value', "") c = cv.dvz_gui_label(self._c_gui, c_name, c_value) # Gui control object w = GuiControl() w.create(self._c_gui, c, name, ctype) return w <|end_of_text|># cython: profile=False cimport cython from libc.stdint cimport uint32_t cdef uint32_t *CRC_TABLE = [0x00000000L, 0xf26b8303L, 0xe13b70f7L, 0x1350f3f4L, 0xc79a971fL, 0x35f1141cL, 0x26a1e7e8L, 0xd4ca64ebL, 0x8ad958cfL, 0x78b2dbccL, 0x6be22838L, 0x9989ab3bL, 0x4d43cfd0L, 0xbf284cd3L, 0xac78bf27L, 0x5e133c24L, 0x105ec76fL, 0xe235446cL, 0xf165b798L, 0x030e349bL, 0xd7c45070L, 0x25afd373L, 0x36ff2087L, 0xc494a384L, 0x9a879fa0L, 0x68ec1ca3L, 0x7bbcef57L, 0x89d76c54L, 0x5d1d08bfL, 0xaf768bbcL, 0xbc267848L, 0x4e4dfb4bL, 0x20bd8edeL, 0xd2d60dddL, 0xc186fe29L, 0x33ed7d2aL, 0xe72719c1L, 0x154c9ac2L, 0x061c6936L, 0xf477ea35L, 0xaa64d611L, 0x580f5512L, 0x4b5fa6e6L, 0xb93425e5L, 0x6dfe410eL, 0x9f95c20dL, 0x8cc531f9L, 0x7eaeb2faL, 0x30e349b1L, 0xc288cab2L, 0xd1d83946L, 0x23b3ba45L, 0xf779deaeL, 0x05125dadL, 0x1642ae59L, 0xe429
Cython
2d5aL, 0xba3a117eL, 0x4851927dL, 0x5b016189L, 0xa96ae28aL, 0x7da08661L, 0x8fcb0562L, 0x9c9bf696L, 0x6ef07595L, 0x417b1dbcL, 0xb3109ebfL, 0xa0406d4bL, 0x522bee48L, 0x86e18aa3L, 0x748a09a0L, 0x67dafa54L, 0x95b17957L, 0xcba24573L, 0x39c9c670L, 0x2a993584L, 0xd8f2b687L, 0x0c38d26cL, 0xfe53516fL, 0xed03a29bL, 0x1f682198L, 0x5125dad3L, 0xa34e59d0L, 0xb01eaa24L, 0x42752927L, 0x96bf4dccL, 0x64d4cecfL, 0x77843d3bL, 0x85efbe38L, 0xdbfc821cL, 0x2997011fL, 0x3ac7f2ebL, 0xc8ac71e8L, 0x1c661503L, 0xee0d9600L, 0xfd5d65f4L, 0x0f36e6f7L, 0x61c69362L, 0x93ad1061L, 0x80fde395L, 0x72966096L, 0xa65c047dL, 0x5437877eL, 0x4767748aL, 0xb50cf789L, 0xeb1fcbadL, 0x197448aeL, 0x0a24bb5aL, 0xf84f3859L, 0x2c855cb2L, 0xdeeedfb1L, 0xcdbe2c45L, 0x3fd5af46L, 0x7198540dL, 0x83f3d70eL, 0x90a324faL, 0x62c8a7f9L, 0xb602c312L, 0x44694011L, 0x5739b3e5L, 0xa55230e6L, 0xfb410cc2L, 0x092a8fc1L, 0x1a7a7c35L, 0xe811ff36L, 0x3cdb9bddL, 0xceb018deL, 0xdde0eb2aL, 0x2f8b6829L, 0x82f63b78L, 0x709db87bL, 0x63cd4b8fL, 0x91a6c88cL, 0x456cac67L, 0xb7072f64L, 0xa457dc90L, 0x563c5f93L, 0x082f63b7L, 0xfa44e0b4L, 0xe9141340L, 0x1b7f9043L, 0xcfb5f4a8L, 0x3dde77abL, 0x2e8e845fL, 0xdce5075cL, 0x92a8fc17L, 0x60c37f14L, 0x73938ce0L, 0x81f80fe3L, 0x55326b08L, 0xa759e80bL, 0xb4091bffL, 0x466298fcL, 0x1871a4d8L, 0xea1a27dbL, 0xf94ad42fL, 0x0b21572cL, 0xdfeb33c7L, 0x2d80b0c4L, 0x3ed04330L, 0xccbbc033L, 0xa24bb5a6L, 0x502036a5L, 0x4370c551L, 0xb11b4652L, 0x65d122b9L, 0x97baa1baL, 0x84ea524eL, 0x7681d14dL, 0x2892ed69L, 0xdaf96e6aL, 0xc9a99d9eL, 0x3bc21e9dL, 0xef087a76L, 0x1d63f975L, 0x0e330a81L, 0xfc588982L, 0xb21572c9L, 0x407ef1caL, 0x532e023eL, 0xa145813dL, 0x758fe5d6L, 0x87e466d5L, 0x94b49521L, 0x66df1622L, 0x38cc2a06L, 0xcaa7a905L, 0xd9f75af1L, 0x2b9cd9f2L, 0xff56bd19L, 0x0d3d3e1aL, 0x1e6dcdeeL, 0xec064eedL, 0xc38d26c4L, 0x31e6a5c7L, 0x22b65633L, 0xd0ddd530L, 0x0417b1dbL, 0xf67c32d8L, 0xe52cc12cL, 0x1747422fL, 0x49547e0bL, 0xbb3ffd08L, 0xa86f0efcL, 0x5a048dffL, 0x8ecee914L, 0x7ca56a17L, 0x6ff599e3L, 0x9d9e1ae0L, 0xd3d3e1abL, 0x21b862a8L, 0x32e8915cL, 0xc083125fL, 0x144976b4L, 0xe622f5b7L, 0xf5720643L, 0x07198540L, 0x590ab964L, 0xab613a67L, 0xb831c993L, 0x4a5a4a90L, 0x9e902e7bL, 0x6cfbad78L, 0x7fab5e8cL, 0x8dc0dd8fL, 0xe330a81aL, 0x115b2b19L, 0x020bd8edL, 0xf0605beeL, 0x24aa3f05L, 0xd6c1bc06L, 0xc5914ff2L, 0x37faccf1L, 0x69e9f0d5L, 0x9b8273d6L, 0x88d28022L, 0x7ab90321L, 0xae7367caL, 0x5c18e4c9L, 0x4f48173dL, 0xbd23943eL, 0xf36e6f75L, 0x0105ec76L, 0x12551f82L, 0xe03e9c81L, 0x34f4f86aL, 0xc69f7b69L, 0xd5cf889dL, 0x27a40b9eL, 0x79b737baL, 0x8bdcb4b9L, 0x988c474dL, 0x6ae7c44eL, 0xbe2da0a5L, 0x4c4623a6L, 0x5f16d052L, 0xad7d5351L] # initial CRC value cdef uint32_t CRC_INIT = 0 cdef uint32_t _MASK = 0xFFFFFFFFL #cdef uint32_t crc_update(uint32_t crc, bytes data): # cdef char b # cdef int table_index # # crc = crc ^ _MASK # for b in data: # table_index = (crc ^ b) & 0xff # crc = (CRC_TABLE[table_index] ^ (
Cython
crc >> 8)) & _MASK # return crc ^ _MASK @cython.wraparound(False) @cython.boundscheck(False) cdef inline uint32_t crc_update(uint32_t crc, char *data, size_t n) nogil: cdef char b cdef int table_index cdef size_t i crc = crc ^ _MASK for i in range(n): b = data[i] table_index = (crc ^ b) & 0xff crc = (CRC_TABLE[table_index] ^ (crc >> 8)) & _MASK return crc ^ _MASK @cython.wraparound(False) @cython.boundscheck(False) cdef inline uint32_t crc_finalize(uint32_t crc) nogil: return crc & _MASK @cython.wraparound(False) @cython.boundscheck(False) cdef inline uint32_t crc32c(char *data, size_t n) nogil: return crc_finalize(crc_update(CRC_INIT, data, n)) @cython.wraparound(False) @cython.boundscheck(False) cpdef uint32_t masked_crc32c(bytes data): cdef uint32_t crc = crc32c(data, len(data)) return (((crc >> 15) | (crc << 17)) + 0xa282ead8) & 0xffffffff <|end_of_text|>cdef extern from "zoltan_types.h": # basic type used by all of Zoltan ctypedef unsigned int ZOLTAN_ID_TYPE # MPI data type cdef unsigned int ZOLTAN_ID_MPI_TYPE # pointer to the basic type ctypedef ZOLTAN_ID_TYPE* ZOLTAN_ID_PTR # /*****************************************************************************/ # /* # * Error codes for Zoltan library # * ZOLTAN_OK - no errors # * ZOLTAN_WARN - some warning occurred in Zoltan library; # * application should be able to continue running # * ZOLTAN_FATAL - a fatal error occurred # * ZOLTAN_MEMERR - memory allocation failed; with this error, it could be # * possible to try a different, more memory-friendly, # * algorithm. # */ # /*****************************************************************************/ cdef int ZOLTAN_OK cdef int ZOLTAN_WARN cdef int ZOLTAN_FATAL cdef int ZOLTAN_MEMERR # /*****************************************************************************/ # /* Hypergraph query function types # */ # /*****************************************************************************/ cdef int _ZOLTAN_COMPRESSED_EDGE cdef int _ZOLTAN_COMPRESSED_VERTEX <|end_of_text|>cdef extern from 'ql/math/interpolations/backwardflatinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass BackwardFlat: pass cdef extern from 'ql/math/interpolations/loginterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass LogLinear: pass cdef extern from 'ql/math/interpolations/linearinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass Linear: pass cdef extern from 'ql/math/interpolations/bilinearinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass Bilinear: pass cdef extern from 'ql/math/interpolations/bicubicsplineinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass Bicubic: pass cdef extern from 'ql/math/interpolations/sabrinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass SABRInterpolation: pass cdef extern from 'ql/math/interpolations/cubicinterpolation.hpp' namespace 'QuantLib' nogil: cdef cppclass Cubic: pass <|end_of_text|>print("hello extension") <|end_of_text|>cimport cython as ct from cython.parallel cimport prange cimport numpy as np import numpy as np from cython cimport parallel from libc cimport math as cmath import multiprocessing as mp cdef int nproc = mp.cpu_count() @ct.boundscheck(False) @ct.wraparound(False) def projectCluster( clusters, id, output, axis ): assert( len(clusters.shape) == 3 ) assert( len(output.shape) == 2) assert( clusters.shape[0] == clusters.shape[1] ) assert( clusters.shape[0] == clusters.shape[2] ) assert( clusters.shape[0] == output.shape[0] ) assert( clusters.shape[0] == output.shape[1] ) cdef np.ndarray[np.uint8_t, ndim=3] clustersC = clusters cdef int idC = id cdef np.ndarray[np.uint8_t, ndim=2] outputC = output cdef int N = clusters.shape[0] cdef int ix, iy, iz for ix in range(N): for iy in range(N): for iz in range(N): if ( clustersC[ix,iy,iz] == idC and axis==0 ): outputC[iy,iz] = outputC[iy,iz]+1 elif ( clustersC[ix,iy,iz] == idC and axis==1 ): outputC[ix,iz] = outputC[ix,iz]+1 elif ( clustersC[ix,iy,iz] == idC and axis==2 ): outputC[ix,iy] = outputC[ix,iy]+1 return outputC @ct.boundscheck(False) @ct.wraparound(False) def averageAzimuthalClusterWeightsAroundX( clusters, clusterID, output, mask ): assert( len(output.shape) == 2 ) assert( len(clusters.shape) == 3 ) assert( clusters.shape[0] == clusters.shape[1] ) assert( clusters.shape[0] == clusters.shape[2] ) assert( clusters.shape[0] == output.shape[0] ) assert( clusters.shape[0] == output.shape[1] ) cdef np.ndarray[np.float64_t, ndim=2] outputR = output cdef np.ndarray[np.uint8_t,ndim=3] clustersR = clusters cdef np.ndarray[np.uint8_t,ndim=3] maskC = mask cdef int N = clusters.shape[0] cdef int cID = clusterID cdef float qy, qz, qperp, weight cdef int qperpInt cdef center=N/2 for ix in range(N): for iy in range(N): for iz in range(N): if ( maskC[ix,iy,iz] == 0 ): continue if ( clustersR[ix,iy,iz] == cID ): qy = iy-N/2 qz = iz-N/2 qperp = cmath.sqrt(qy*qy+qz*qz) qperpInt = <int>qperp # Rounds to integer below if ( qperpInt < (N-1)/2 ): weight = qperp-qperpInt outputR[ix,center+qperpInt] = outputR[ix,center+qperpInt]+1.0-weight outputR[ix,center+qperpInt+1] = outputR[ix,center+qperpInt+1] + weight elif ( qperpInt < N/2 ): outputR[ix,center+qperpInt] = outputR[ix,center+qperpInt] + 1.0 return output @ct.boundscheck(False) @ct.wraparound(False) def azimuthalAverageX( data3D, output, mask ): assert( len(data3D.shape) == 3 ) assert( len(output.shape) == 2 ) assert( data3D.shape[0] == data3D.shape[1] ) assert( data3D.shape[0] == data3D.shape[2] ) assert( data3D.shape[0] == output.shape[0] ) assert( data3D.shape[0] == output.shape[1] ) cdef np.ndarray[np.float64_t,ndim=3] data3DC = data3D cdef np.ndarray[np.float64_t,ndim=2] outputC = output cdef np.ndarray[np.uint8_t,ndim=3] maskC = mask cdef int N = data3D.shape[0] cdef float qy, qz, qperp, weight cdef int qperpInt cdef int center = N/2 for ix in range(N): for iy in range(N): for iz in range(N): if ( maskC[ix,iz,iz] == 0 ): continue qy = iy-N/2 qz = iz-N/2 qperp = cmath.sqrt( qy*qy + qz*qz ) qperpInt = <int>qperp # Rounds to integer below if ( qperpInt < N-1 ): weight = qperp-qperpInt outputC
Cython
[ix,center+qperpInt] = outputC[ix,center+qperpInt] + data3DC[ix,iy,iz]*(1.0-weight) outputC[ix,center+qperpInt+1] = outputC[ix,center+qperpInt+1] + data3DC[ix,iy,iz]*weight elif ( qperpInt < N ): outputC[ix,center+qperpInt] = outputC[ix,center+qperpInt] + data3DC[ix,iy,iz] return output @ct.boundscheck(False) @ct.wraparound(False) def maskedSumOfSquares( reference, data, mask ): cdef np.ndarray[np.float64_t] ref = reference.ravel() cdef np.ndarray[np.float64_t] dataR = data.ravel() cdef np.ndarray[np.uint8_t] maskR = mask.ravel() cdef int N = data.size cdef int i cdef np.ndarray[np.float64_t] sumsq = np.zeros(nproc) for i in prange(N, nogil=True, num_threads=nproc): if ( maskR[i] == 1 ): sumsq[parallel.threadid()] = sumsq[parallel.threadid()] + cmath.pow( ref[i]-dataR[i], 2 ) return np.sum(sumsq) <|end_of_text|># distutils: language = c++ # # Copyright 2015-2020 CNRS-UM LIRMM, CNRS-AIST JRL # cimport mc_control.c_mc_control as c_mc_control cimport eigen.eigen as eigen cimport sva.c_sva as c_sva cimport sva.sva as sva cimport mc_observers.c_mc_observers as c_mc_observers cimport mc_observers.mc_observers as mc_observers cimport mc_rbdyn.c_mc_rbdyn as c_mc_rbdyn cimport mc_rbdyn.mc_rbdyn as mc_rbdyn cimport mc_solver.mc_solver as mc_solver cimport mc_tasks.mc_tasks as mc_tasks cimport mc_rtc.mc_rtc as mc_rtc cimport mc_rtc.gui.gui as mc_rtc_gui from cython.operator cimport preincrement as preinc from cython.operator cimport dereference as deref from libcpp.map cimport map as cppmap from libcpp.string cimport string from libcpp.vector cimport vector from libcpp cimport bool as cppbool import warnings def deprecated(): warnings.simplefilter('always', category=DeprecationWarning) warnings.warn("This call is deprecated", DeprecationWarning) warnings.simplefilter('ignore', category=DeprecationWarning) cdef class ControllerResetData(object): def __cinit__(self): pass property q: def __get__(self): return self.impl.q cdef ControllerResetData ControllerResetDataFromPtr(c_mc_control.ControllerResetData * p): cdef ControllerResetData ret = ControllerResetData() ret.impl = p return ret cdef class Contact(object): def __ctor__(self, r1, r2, r1Surface, r2Surface, friction = mc_rbdyn.Contact.defaultFriction, eigen.Vector6d dof = None): if isinstance(r1, unicode): r1 = r1.encode(u'ascii') if isinstance(r1Surface, unicode): r1Surface = r1Surface.encode(u'ascii') if isinstance(r2, unicode): r2 = r2.encode(u'ascii') if isinstance(r2Surface, unicode): r2Surface = r2Surface.encode(u'ascii') if dof is None: self.impl = c_mc_control.Contact(r1, r2, r1Surface, r2Surface, friction) else: self.impl = c_mc_control.Contact(r1, r2, r1Surface, r2Surface, friction, dof.impl) def __cinit__(self, *args): if len(args) > 0: self.__ctor__(*args) property r1: def __get__(self): if self.impl.r1.has_value(): return self.impl.r1.value() else: return None def __set__(self, r1): if isinstance(r1, unicode): r1 = r1.encode(u'ascii') self.impl.r1 = <string>(r1) property r1Surface: def __get__(self): return self.impl.r1Surface def __set__(self, r1Surface): if isinstance(r1Surface, unicode): r1Surface = r1Surface.encode(u'ascii') self.impl.r1Surface = r1Surface property r2: def __get__(self): if self.impl.r2.has_value(): return self.impl.r2.value() else: return None def __set__(self, r2): if isinstance(r2, unicode): r2 = r2.encode(u'ascii') self.impl.r2 = <string>(r2) property r2Surface: def __get__(self): return self.impl.r2Surface def __set__(self, r2Surface): if isinstance(r2Surface, unicode): r2Surface = r2Surface.encode(u'ascii') self.impl.r2Surface = r2Surface property friction: def __get__(self): return self.impl.friction def __set__(self, friction): self.impl.friction = friction property dof: def __get__(self): return eigen.Vector6dFromC(self.impl.dof) def __set__(self, dof): if isinstance(dof, eigen.Vector6d): self.impl.dof = (<eigen.Vector6d>dof).impl else: self.dof = eigen.Vector6d(dof) cdef Contact ContactFromC(const c_mc_control.Contact & c): cdef Contact ret = Contact() ret.impl = c return ret cdef class MCController(object): def __cinit__(self): pass def run(self): return self.base.run() def reset(self, ControllerResetData data): self.base.reset(deref(data.impl)) def env(self): return mc_rbdyn.RobotFromC(self.base.env()) def robots(self): return mc_rbdyn.RobotsFromRef(self.base.robots()) def supported_robots(self): supported = [] self.base.supported_robots(supported) return supported def config(self): return mc_rtc.ConfigurationFromRef(self.base.config()) def logger(self): return mc_rtc.LoggerFromRef(self.base.logger()) def gui(self): return mc_rtc_gui.StateBuilderFromShPtr(self.base.gui()) property timeStep: def __get__(self): return self.base.timeStep property contactConstraint: def __get__(self): return mc_solver.ContactConstraintFromPtr(self.base.contactConstraint.get()) property dynamicsConstraint: def __get__(self): return mc_solver.DynamicsConstraintFromPtr(self.base.dynamicsConstraint.get()) property kinematicsConstraint: def __get__(self): return mc_solver.KinematicsConstraintFromPtr(self.base.kinematicsConstraint.get()) property selfCollisionConstraint: def __get__(self): return mc_solver.CollisionsConstraintFromPtr(self.base.selfCollisionConstraint.get()) property postureTask: def __get__(self): return mc_tasks.PostureTaskFromPtr(self.base.postureTask.get()) property qpsolver: def __get__(self): return mc_solver.QPSolverFromRef(self.base.solver()) def hasObserverPipeline(self, name): if isinstance(name, unicode): name = name.encode(u'ascii') return self.base.hasObserverPipeline(name) def observerPipeline(self, name = None): if isinstance(name, unicode): name = name.encode(u'ascii') if name is None: return mc_observers.ObserverPipelineFromRef(self.base.observerPipeline()) else: return mc_observers.ObserverPipelineFromRef(self.base.observerPipeline(name)) def observerPipelines(self): it = self.base.observerPipelines().begin() end = self.base.observerPipelines().end() ret = [] while it!= end: ret.append(mc_observers.ObserverPipelineFromRef(deref(it))) preinc(it) return ret def addCollisions(self, r1, r2, collisions): assert(all([isinstance(col, mc_rbdyn.Collision) for col in collisions])) cdef vector[c_mc_rbdyn.Collision] cols if isinstance(r1, unicode): r1 = r1.encode(u'ascii') if isinstance(r2, unicode): r2 = r2.encode(u'ascii') for col in collisions: cols.push_back((<mc_rbdyn.Collision>col).impl) self.base.addCollisions(r1, r2, cols) def removeCollisions(self, r1, r2, collisions = None): cdef vector[c_mc_rbdyn.Collision] cols if isinstance(r1, unicode): r1 = r1.encode(u'ascii') if isinstance(r2, unicode): r2 = r2.encode(u'ascii') if collisions is None: self.base.removeCollisions(r1, r2) else: for col in collisions:
Cython
cols.push_back((<mc_rbdyn.Collision>col).impl) self.base.removeCollisions(r1, r2, cols) def hasRobot(self, name): if isinstance(name, unicode): name = name.encode(u'ascii') return self.base.hasRobot(name) def robot(self, name = None): if isinstance(name, unicode): name = name.encode(u'ascii') if name is None: return mc_rbdyn.RobotFromC(self.base.robot()) else: return mc_rbdyn.RobotFromC(self.base.robot(name)) def addContact(self, c, *args): if isinstance(c, Contact): assert len(args) == 0, "addContact takes either an mc_control.Contact object or arguments for its construction" self.base.addContact((<Contact>c).impl) else: self.addContact(Contact(c, *args)) def removeContact(self, c, *args): if isinstance(c, Contact): assert len(args) == 0, "removeContact takes either an mc_control.Contact object or arguments for its construction" self.base.removeContact((<Contact>c).impl) else: self.removeContact(Contact(c, *args)) def contacts(self): cdef c_mc_control.ContactSet cs = self.base.contacts() return [ContactFromC(c) for c in cs] def hasContact(self, Contact c): self.base.hasContact(c.impl) cdef MCController MCControllerFromPtr(c_mc_control.MCController * p): cdef MCController ret = MCController() ret.base = p return ret cdef class PythonRWCallback(object): def __cinit__(self, succ, out): self.impl.success = succ self.impl.out = out property success: def __get__(self): return self.impl.success def __set__(self, value): self.impl.success = value property out: def __get__(self): return self.impl.out def __set__(self, value): self.impl.out = value cdef cppbool python_to_run_callback(void * f) except+ with gil: return (<object>f).run_callback() cdef void python_to_reset_callback(const c_mc_control.ControllerResetData & crd, void * f) except+ with gil: (<object>f).reset_callback(ControllerResetDataFromPtr(&(c_mc_control.const_cast_crd(crd)))) cdef c_sva.PTransformd python_af_callback(callback, const c_mc_rbdyn.Robot & robot) except+ with gil: cdef mc_rbdyn.Robot r = mc_rbdyn.RobotFromC(robot) cdef sva.PTransformd af = callback(r) return deref(af.impl) cdef class MCPythonController(MCController): AF_CALLBACKS = [] def __dealloc__(self): del self.impl self.impl = self.base = NULL def __cinit__(self, robot_modules, double dt): cdef mc_rbdyn.RobotModuleVector rmv = mc_rbdyn.RobotModuleVector(robot_modules) self.impl = self.base = new c_mc_control.MCPythonController(rmv.v, dt) try: self.run_callback c_mc_control.set_run_callback(deref(self.impl), &python_to_run_callback, <void*>(self)) except AttributeError: raise TypeError("You need to implement a run_callback method in your object") try: self.reset_callback c_mc_control.set_reset_callback(deref(self.impl), &python_to_reset_callback, <void*>(self)) except AttributeError: pass def addAnchorFrameCallback(self, name, callback): if isinstance(name, unicode): name = name.encode(u'ascii') MCPythonController.AF_CALLBACKS.append(callback) c_mc_control.add_anchor_frame_callback(deref(self.impl), <string>(name), &python_af_callback, callback) def removeAnchorFrameCallback(self, name): if isinstance(name, unicode): name = name.encode(u'ascii') c_mc_control.remove_anchor_frame_callback(deref(self.impl), name) cdef class MCGlobalController(object): def __dealloc__(self): del self.impl self.impl = NULL def __cinit_simple__(self): self.impl = new c_mc_control.MCGlobalController() def __cinit_conf__(self, conf): if isinstance(conf, unicode): conf = conf.encode(u'ascii') self.impl = new c_mc_control.MCGlobalController(conf) def __cinit_full__(self, conf, mc_rbdyn.RobotModule rm): if isinstance(conf, unicode): conf = conf.encode(u'ascii') self.impl = new c_mc_control.MCGlobalController(conf, rm.impl) def __cinit__(self, *args): if len(args) == 0: self.__cinit_simple__() elif len(args) == 1: self.__cinit_conf__(args[0]) elif len(args) == 2: self.__cinit_full__(args[0], args[1]) else: raise TypeError("Wrong arguments passed to MCGlobalController ctor") def init(self, q, pos = None): cdef c_mc_control.array7d p = c_mc_control.array7d() if pos is None: self.impl.init(q) else: assert(len(pos) == 7) for i,pi in enumerate(pos): p[i] = pos[i] self.impl.init(q, p) def setSensorPosition(self, eigen.Vector3d p): self.impl.setSensorPosition(p.impl) def setSensorOrientation(self, eigen.Quaterniond q): self.impl.setSensorOrientation(q.impl) def setSensorLinearVelocity(self, eigen.Vector3d lv): self.impl.setSensorLinearVelocity(lv.impl) def setSensorAngularVelocity(self, eigen.Vector3d av): self.impl.setSensorAngularVelocity(av.impl) def setSensorAcceleration(self, eigen.Vector3d a): deprecated() self.impl.setSensorLinearAcceleration(a.impl) def setSensorLinearAcceleration(self, eigen.Vector3d a): self.impl.setSensorLinearAcceleration(a.impl) def setEncoderValues(self, q): self.impl.setEncoderValues(q) def setEncoderVelocities(self, alpha): self.impl.setEncoderVelocities(alpha) def setJointTorques(self, tau): self.impl.setJointTorques(tau) def setWrenches(self, wrenchesIn): cdef cppmap[string, c_sva.ForceVecd] wrenches = cppmap[string, c_sva.ForceVecd]() for sensor,w in wrenchesIn.iteritems(): if not isinstance(w, sva.ForceVecd): w = sva.ForceVecd(w) wrenches[sensor] = deref((<sva.ForceVecd>(w)).impl) self.impl.setWrenches(wrenches) def run(self): return self.impl.run() def timestep(self): return self.impl.timestep() def controller(self): return MCControllerFromPtr(&(self.impl.controller())) def ref_joint_order(self): return self.impl.ref_joint_order() def robot(self): return mc_rbdyn.RobotFromC(self.impl.robot()) property running: def __get__(self): return self.impl.running def __set__(self, b): self.impl.running = b cdef class ElementId(object): def __cinit__(self, category, name): if isinstance(name, unicode): name = name.encode(u'ascii') self.impl = c_mc_control.ElementId([s.encode(u'ascii') if isinstance(s, unicode) else s for s in category], name) property category: def __get__(self): return self.impl.category property name: def __get__(self): return self.impl.name cdef class ControllerClient(object): def __cinit__(self, sub_conn_uri, push_conn_uri, timeout = 0.0): if isinstance(sub_conn_uri, unicode): sub_conn_uri = sub_conn_uri.encode(u'ascii') if isinstance(push_conn_uri, unicode): push_conn_uri = push_conn_uri.encode(u'ascii') self.impl = new c_mc_control.ControllerClient(sub_conn_uri, push_conn_uri, timeout) def send_request(self, element_id, data = None): if data is None: deref(self.impl).send_request((<ElementId>element_id).impl) else: deref(self.impl).send_request((<ElementId>element_id).impl, deref((<mc_rtc.Configuration>data).impl)) <|end_of_text|>cimport pyftw from pyftw cimport ftw, nftw, stat, FTW, dev_t, ino_t, mode_t, nlink_t, uid_t, gid_t, off_t, blksize_t, blkcnt_t, time_t __doc__ = "Primitive ftw.h wrapper" # Flags cpdef enum: FTW_F = 0 FTW_D = 1 FTW_DNR = 2 FTW_NS = 3 FTW_SL = 4 FTW_DP = 5 FTW_SLN = 6 cpdef enum: FTW_PHYS = 1 FTW_MOUNT = 2 FTW_CHDIR = 4 FTW_DEPTH
Cython
= 8 FTW_ACTIONRETVAL = 16 # Service wrappers cdef class Stat: cdef public dev_t st_dev cdef public ino_t st_ino cdef public mode_t st_mode cdef public nlink_t st_nlink cdef public uid_t st_uid cdef public gid_t st_gid cdef public dev_t st_rdev cdef public off_t st_size cdef public blksize_t st_blksize cdef public blkcnt_t st_blocks cdef public time_t st_atim cdef public time_t st_mtim cdef public time_t st_ctim cdef fill(self, const stat *sb): self.st_dev = sb.st_dev self.st_ino = sb.st_ino self.st_mode = sb.st_mode self.st_nlink = sb.st_nlink self.st_uid = sb.st_uid self.st_gid = sb.st_gid self.st_rdev = sb.st_rdev self.st_size = sb.st_size self.st_blksize = sb.st_blksize self.st_blocks = sb.st_blocks self.st_atim = sb.st_atime self.st_mtim = sb.st_mtime self.st_ctim = sb.st_ctime cdef class Nftw: cdef public int base cdef public int level cdef fill(self, FTW *ftwbuf): self.base = ftwbuf.base self.level = ftwbuf.level # Globals for python callbacks cdef ftw_fn cdef nftw_fn # C callbacks cdef int ftw_callback(const char *fpath, const stat *sb, int typeflag): return ftw_fn(fpath, Stat().fill(sb), typeflag) cdef int nftw_callback(const char *fpath, const stat *sb, int typeflag, FTW *ftwbuf): return nftw_fn(fpath, Stat().fill(sb), typeflag, Nftw().fill(ftwbuf)) # Wrappers cpdef int py_ftw(const char *dirpath, fn, int nopenfd): '''py_ftw(dirpath, fn, nopenfd)\n\nPerform file tree walk (ftw wrapper)''' global ftw_fn ftw_fn = fn return ftw(dirpath, ftw_callback, nopenfd) cpdef int py_nftw(const char *dirpath, fn, int nopenfd, int flags): '''py_nftw(dirpath, fn, nopenfd, flags)\n\nPerform file tree walk (nftw wrapper)''' global nftw_fn nftw_fn = fn return nftw(dirpath, nftw_callback, nopenfd, flags) <|end_of_text|>import numpy as _N from cython.parallel import prange, parallel from libc.math cimport sin, fabs def calc_using_prange(int rep, int TR, int N): cdef int tr, i, r cdef double tot outs = _N.empty(rep*TR) cdef double[::1] v_outs = outs cdef double *p_outs = &v_outs[0] with nogil: for r from 0 <= r < rep: for tr in prange(TR): p_outs[r*TR+tr] = FFdv_new(N, tr, r) return outs def calc_using_range(int rep, int TR, int N): cdef int tr, i, r cdef double tot outs = _N.empty(rep*TR) cdef double[::1] v_outs = outs cdef double *p_outs = &v_outs[0] with nogil: for r from 0 <= r < rep: for tr in range(TR): p_outs[r*TR+tr] = FFdv_new(N, tr, r) return outs cdef double FFdv_new(int _Np1, int r, int tr) nogil: cdef double tot = 1 cdef int n1, n2, n3 for n1 from 1 <= n1 < _Np1: for n2 from 1 <= n2 < _Np1: tot += fabs(sin((n1 + n2) / 1000) + tr + r + n3) * 0.001 return tot """ def doit(int rep, int TR, int N): cdef int tr, i, r with nogil: for r from 0 <= r < rep: for tr in prange(TR): FFdv_new(N) cdef void FFdv_new(int _Np1) nogil: cdef double tot = 1 cdef int n1, n2, n3 for n1 from 1 <= n1 < _Np1: for n2 from 1 <= n2 < _Np1: for n3 from 1 <= n3 < _Np1: tot += (n1 + n2) / 100 + 200 + n3 """ <|end_of_text|>#cython: language_level=3 import os from pysam import AlignmentFile __all__ = ['Bri', 'bench'] """ Expose bare minimum from jts/bri headers """ cdef extern from "bri_index.h": struct bam_read_idx_record: size_t file_offset struct bam_read_idx: bam_read_idx_record* records bam_read_idx*bam_read_idx_load(const char* input_bam) void bam_read_idx_build(const char* input_bam) void bam_read_idx_destroy(bam_read_idx* bri) cdef extern from "bri_get.h": void bam_read_idx_get_range(const bam_read_idx* bri, const char* readname, bam_read_idx_record** start, bam_read_idx_record** end) cdef extern from "bri_benchmark.h": int bam_read_idx_benchmark_main(int argc, char** argv) def bench(input_bam): bam_read_idx_benchmark_main(2, ['benchmark', input_bam.encode('utf-8')]) cdef class Bri: """ Wrapper class for Jared's bri, supports creating and reading.bri index and extracting reads using pysam Attributes: index (bam_read_idx*): Bri index instance input_bam_path (bytes): Path to bam file input_bri_path (bytes): Path to bri file hts (pysam.AlignmentFile): Bam file instance """ cdef: bam_read_idx*index object hts bytes input_bam_path bytes input_bri_path def __init__(self, input_bam): """ Args: input_bam (str): Path to.bam file """ self.input_bam_path = input_bam.encode('utf-8') self.input_bri_path = (input_bam + '.bri').encode('utf-8') if not os.path.exists(self.input_bam_path): raise IOError("Bam file does not exist") def create(self): """ Create bri index for bam file by calling bam_read_idx_build and bam_read_idx_save. Index is immediately destroyed, call load() after this to recycle this object. """ bam_read_idx_build(self.input_bam_path) # noinspection PyAttributeOutsideInit def load(self): """ Load the index from.bri file """ if not os.path.exists(self.input_bri_path): # Avoid exit() calls in bri_index.c raise IOError("Bri file does not exist") self.index = bam_read_idx_load(self.input_bam_path) # load.bri index self.hts = AlignmentFile(self.input_bam_path, 'rb') # load.bam file def get(self, read_name): """ Get reads for read_name from the bam file using.bri index Args: read_name (str): Reads to search for Yields: pysam.AlignedSegment: found reads """ if not self.index: raise ValueError('Bri index is not loaded, call load() function first') cdef: bam_read_idx_record*start bam_read_idx_record*end bam_read_idx_get_range(self.index, read_name.encode('utf-8'), &start, &end) hts_iter = iter(self.hts) while start!= end: self.hts.seek(start.file_offset) read = next(hts_iter) yield read start += 1 def __dealloc__(self): """ Proper cleanup """ if self.index: bam_read_idx_destroy(self.index) if self.hts: self.hts.close() <|end_of_text|># This is an example of a pure Python function def getForce(): # Write your code here, then delete the "pass" statement below pass<|end_of_text|># cython: profile=True #cimport cython #cimport dilap.core.tools as dpr cimport dilap.geometry.tools as gtl from dilap.geometry.vec3 cimport vec3 from libc.math cimport sqrt from libc.math c
Cython
import sqrt from libc.math cimport cos from libc.math cimport sin from libc.math cimport tan from libc.math cimport acos from libc.math cimport asin from libc.math cimport hypot cimport numpy import numpy stuff = 'hi' __doc__ = '''dilapidator\'s implementation of a quaternion in R3''' # dilapidators implementation of a quaternion in R3 cdef class quat: ########################################################################### ### python object overrides ############################################### ########################################################################### def __str__(self):return 'quat:'+str(tuple(self)) def __repr__(self):return 'quat:'+str(tuple(self)) def __iter__(self):yield self.w;yield self.x;yield self.y;yield self.z def __mul__(self,o):return self.mul(o) def __add__(self,o):return self.add(o) def __sub__(self,o):return self.sub(o) def __is_equal(self,o):return self.isnear(o) def __richcmp__(x,y,op): if op == 2:return x.__is_equal(y) else:assert False ########################################################################### ########################################################################### ### c methods ############################################################# ########################################################################### def __cinit__(self,float w,float x,float y,float z): self.w = w self.x = x self.y = y self.z = z # given an angle a and axis v, modify to represent # a rotation by a around v and return self # NOTE: negative a still maps to positive self.w cdef quat av_c(self,float a,vec3 v): cdef float a2 = a/2.0 cdef float sa = sin(a2) cdef float vm = v.mag_c() self.w = cos(a2) self.x = v.x*sa/vm self.y = v.y*sa/vm self.z = v.z*sa/vm return self # modify to represent a rotation # between two vectors and return self cdef quat uu_c(self,vec3 x,vec3 y): cdef float a = x.ang_c(y) cdef vec3 v if a == 0.0:self.w = 1;self.x = 0;self.y = 0;self.z = 0 else: v = x.crs_c(y) return self.av_c(a,v) # set self to the quaternion that rotates v to (0,0,1) wrt the xy plane cdef quat toxy_c(self,vec3 v): if v.isnear(vec3(0,0,-1)): self.w = 0;self.x = 1;self.y = 0;self.z = 0 elif not v.isnear(vec3(0,0,1)):self.uu_c(v,vec3(0,0,1)) else:self.av_c(0,vec3(0,0,1)) return self # return an independent copy of this quaternion cdef quat cp_c(self): cdef quat n = quat(self.w,self.x,self.y,self.z) return n # return an independent flipped copy of this quaternion cdef quat cpf_c(self): cdef quat n = quat(-self.w,self.x,self.y,self.z) return n # is quat o within a very small neighborhood of self cdef bint isnear_c(self,quat o): cdef float dw = (self.w-o.w) if dw*dw > gtl.epsilonsq_c:return 0 cdef float dx = (self.x-o.x) if dx*dx > gtl.epsilonsq_c:return 0 cdef float dy = (self.y-o.y) if dy*dy > gtl.epsilonsq_c:return 0 cdef float dz = (self.z-o.z) if dz*dz > gtl.epsilonsq_c:return 0 return 1 # return the squared magintude of self cdef float mag2_c(self): cdef float w2 = self.w*self.w cdef float x2 = self.x*self.x cdef float y2 = self.y*self.y cdef float z2 = self.z*self.z cdef float m2 = w2 + x2 + y2 + z2 return m2 # return the magintude of self cdef float mag_c(self): return sqrt(self.mag2_c()) # normalize and return self cdef quat nrm_c(self): cdef float m = self.mag_c() if m == 0.0:return self else:return self.uscl_c(1.0/m) # flip the direction of and return self cdef quat flp_c(self): self.w *= -1.0 return self # multiply each component by a scalar of and return self cdef quat uscl_c(self,float s): self.w *= s self.x *= s self.y *= s self.z *= s return self # conjugate and return self cdef quat cnj_c(self): self.x *= -1.0 self.y *= -1.0 self.z *= -1.0 return self # compute the inverse of self and return cdef quat inv_c(self): cdef m = self.mag2_c() cdef quat n = self.cp_c().cnj_c().uscl_c(1/m) return n # given quat o, return self + o cdef quat add_c(self,quat o): cdef quat n = quat(self.w+o.w,self.x+o.x,self.y+o.y,self.z+o.z) return n # given quat o, return self - o cdef quat sub_c(self,quat o): cdef quat n = quat(self.w-o.w,self.x-o.x,self.y-o.y,self.z-o.z) return n # given quat o, rotate self so that self represents # a rotation by self and then q (q * self) cdef quat mul_c(self,quat o): cdef float nw,nx,ny,nz if gtl.isnear_c(self.w,0):nw,nx,ny,nz = o.__iter__() elif gtl.isnear_c(o.w,0):nw,nx,ny,nz = self.__iter__() else: nw = o.w*self.w - o.x*self.x - o.y*self.y - o.z*self.z nx = o.w*self.x + o.x*self.w + o.y*self.z - o.z*self.y ny = o.w*self.y - o.x*self.z + o.y*self.w + o.z*self.x nz = o.w*self.z + o.x*self.y - o.y*self.x + o.z*self.w cdef quat n = quat(nw,nx,ny,nz) return n # given quat o, rotate self so that self represents # a rotation by self and then q (q * self) cdef quat rot_c(self,quat o): cdef quat qres = self.mul_c(o) self.w,self.x,self.y,self.z = qres.__iter__() return self # rotate a set of vec3 points by self cdef quat rotps_c(self,ps): cdef vec3 p cdef int px cdef int pcnt = len(ps) for px in range(pcnt): p = ps[px] p.rot_c(self) return self # return the dot product of self and quat o cdef float dot_c(self,quat o): return self.w*o.w + self.x*o.x + self.y*o.y + self.z*o.z # spherically linearly interpolate between # self and quat o proportionally to ds cdef quat slerp_c(self,quat o,float ds): cdef float hcosth = self.dot_c(o) # will need to flip result direction if hcosth < 0???? if gtl.isnear_c(abs(hcosth),1.0):return self.cp_c() cdef float hth = acos(hcosth) cdef float hsinth = sqrt(1.0 - hcosth*hcosth) cdef float nw,nx,ny,nz,a,b if gtl.isnear_c(hsinth,0): nw = (self.w*0.5 + o.w*0.5) nx = (self.x*0.5 + o.x*0.5) ny = (self.y*0.5 + o.y*0.5) nz = (self.z*0.5 + o.z*0.5) else: a = sin((1-ds)*hth)/hsinth b = sin(( ds)*hth)/hsinth nw = (self.w*a + o.w*b) nx = (self.x*a + o.x*b) ny = (self.y*a + o.y*b) nz = (self.z*a + o.z*b)
Cython
cdef quat n = quat(nw,nx,ny,nz) return n ########################################################################### ########################################################################### ### python wrappers for c methods ######################################### ########################################################################### # given an angle a and axis v, modify to represent # a rotation by a around v and return self cpdef quat av(self,float a,vec3 v): '''modify to represent a rotation about a vector by an angle''' return self.av_c(a,v) # modify to represent a rotation # between two vectors and return self cpdef quat uu(self,vec3 x,vec3 y): '''modify to represent a rotation from one vector to another''' return self.uu_c(x,y) # set self to the quaternion that rotates v to (0,0,1) wrt the xy plane cpdef quat toxy(self,vec3 v): '''set self to the quaternion that rotates v to (0,0,1) wrt the xy plane''' return self.toxy_c(v) # return an independent copy of this quaternion cpdef quat cp(self): '''create an independent copy of this quaternion''' return self.cp_c() # return an independent flipped copy of this quaternion cpdef quat cpf(self): '''create an independent flipped copy of this quaternion''' return self.cpf_c() # is quat o within a very small neighborhood of self cpdef bint isnear(self,quat o): '''determine if a point is numerically close to another''' return self.isnear_c(o) # return the squared magintude of self cpdef float mag2(self): '''compute the squared magnitude of this quaternion''' return self.mag2_c() # return the magintude of self cpdef float mag(self): '''compute the magnitude of this quaternion''' return self.mag_c() # normalize and return self cpdef quat nrm(self): '''normalize this quaternion''' return self.nrm_c() # flip the direction of and return self cpdef quat flp(self): '''flip the direction of rotation represented by this quaternion''' return self.flp_c() # multiply each component by a scalar of and return self cpdef quat uscl(self,float s): '''multiply components of this point by a scalar''' return self.uscl_c(s) # conjugate and return self cpdef quat cnj(self): '''conjugate this quaternion''' return self.cnj_c() # compute the inverse of self and return cpdef quat inv(self): '''compute the inverse of this quaternion''' return self.inv_c() # given quat o, return self + o cpdef quat add(self,quat o): '''compute the addition of this quaternion and another''' return self.add_c(o) # given quat o, return self - o cpdef quat sub(self,quat o): '''compute the subtraction of this quaternion and another''' return self.sub_c(o) # given quat o, rotate self so that self represents # a rotation by self and then q (q * self) cpdef quat mul(self,quat o): '''rotate this quaternion by another quaternion''' return self.mul_c(o) # given quat o, rotate self so that self represents # a rotation by self and then q (q * self) cpdef quat rot(self,quat o): '''rotate this quaternion by another quaternion''' return self.rot_c(o) # rotate a set of vec3 points by self cpdef quat rotps(self,ps): '''rotate a set of vec3 points this quaternion''' return self.rotps_c(ps) # return the dot product of self and quat o cpdef float dot(self,quat o): '''compute the dot product of this quaternion and another''' return self.dot_c(o) # spherically linearly interpolate between # self and quat o proportionally to ds cpdef quat slerp(self,quat o,float ds): '''create a new quat interpolated between this quat and another''' return self.slerp_c(o,ds) ########################################################################### <|end_of_text|>import numpy as np cimport numpy as np assert sizeof(float) == sizeof(np.float32_t) cdef extern from "kernel/manager.hh": cdef cppclass C_distMatrix "distMatrix": C_distMatrix(np.float32_t*, np.float32_t*, np.float32_t*, int, int, int) void compute() void compute_sharedMem() cdef class distMatrix: cdef C_distMatrix* g def __cinit__(self, \ np.ndarray[ndim=1, dtype=np.float32_t] A, \ np.ndarray[ndim=1, dtype=np.float32_t] B, \ np.ndarray[ndim=1, dtype=np.float32_t] C, \ int x1, int x2, int dim): self.g = new C_distMatrix(&A[0], &B[0], &C[0], x1, x2, dim) def compute(self): self.g.compute() def compute_sharedMem(self): self.g.compute_sharedMem()<|end_of_text|>from CBARX cimport * from DataContainer cimport * cdef class CBARX2(CBARX): cpdef BuildElementMatrix(self,DataContainer dc) cpdef BuildInternalForceVector(self, DataContainer dc)<|end_of_text|>cdef extern from "stdlib.h": cpdef long random() nogil cpdef void srandom(unsigned int) nogil cpdef const long RAND_MAX cdef double randdbl() nogil: cdef double r r = random() r = r/RAND_MAX return r cpdef double calcpi(const int samples): """serially calculate Pi using Cython library functions""" cdef int inside, i cdef double x, y inside = 0 srandom(0) for i in range(samples): x = randdbl() y = randdbl() if (x*x)+(y*y) < 1: inside += 1 return (4.0 * inside)/samples <|end_of_text|>from mpfmc.core.audio.sdl2 cimport * from mpfmc.core.audio.gstreamer cimport * from mpfmc.core.audio.sound_file cimport * from mpfmc.core.audio.track cimport * from mpfmc.core.audio.notification_message cimport * # --------------------------------------------------------------------------- # Sound Loop Track types # --------------------------------------------------------------------------- cdef enum: do_not_stop_loop = 0xFFFFFFFF cdef enum LayerStatus: layer_stopped = 0 layer_queued = 1 layer_playing = 2 layer_fading_in = 3 layer_fading_out = 4 ctypedef struct SoundLoopLayerSettings: LayerStatus status SoundSample *sound Uint8 volume long sound_loop_set_id Uint64 sound_id Uint32 fade_in_steps Uint32 fade_out_steps Uint32 fade_steps_remaining bint looping Uint8 marker_count GArray *markers cdef enum SoundLoopSetPlayerStatus: # Enumeration of the possible sound loop set player status values. player_idle = 0 player_delayed = 1 player_fading_in = 2 player_fading_out = 3 player_playing = 4 ctypedef struct SoundLoopSetPlayer: SoundLoopSetPlayerStatus status Uint32 length SoundLoopLayerSettings master_sound_layer GSList *layers # An array of SoundLoopLayerSettings objects Uint32 sample_pos Uint32 stop_loop_samples_remaining Uint32 start_delay_samples_remaining float tempo ctypedef struct TrackSoundLoopState: # State variables for TrackSoundLoop tracks GSList *players SoundLoopSetPlayer *current # --------------------------------------------------------------------------- # TrackSoundLoop class # --------------------------------------------------------------------------- cdef class TrackSoundLoop(Track): # Track state needs to be stored in a C struct in order for them to be accessible in # the SDL callback functions without the GIL (for performance reasons). # The TrackSoundLoopState struct is allocated during construction and freed during # destruction. cdef TrackSoundLoopState *type_state cdef long _sound_loop_set_counter cdef dict _active_sound_loop_sets cdef process_notification_message(self, NotificationMessageContainer *notification_message) cdef _apply_layer_settings(self, SoundLoopLayerSettings *layer, dict layer_settings) cdef _initialize_player(self, SoundLoopSetPlayer *player) cdef _delete_player(self, SoundLoopSetPlayer *player) cdef _delete_player_layers(self, SoundLoopSetPlayer *player) cdef _cancel_all_delayed_players(self) cdef _fade_out_all_players(self, Uint32 fade_steps) cdef inline Uint32 _fix_sample_frame_pos(self, Uint32 sample_pos, Uint8 bytes_per_sample, int channels) cdef inline Uint32 _round_sample_pos_up_to_interval(self, Uint32 sample_pos, Uint32 interval, int bytes_per_sample_frame) @staticmethod cdef void mix_playing_sounds(TrackState *track, Uint32 buffer_length, AudioCallbackData *callback_data) nogil cdef SoundLoopLayerSettings *_create_sound_loop_layer_settings() nogil <|end_of_text|>from cython.operator cimport
Cython
dereference as deref from libc.stdlib cimport free from libcpp cimport bool from hltypes cimport Array, String cimport XAL import os cdef char* XAL_AS_ANDROID = "Android" cdef char* XAL_AS_DIRECTSOUND = "DirectSound" cdef char* XAL_AS_OPENAL = "OpenAL" cdef char* XAL_AS_SDL = "SDL" cdef char* XAL_AS_AVFOUNDATION = "AVFoundation" cdef char* XAL_AS_COREAUDIO = "CoreAudio" cdef char* XAL_AS_DISABLED = "Disabled" cdef char* XAL_AS_DEFAULT = "" cdef XAL.BufferMode FULL = XAL.FULL cdef XAL.BufferMode LAZY = XAL.LAZY cdef XAL.BufferMode MANAGED = XAL.MANAGED cdef XAL.BufferMode ON_DEMAND = XAL.ON_DEMAND cdef XAL.BufferMode STREAMED = XAL.STREAMED cdef XAL.SourceMode DISK = XAL.DISK cdef XAL.SourceMode RAM = XAL.RAM cdef XAL.Format FLAC = XAL.FLAC cdef XAL.Format M4A = XAL.M4A cdef XAL.Format OGG = XAL.OGG cdef XAL.Format SPX = XAL.SPX cdef XAL.Format WAV = XAL.WAV cdef XAL.Format UNKNOWN = XAL.UNKNOWN cdef extern from *: ctypedef char* const_char_ptr "const char*" ctypedef unsigned char* const_unsigned_char_ptr "const unsigned char*" ctypedef String& chstr "chstr" ctypedef String hstr "hstr" ctypedef Array harray "harray" # cdef str LOG_PATH = "" # cdef bool LOG_ENABLED = False # cpdef SetLogPath(str path): # ''' # Sets the path where XAL should create a log file. # the path should not include the file # PyXAL will try to create a folder at the path if the path doesn't exist and will save it's log in that folder as a file named XAL.log # @param path: string path to the folder where the log should be made # @return: returns True or False if the path was set # ''' # global LOG_PATH # cdef str blank = "" # cdef bint result = False # if not LOG_PATH == blank and not os.path.exists(path) or not os.path.isdir(path): # try: # os.makedirs(path) # except StandardError: # return result # LOG_PATH = path # result = True # return result # cpdef EnableLogging(bool state = True, str path = ""): # ''' # sets the logging state of PyXAL by default it is off # @param state: bool True or False if XAL should be logging data default is True so calling # PyXAL.EnableLogging will turn logging on (by default PyXAL does not log) # @param path: string path to the folder where PyXAL should create the log # it is an empty string by default so that should mean the log will be made in the # current working directory. calling PyXAL.EnableLogging will set the path to an empty string if the paramater is not included # @return: returns True or False if the path was set # ''' # global LOG_ENABLED # LOG_ENABLED = state # cdef bint result = False # result = SetLogPath(path) # return result # cdef void Log(chstr logMessage): # global LOG_PATH # global LOG_ENABLED # if not LOG_ENABLED: # return # cdef const_char_ptr message # cdef const_char_ptr line_end = "\n" # message = logMessage.c_str() # pymessage = message + line_end # if os.path.exists(LOG_PATH): # try: # path = os.path.join(LOG_PATH, "XAL.log") # file = open(path, "ab") # file.write(pymessage) # file.close() # except StandardError: # pass # XAL.setLogFunction(Log) Mgr = None cdef hstr Py_to_Hstr (string): py_byte_string = string.encode('UTF-8') cdef char* c_str = py_byte_string cdef hstr hstring = hstr(c_str) return hstring cdef Hstr_to_Py (hstr string): cdef const_char_ptr c_str = string.c_str() py_byte_string = c_str pystring = py_byte_string.decode('UTF-8') return pystring cdef class PyAudioManager: ''' A wrapper for the C++ xal::AudioManager class. it is currently not used ''' cdef XAL.AudioManager *_pointer cdef bool destroyed def __init__(self): ''' this is a wapper class for a C++ class. it should not be initialied outside of the PyXAL module as proper set up would be impossible. as such calling the __init__ method will raise a Runtime Error ''' raise RuntimeError("PyAudioManager Can not be initialized from python") cdef class SoundWrapper: ''' A wrapper class for the C++ xal::Sound class. it is returned by the XALManager.createSound and PyPlayer.getSound methods ''' cdef XAL.Sound *_pointer cdef bool destroyed def __init__(self): ''' this is a wapper class for a C++ class. it should not be initialied outside of the PyXAL module as proper set up would be impossible. as such calling the __init__ method will raise a Runtime Error ''' raise RuntimeError("PySound Can not be initialized from python") def _destroy(self): if self.isXALInitialized() and not self.destroyed : XAL.mgr.destroySound(self._pointer) self.destroyed = True def __dealloc__(self): if (XAL.mgr!= NULL) and (not self.destroyed): XAL.mgr.destroySound(self._pointer) self.destroyed = True def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def getName(self): ''' @return: returns the string name of the sound. it is normal the full path of teh sound file with out the file extention ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getName() name = Hstr_to_Py(hl_name) return name def getFilename(self): ''' @return: returns a string containing the file name the sound was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getFilename() name = Hstr_to_Py(hl_name) return name def getRealFilename(self): ''' @return: returns a string with the full path to the file the string was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getRealFilename() name = Hstr_to_Py(hl_name) return name def getSize(self): ''' @return: int the size of the sound data in bits not bytes ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int size = self._pointer.getSize() return size def getChannels(self): ''' @return: int number of channels the sound has. 1 for mono or 2 for stereo ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int channels = self._pointer.getChannels() return channels def getSamplingRate(self): ''' @return: int the sampeling rate for the sound in samples per second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int rate = self._pointer.getSamplingRate() return rate def getBitsPerSample(self): ''' @return: int the bits per sample of data in the sound. usualy 8, 16, or 24, possibly 32 not sure ''' if not self.isXALInitialized():
Cython
raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int rate = self._pointer.getBitsPerSample() return rate def getDuration(self): ''' @return: float duration of the sound in seconds. it is a floating point number to acound for fractions of a second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef float duration = self._pointer.getDuration() return duration def getFormat(self): ''' @return: int the intrnal designation of the sound format. coresponds to a file type but as of now there is no way to tell for certin which is which as the nubers will change depending on what formats are currently suported by XAL ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int format = <int>self._pointer.getFormat() return format def isStreamed(self): ''' @return: bool is the sound being streamed from it's file to the player? or is it comleatly loaded into memory. should always return false in PyXAL as PyXAL uses full decoding mode ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef bint streamed = self._pointer.isStreamed() return streamed def readPcmData(self): ''' read the pcm data of the sound and return it the format of said data can be determined from the size, chanels, bits per sample and sampleling rate of the sound @return: a 2 tuple of (number of bits read, string of bytes read) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef unsigned char* pcm_data cdef int pcm_size cdef char* c_data data = "" try: pcm_size = self._pointer.readPcmData(&pcm_data) if pcm_size > 0: c_data = <char*>pcm_data data = c_data[:pcm_size] finally: free(pcm_data) pcm_data = NULL return (pcm_size, data) cdef class PlayerWrapper: ''' a wraper for the C++ class xal::Player. it is retuned by the XALManager.createPlayer method ''' cdef XAL.Player *_pointer cdef bool destroyed def __init__(self): ''' this is a wapper class for a C++ class. it should not be initialied outside of the PyXAL module as proper set up would be impossible. as such calling the __init__ method will raise a Runtime Error ''' raise RuntimeError("PyPlayer Can not be initialized from python") def _destroy(self): if self.isXALInitialized() and not self.destroyed: XAL.mgr.destroyPlayer(self._pointer) self.destroyed = True def __dealloc__(self): if (XAL.mgr!= NULL) and (not self.destroyed): XAL.mgr.destroyPlayer(self._pointer) self.destroyed = True def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def getGain(self): ''' @return: float the current gain of the player (also knows as volume) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef float gain = self._pointer.getGain() return gain def setGain(self, float value): ''' set the gain of the player (also knows as volume) @param value: float the value of the volume to set 1.0 is normal 2.0 is twice as loud 0.5 is half volume ect. ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._pointer.setGain(value) def getPitch(self): ''' @return: float the current pitch of the player ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef float offset = self._pointer.getPitch() return offset def setPitch(self, float value): ''' set the current pitch of the player @param value: float the value of the pitch to set to set 1.0 is normal 2.0 is a 200% shift 0.5 is a 50% shift ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._pointer.setPitch(value) def getName(self): ''' @return: returns the string name of the sound. it is normal the full path of teh sound file with out the file extention ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getName() name = Hstr_to_Py(hl_name) return name def getFilename(self): ''' @return: returns a string containing the file name the sound was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getFilename() name = Hstr_to_Py(hl_name) return name def getRealFilename(self): ''' @return: returns a string with the full path to the file the string was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef hstr hl_name = self._pointer.getRealFilename() name = Hstr_to_Py(hl_name) return name def getDuration(self): ''' @return: float duration of the sound in seconds. it is a floating point number to acound for fractions of a second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef float duration = self._pointer.getDuration() return duration def getSize(self): ''' @return: int the size of the sound data in bits not bytes ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef int size = self._pointer.getSize() return size def getTimePosition(self): ''' @return: float the time position in seconds ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef float size = self._pointer.getTimePosition() return size def getSamplePosition(self): ''' @return: unsigned int the position in the buffer ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") cdef unsigned int size = self._pointer.getSamplePosition() return size def isPlaying(self): ''' @return: bool True of the sound is playing ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isPlaying() def isPaused(self): ''' @return: bool True if the sound is paused ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isPaused() def isFading(self): ''' @return: bool True if the sound is fading in or out ''' if not self.isXALInitialized(): raise RuntimeError
Cython
("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isFading() def isFadingIn(self): ''' @return: bool True if the sound is fading in ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isFadingIn() def isFadingOut(self): ''' @return: bool True if teh sound is fading out ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isFadingOut() def isLooping(self): ''' @return: bool True of the sound is looping ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._pointer.isLooping() def play(self, float fadeTime = 0.0, bool looping = False): ''' start the sound playing at it's current offset, the offset starts at 0.0 when teh sound is first loaded @param fadeTime: float the time in seconds for the sound to fade in (0.0 by default) @param looping: bool should the sound loop (False by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._pointer.play(fadeTime, looping) def stop(self, float fadeTime = 0.0): ''' stop the sound playing and rest set it's offset to 0.0 @param fadeTime: float the time in seconds for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._pointer.stop(fadeTime) def pause(self, float fadeTime = 0.0): ''' stop the sound playing keeping the current offset of the sound @param fadeTime: float the time in seconds for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._pointer.pause(fadeTime) class PySound(object): ''' a interface for the wrapper of the xal::Sound class ''' CATEGORY_STR = "default" _wrapper = None destroyed = False def __init__(self, filename): ''' this creates a sound object from a file name ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") path = os.path.split(filename)[0] cdef hstr file_str = Py_to_Hstr(filename) cdef hstr path_str = Py_to_Hstr(path) cdef hstr category = Py_to_Hstr(self.CATEGORY_STR) cdef XAL.Sound* sound sound = XAL.mgr.createSound(file_str, category, path_str) if sound == NULL: raise RuntimeError("XAL Failed to load file %s" % filename) cdef SoundWrapper wrapper = SoundWrapper.__new__(SoundWrapper) wrapper._pointer = sound wrapper.destroyed = False self._wrapper = wrapper def _destroy(self): if self.isXALInitialized() and not self.destroyed: self._wrapper._destroy() self.destroyed = True def __del__(self): if self.isXALInitialized(): self._destroy() del self._wrapper def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def getName(self): ''' @return: returns the string name of the sound. it is normal the full path of teh sound file with out the file extention ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getName() def getFilename(self): ''' @return: returns a string containing the file name the sound was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getFilename() def getRealFilename(self): ''' @return: returns a string with the full path to the file the string was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getRealFilename() def getSize(self): ''' @return: int the size of the sound data in bits not bytes ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getSize() def getChannels(self): ''' @return: int number of channels the sound has. 1 for mono or 2 for stereo ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getChannels() def getSamplingRate(self): ''' @return: int the sampeling rate for the sound in samples per second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getSamplingRate() def getBitsPerSample(self): ''' @return: int the bits per sample of data in the sound. usualy 8, 16, or 24, possibly 32 not sure ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getBitsPerSample() def getDuration(self): ''' @return: float duration of the sound in seconds. it is a floating point number to acound for fractions of a second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getDuration() def getFormat(self): ''' @return: int the intrnal designation of the sound format. coresponds to a file type but as of now there is no way to tell for certin which is which as the nubers will change depending on what formats are currently suported by XAL ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getFormat() def isStreamed(self): ''' @return: bool is the sound being streamed from it's file to the player? or is it comleatly loaded into memory. should always return false in PyXAL as PyXAL uses full decoding mode ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isStreamed() def readPcmData(self): ''' read the raw data of the sound and return it the format of said data can be determined from the size, chanels, bits per sample and sampleling rate of the sound @return: a 2 tuple of (number of bits read, string of bytes read) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.readPcmData() class PyPlayer(object): ''' a interface for the C++ wrapper ''' _wrapper = None _sound = None destroyed = False def __init__(self, sound): ''' a PyPlayer object created by bassing a PySound to the __init__ method ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if not isinstance(sound, PySound
Cython
): raise TypeError("Expected argument 1 to be of type PySound got %s" % type(sound)) sound_name = sound.getName() cdef hstr hl_name = Py_to_Hstr(sound_name) cdef XAL.Player* player player = XAL.mgr.createPlayer(hl_name) if player == NULL: raise RuntimeError("XAL Failed to create a player for %s" % sound_name) cdef PlayerWrapper wrapper = PlayerWrapper.__new__(PlayerWrapper) wrapper._pointer = player wrapper.destroyed = False self._wrapper = wrapper self._sound = sound def _destroy(self): if self.isXALInitialized() and not self.destroyed: self._wrapper._destroy() self.destroyed = True def __del__(self): global Mgr if not self.destroyed: if Mgr is not None: if hasattr(Mgr, "_players"): if Mgr._players.has_key(self.getName()): if self in Mgr._player[self.getName()]: Mgr.players[self.getName()].remove(self) if self.isXALInitialized(): self._destroy() del self._wrapper del self._sound def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def getGain(self): ''' @return: float the current gain of the player (also knows as volume) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getGain() def setGain(self, float value): ''' set the gain of the player (also knows as volume) @param value: float the value of the volume to set 1.0 is normal 2.0 is twice as loud 0.5 is half volume ect. ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._wrapper.setGain(value) def getPitch(self): ''' @return: float the current pitch of the player ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getPitch() def setPitch(self, float value): ''' set the current pitch of the player @param value: float the value of the pitch to set to set 1.0 is normal 2.0 is a 200% shift 0.5 is a 50% shift ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._wrapper.setPitch(value) def getSound(self): ''' return a PySound class wrapper for the sound object of the player ''' return self._sound def getName(self): ''' @return: returns the string name of the sound. it is normal the full path of teh sound file with out the file extention ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getName() def getFilename(self): ''' @return: returns a string containing the file name the sound was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getFilename() def getRealFilename(self): ''' @return: returns a string with the full path to the file the string was loaded from ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getRealFilename() def getDuration(self): ''' @return: float duration of the sound in seconds. it is a floating point number to acound for fractions of a second ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getDuration() def getSize(self): ''' @return: int the size of the sound data in bits not bytes ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getSize() def getTimePosition(self): ''' @return: float the time position in seconds ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getTimePosition() def getSamplePosition(self): ''' @return: unsigned int the position in the buffer ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.getSamplePosition() def isPlaying(self): ''' @return: bool True of the sound is playing ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isPlaying() def isPaused(self): ''' @return: bool True if the sound is paused ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isPaused() def isFading(self): ''' @return: bool True if the sound is fading in or out ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isFading() def isFadingIn(self): ''' @return: bool True if the sound is fading in ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isFadingIn() def isFadingOut(self): ''' @return: bool True if teh sound is fading out ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isFadingOut() def isLooping(self): ''' @return: bool True of the sound is looping ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") return self._wrapper.isLooping() def play(self, float fadeTime = 0.0, bool looping = False): ''' start the sound playing at it's current offset, the offset starts at 0.0 when teh sound is first loaded @param fadeTime: float the time in seconds for the sound to fade in (0.0 by default) @param looping: bool should the sound loop (False by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._wrapper.play(fadeTime, looping) def stop(self, float fadeTime = 0.0): ''' stop the sound playing and rest set it's offset to 0.0 @param fadeTime: float the time in seconds for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed") self._wrapper.stop(fadeTime) def pause(self, float fadeTime = 0.0): ''' stop the sound playing keeping the current offset of the sound @param fadeTime: float the time in seconds for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self.destroyed: raise RuntimeError("the C++ interface for this object has been destroyed")
Cython
self._wrapper.pause(fadeTime) cdef class XALManagerWrapper(object): ''' a wrapper for the xal::mgr object which is a xal::AudioManager. in other words this is the main interface to XAL you SHOLD NOT create an instance of the class yourself. call PyXAL.Init to set up XAL. an instance of this class will be made avalable at PyXAL.Mgr ''' cdef bint destroyed, inited cdef XAL.Category *_category cdef char* CATEGORY_STR def __init__(self, char* systemname, int backendId, bint threaded = False, float updateTime = 0.01, char* deviceName = ""): ''' sets up the interface and initializes XAL you SHOULD NOT BE CREATING THIS CLASS YOUR SELF call PyXAL.Init and use the object created at PyXAL.Mgr if PyXAL.Mgr is None call PyXAL.Destroy and then PyXAL.Init to set up the interface again @param systemname: string name of the back end system to use @param backendId: int window handle of the calling aplication @param threaded: bool should the system use a threaded interface? (False by defaut) @param updateTime: float how offten should XAL update (0.01 by default) @param deviceName: string arbatrary device name ("" by default) ''' global Mgr if Mgr is not None: raise RuntimeError("Only one XALManager interface allowed at a time, use the one at PyXAL.Mgr") self.CATEGORY_STR = "default" cdef hstr name = hstr(systemname) cdef hstr dname = hstr(deviceName) self._destroyXAL() XAL.init(name, <void*>backendId, threaded, updateTime, dname) self.inited = True self.destroyed = False self.SetupXAL() def __dealloc__(self): if XAL.mgr!= NULL: fade = 0.0 XAL.mgr.stopAll(fade) XAL.destroy() def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def SetupXAL(self): ''' set up XAL and create the default sound catagory ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr category = hstr(self.CATEGORY_STR) self._category = XAL.mgr.createCategory(category, FULL, DISK) def _destroyXAL(self): if XAL.mgr!= NULL: fade = 0.0 XAL.mgr.stopAll(fade) XAL.destroy() class XALManager(object): ''' a wrapper for the xal::mgr object which is a xal::AudioManager. in other words this is the main interface to XAL you SHOLD NOT create an instance of the class yourself. call PyXAL.Init to set up XAL. an instance of this class will be made avalable at PyXAL.Mgr ''' destroyed = False inited = False CATEGORY_STR = "default" _players = {} _wrapper = None def __init__(self, int backendId, bint threaded = False): ''' sets up the interface and initializes XAL you SHOULD NOT BE CREATING THIS CLASS YOUR SELF call PyXAL.Init and use the object created at PyXAL.Mgr if PyXAL.Mgr is None call PyXAL.Destroy and then PyXAL.Init to set up the interface again @param backendId: int window handle of the calling aplication @param threaded: bool should the system use a threaded interface? (False by defaut) ''' global Mgr if Mgr is not None: raise RuntimeError("Only one XALManager interface allowed at a time, use the one at PyXAL.Mgr") cdef XALManagerWrapper wrapper = XALManagerWrapper(XAL_AS_DEFAULT, backendId, threaded) self._wrapper = wrapper self._players = {} def isXALInitialized(self): ''' returns true if the C++ side of the interface to XAL exists ''' if XAL.mgr!= NULL: return True else: return False def __del__(self): ''' make sure XAL is destroyed if the interface is destroyed ''' del self._players del self._wrapper def clear(self): ''' clear the XAL interface and reset it to be like it was freshly initialized all current sounds and players become invalid ''' self._players = {} if self.isXALInitialized(): fade = 0.0 XAL.mgr.stopAll(fade) XAL.mgr.clear() def createSound(self, filename): ''' create a sound object raises a runtime error if the sound fails to load so be sure to put this call in a try except block @param filename: string full path to a sound file to load @return: a PySound wraper to the sound object ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") pysound = PySound(filename) return pysound def createPlayer(self, sound): ''' create a player from a sound object raises a runtime error if XAL fails to create a player so be sure to put this call in a try except block @param sound: a PySound wrapper to a sound object @return: a PyPlayer wraper to the player object ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if not isinstance(sound, PySound): raise TypeError("Expected argument 1 to be of type PySound got %s" % type(sound)) sound_name = sound.getName() if not self._players.has_key(sound_name): self._players[sound_name] = [] pyplayer = PyPlayer(sound) self._players[sound_name].append(pyplayer) return pyplayer def destroyPlayer(self, player): ''' destroy a player object destroyes the C++ interface. the object is unusable after this @param pyplayer: the PyPlayer wrapper for the player to destory ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if not isinstance(player, PyPlayer): raise TypeError("Expected argument 1 to be of type PyPlayer got %s" % type(player)) name = player.getName() if self._players.has_key(name): if player in self._players[name]: self._players[name].remove(player) player._destroy() def destroySound(self, sound): ''' destroy a sound object destroyes the C++ interface. the object is unusable after this and so is any player that uses the sound @param pyplayer: the Pysound wrapper for the sound to destory ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if not isinstance(sound, PySound): raise TypeError("Expected argument 1 to be of type PySound got %s" % type(sound)) sound._destroy() def findPlayer(self, str name): ''' tries to find a player for the sound whos name is passed. it find the player useing the intrealy kept list of wrpaed player instances. returns the first player in the list @param name: string the name of the soudn to find a player for @return: a PyPlayer wraper to the player object or None if no player is found ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") if self._players.has_key(name): if len(self._players[name]) > 0: return self._players[name][0] return None def play(self, name, float fadeTime = 0.0, bool looping = False, float gain = 1.0): ''' play the sound identified by the name passed (it must of alrady been created) @param name: string the name of the sound to play. it must alrady of been created @param fadeTime: float time is seconds for teh sound to fade in (0.0 by default) @param looping: bool should the sound loop? (False by default) @param gain: float the volume to play the sound at. 1.0 is normal 0.5 is half 2.0 is twice the volume ect. (1.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) XAL.mgr.play(hl_name, fadeTime, looping, gain) def stop(self, name, float fadeTime = 0.0): ''' stop playing the sound identifed by the name passed @param name: string the name of the sound to stop @param fadeTime: float the
Cython
time is second for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) XAL.mgr.stop(hl_name, fadeTime) def stopFirst(self, name, float fadeTime = 0.0): ''' stop playing the first player of the sound identifed by the name passed @param name: string the name of the sound to stop @param fadeTime: float the time is second for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) XAL.mgr.stopFirst(hl_name, fadeTime) def stopAll(self, float fadeTime = 0.0): ''' stop playing the all players of the sound identifed by the name passed @param name: string the name of the sound to stop @param fadeTime: float the time is second for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") XAL.mgr.stopAll(fadeTime) def isAnyPlaying(self, name): ''' @param name: sting name of sound to check @return: bool True if there is a sound by this name playing ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) cdef bint result = XAL.mgr.isAnyPlaying(hl_name) return result def isAnyFading(self, name): ''' @param name: sting name of sound to check @return: bool True if there is a sound by this name fading in or out ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) cdef bint result = XAL.mgr.isAnyFading(hl_name) return result def isAnyFadingIn(self, name): ''' @param name: sting name of sound to check @return: bool True if there is a sound by this name fading in ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) cdef bint result = XAL.mgr.isAnyFadingIn(hl_name) return result def isAnyFadingOut(self, name): ''' @param name: sting name of sound to check @return: bool True if there is a sound by this name fading out ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") cdef hstr hl_name = Py_to_Hstr(name) cdef bint result = XAL.mgr.isAnyFadingOut(hl_name) return result def suspendAudio(self): ''' pause all sounds and players @param fadeTime: float the time is second for the sound to fade out (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") XAL.mgr.suspendAudio() def resumeAudio(self): ''' resume all sounds and players @param fadeTime: float the time is second for the sound to fade in (0.0 by default) ''' if not self.isXALInitialized(): raise RuntimeError("XAL is not Initialized") XAL.mgr.resumeAudio() def Init(int backendId, bint threaded = True): ''' Setup XAL and create an XALManager interface at PyXAL.Mgr @param backendId: int window handel in the calling aplication @param threaded: bool should XAL use a threaded interface? (True by default) ''' global Mgr if Mgr is None: if XAL.mgr!= NULL: fade = 0.0 XAL.mgr.stopAll(fade) XAL.destroy() Mgr = XALManager(backendId, threaded) def Destroy(): ''' Destroy XAL and remove the interface at PyXAL setting it to None ''' global Mgr if XAL.mgr!= NULL: fade = 0.0 XAL.mgr.stopAll(fade) XAL.destroy() Mgr = None<|end_of_text|>from collections import OrderedDict as odict from bot_belief_1 cimport Bot as BotBelief1 from bot_belief_4 cimport Bot as BotBelief4 from bot_belief_f cimport Bot as BotBeliefF from bot_diffs_1 cimport Bot as BotDiffs1 from bot_diffs_1_m cimport Bot as BotDiffs1M from bot_diffs_2 cimport Bot as BotDiffs2 from bot_diffs_3 cimport Bot as BotDiffs3 from bot_diffs_4 cimport Bot as BotDiffs4 from bot_diffs_4_m cimport Bot as BotDiffs4M from bot_linear cimport Bot as BotLinear from bot_linear_m cimport Bot as BotLinearM from bot_phases_1 cimport Bot as BotPhases1 from bot_quadratic cimport Bot as BotQuadratic from bot_random cimport Bot as BotRandom from bot_random_1 cimport Bot as BotRandom1 from bot_random_5 cimport Bot as BotRandom5 from bot_random_n cimport Bot as BotRandomN from bot_simi cimport Bot as BotSimi from bot_states_1 cimport Bot as BotStates1 available_bots = odict(( ('belief_1', BotBelief1), ('belief_4', BotBelief4), ('belief_f', BotBeliefF), ('diffs_1', BotDiffs1), ('diffs_1_m', BotDiffs1M), ('diffs_2', BotDiffs2), ('diffs_3', BotDiffs3), ('diffs_4', BotDiffs4), ('diffs_4_m', BotDiffs4M), ('linear', BotLinear), ('linear_m', BotLinearM), ('phases_1', BotPhases1), ('quadratic', BotQuadratic), ('random', BotRandom), ('random_1', BotRandom1), ('random_5', BotRandom5), ('random_n', BotRandomN), ('simi', BotSimi), ('states_1', BotStates1) )) <|end_of_text|>from.object cimport PyObject cdef extern from "Python.h": ############################################################################ # 6.3 Sequence Protocol ############################################################################ bint PySequence_Check(object o) # Return 1 if the object provides sequence protocol, and 0 # otherwise. This function always succeeds. Py_ssize_t PySequence_Size(object o) except -1 # Returns the number of objects in sequence o on success, and -1 # on failure. For objects that do not provide sequence protocol, # this is equivalent to the Python expression "len(o)". Py_ssize_t PySequence_Length(object o) except -1 # Alternate name for PySequence_Size(). object PySequence_Concat(object o1, object o2) # Return value: New reference. # Return the concatenation of o1 and o2 on success, and NULL on # failure. This is the equivalent of the Python expression "o1 + # o2". object PySequence_Repeat(object o, Py_ssize_t count) # Return value: New reference. # Return the result of repeating sequence object o count times, or # NULL on failure. This is the equivalent of the Python expression # "o * count". object PySequence_InPlaceConcat(object o1, object o2) # Return value: New reference. # Return the concatenation of o1 and o2 on success, and NULL on # failure. The operation is done in-place when o1 supports # it. This is the equivalent of the Python expression "o1 += o2". object PySequence_InPlaceRepeat(object o, Py_ssize_t count) # Return value: New reference. # Return the result of repeating sequence object o count times, or # NULL on failure. The operation is done in-place when o supports # it. This is the equivalent of the Python expression "o *= # count". object PySequence_GetItem(object o, Py_ssize_t i) # Return value: New reference. # Return the ith element of o, or NULL on failure. This is the # equivalent of the Python expression "o[i]". object PySequence_GetSlice(object o, Py_ssize_t i1, Py_ssize_t i2) # Return value: New reference. # Return the slice of sequence object o between i1 and i2, or NULL # on failure. This is the equivalent of the Python expression # "o[i1
Cython
:i2]". int PySequence_SetItem(object o, Py_ssize_t i, object v) except -1 # Assign object v to the ith element of o. Returns -1 on # failure. This is the equivalent of the Python statement "o[i] = # v". This function does not steal a reference to v. int PySequence_DelItem(object o, Py_ssize_t i) except -1 # Delete the ith element of object o. Returns -1 on failure. This # is the equivalent of the Python statement "del o[i]". int PySequence_SetSlice(object o, Py_ssize_t i1, Py_ssize_t i2, object v) except -1 # Assign the sequence object v to the slice in sequence object o # from i1 to i2. This is the equivalent of the Python statement # "o[i1:i2] = v". int PySequence_DelSlice(object o, Py_ssize_t i1, Py_ssize_t i2) except -1 # Delete the slice in sequence object o from i1 to i2. Returns -1 # on failure. This is the equivalent of the Python statement "del # o[i1:i2]". int PySequence_Count(object o, object value) except -1 # Return the number of occurrences of value in o, that is, return # the number of keys for which o[key] == value. On failure, return # -1. This is equivalent to the Python expression # "o.count(value)". int PySequence_Contains(object o, object value) except -1 # Determine if o contains value. If an item in o is equal to # value, return 1, otherwise return 0. On error, return -1. This # is equivalent to the Python expression "value in o". Py_ssize_t PySequence_Index(object o, object value) except -1 # Return the first index i for which o[i] == value. On error, # return -1. This is equivalent to the Python expression # "o.index(value)". object PySequence_List(object o) # Return value: New reference. # Return a list object with the same contents as the arbitrary # sequence o. The returned list is guaranteed to be new. object PySequence_Tuple(object o) # Return value: New reference. # Return a tuple object with the same contents as the arbitrary # sequence o or NULL on failure. If o is a tuple, a new reference # will be returned, otherwise a tuple will be constructed with the # appropriate contents. This is equivalent to the Python # expression "tuple(o)". object PySequence_Fast(object o, char *m) # Return value: New reference. # Returns the sequence o as a tuple, unless it is already a tuple # or list, in which case o is returned. Use # PySequence_Fast_GET_ITEM() to access the members of the # result. Returns NULL on failure. If the object is not a # sequence, raises TypeError with m as the message text. PyObject* PySequence_Fast_GET_ITEM(object o, Py_ssize_t i) # Return value: Borrowed reference. # Return the ith element of o, assuming that o was returned by # PySequence_Fast(), o is not NULL, and that i is within bounds. PyObject** PySequence_Fast_ITEMS(object o) # Return the underlying array of PyObject pointers. Assumes that o # was returned by PySequence_Fast() and o is not NULL. object PySequence_ITEM(object o, Py_ssize_t i) # Return value: New reference. # Return the ith element of o or NULL on failure. Macro form of # PySequence_GetItem() but without checking that # PySequence_Check(o) is true and without adjustment for negative # indices. Py_ssize_t PySequence_Fast_GET_SIZE(object o) # Returns the length of o, assuming that o was returned by # PySequence_Fast() and that o is not NULL. The size can also be # gotten by calling PySequence_Size() on o, but # PySequence_Fast_GET_SIZE() is faster because it can assume o is # a list or tuple. <|end_of_text|>import sys cdef str container_format_postfix = 'le' if sys.byteorder == 'little' else 'be' cdef object _cinit_bypass_sentinel cdef AudioFormat get_audio_format(lib.AVSampleFormat c_format): """Get an AudioFormat without going through a string.""" cdef AudioFormat format = AudioFormat.__new__(AudioFormat, _cinit_bypass_sentinel) format._init(c_format) return format cdef class AudioFormat(object): """Descriptor of audio formats.""" def __cinit__(self, name): if name is _cinit_bypass_sentinel: return cdef lib.AVSampleFormat sample_fmt if isinstance(name, AudioFormat): sample_fmt = (<AudioFormat>name).sample_fmt else: sample_fmt = lib.av_get_sample_fmt(name) if sample_fmt < 0: raise ValueError('Not a sample format: %r' % name) self._init(sample_fmt) cdef _init(self, lib.AVSampleFormat sample_fmt): self.sample_fmt = sample_fmt def __repr__(self): return '<av.AudioFormat %s>' % (self.name) property name: """Canonical name of the sample format. >>> SampleFormat('s16p').name 's16p' """ def __get__(self): return <str>lib.av_get_sample_fmt_name(self.sample_fmt) property bytes: """Number of bytes per sample. >>> SampleFormat('s16p').bytes 2 """ def __get__(self): return lib.av_get_bytes_per_sample(self.sample_fmt) property bits: """Number of bits per sample. >>> SampleFormat('s16p').bits 16 """ def __get__(self): return lib.av_get_bytes_per_sample(self.sample_fmt) << 3 property is_planar: """Is this a planar format? Strictly opposite of :attr:`is_packed`. """ def __get__(self): return bool(lib.av_sample_fmt_is_planar(self.sample_fmt)) property is_packed: """Is this a planar format? Strictly opposite of :attr:`is_planar`. """ def __get__(self): return not lib.av_sample_fmt_is_planar(self.sample_fmt) property planar: """The planar variant of this format. Is itself when planar: >>> fmt = Format('s16p') >>> fmt.planar is fmt True """ def __get__(self): if self.is_planar: return self return get_audio_format(lib.av_get_planar_sample_fmt(self.sample_fmt)) property packed: """The packed variant of this format. Is itself when packed: >>> fmt = Format('s16') >>> fmt.packed is fmt True """ def __get__(self): if self.is_packed: return self return get_audio_format(lib.av_get_packed_sample_fmt(self.sample_fmt)) property container_name: """The name of a :class:`ContainerFormat` which directly accepts this data. :raises ValueError: when planar, since there are no such containers. """ def __get__(self): if self.is_planar: raise ValueError('no planar container formats') if self.sample_fmt == lib.AV_SAMPLE_FMT_U8: return 'u8' elif self.sample_fmt == lib.AV_SAMPLE_FMT_S16: return's16' + container_format_postfix elif self.sample_fmt == lib.AV_SAMPLE_FMT_S32: return's32' + container_format_postfix elif self.sample_fmt == lib.AV_SAMPLE_FMT_FLT: return 'f32' + container_format_postfix elif self.sample_fmt == lib.AV_SAMPLE_FMT_DBL: return 'f64' + container_format_postfix raise ValueError('unknown layout') <|end_of_text|># Copyright (c) Meta Platforms, Inc. and affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from libc cimport stdint from libcpp cimport bool as cbool from libcpp.string cimport string INT32_MIN = stdint.INT32_MIN INT32_MAX = stdint.INT32_MAX UINT32_MAX = stdint.UINT32_MAX INT64_MIN = stdint.INT64_MIN INT64_MAX = stdint.INT64_MAX UINT64_MAX = stdint.UINT64_MAX cdef extern from "
Cython
thrift/lib/python/capi/test/marshal_fixture.h" namespace "apache::thrift::python": cdef object __make_unicode(object) cdef object __roundtrip_pyobject[T](object) cdef object __roundtrip_unicode(object) cdef object __roundtrip_bytes(object) def roundtrip_int32(object x): return __roundtrip_pyobject[stdint.int32_t](x) def roundtrip_int64(object x): return __roundtrip_pyobject[stdint.int64_t](x) def roundtrip_uint32(object x): return __roundtrip_pyobject[stdint.uint32_t](x) def roundtrip_uint64(object x): return __roundtrip_pyobject[stdint.uint64_t](x) def roundtrip_float(object x): return __roundtrip_pyobject[float](x) def roundtrip_double(object x): return __roundtrip_pyobject[double](x) def roundtrip_bool(object x): return __roundtrip_pyobject[cbool](x) def roundtrip_bytes(object x): return __roundtrip_bytes(x) def roundtrip_unicode(object x): return __roundtrip_unicode(x) def make_unicode(object x): return __make_unicode(x) <|end_of_text|># cython: language_level=3 # cython: profile=True # Time-stamp: <2019-10-30 17:27:50 taoliu> """Module Description: Statistics function wrappers. NOTE: This file is no longer used in any other MACS2 codes. This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file LICENSE included with the distribution). """ from libc.math cimport log10, log from MACS2.Prob import poisson_cdf cdef class P_Score_Upper_Tail: """Unit to calculate -log10 poisson_CDF of upper tail and cache results in a hashtable. """ cdef: dict pscore_dict def __init__ ( self ): self.pscore_dict = dict() cpdef float get_pscore ( self, int x, float l ): cdef: float val if ( x, l ) in self.pscore_dict: return self.pscore_dict [ (x, l ) ] else: # calculate and cache val = -1 * poisson_cdf ( x, l, False, True ) self.pscore_dict[ ( x, l ) ] = val return val cdef class LogLR_Asym: """Unit to calculate asymmetric log likelihood, and cache results in a hashtable. """ cdef: dict logLR_dict def __init__ ( self ): self.logLR_dict = dict() cpdef float get_logLR_asym ( self, float x, float y ): cdef: float val if ( x, y ) in self.logLR_dict: return self.logLR_dict[ ( x, y ) ] else: # calculate and cache if x > y: val = (x*(log10(x)-log10(y))+y-x) elif x < y: val = (x*(-log10(x)+log10(y))-y+x) else: val = 0 self.logLR_dict[ ( x, y ) ] = val return val cdef class LogLR_Sym: """Unit to calculate symmetric log likelihood, and cache results in a hashtable. "symmetric" means f(x,y) = -f(y,x) """ cdef: dict logLR_dict def __init__ ( self ): self.logLR_dict = dict() cpdef float get_logLR_sym ( self, float x, float y ): cdef: float val if ( x, y ) in self.logLR_dict: return self.logLR_dict[ ( x, y ) ] else: # calculate and cache if x > y: val = (x*(log10(x)-log10(y))+y-x) elif y > x: val = (y*(log10(x)-log10(y))+y-x) else: val = 0 self.logLR_dict[ ( x, y ) ] = val return val cdef class LogLR_Diff: """Unit to calculate log likelihood for differential calling, and cache results in a hashtable. here f(x,y) = f(y,x) and f() is always positive. """ cdef: dict logLR_dict def __init__ ( self ): self.logLR_dict = dict() cpdef float get_logLR_diff ( self, float x, float y ): cdef: float val if ( x, y ) in self.logLR_dict: return self.logLR_dict[ ( x, y ) ] else: # calculate and cache if y > x: y, x = x, y if x == y: val = 0 else: val = (x*(log10(x)-log10(y))+y-x) self.logLR_dict[ ( x, y ) ] = val return val <|end_of_text|># cython: cdivision=True cpdef bytearray decrypt(unsigned char *data, int data_len, unsigned char *key, int key_len, unsigned char *scramble, int scramble_len, unsigned char counter, int counter_step=1): cdef unsigned int output_idx = 0 cdef unsigned int idx = 0 cdef unsigned int even_bit_shift = 0 cdef unsigned int odd_bit_shift = 0 cdef unsigned int is_even_bit_set = 0 cdef unsigned int is_odd_bit_set = 0 cdef unsigned int is_key_bit_set = 0 cdef unsigned int is_scramble_bit_set = 0 cdef unsigned int is_counter_bit_set = 0 cdef unsigned int is_counter_bit_inv_set = 0 cdef unsigned int cur_bit = 0 cdef unsigned int output_word = 0 output_data = bytearray(data_len * 2) while idx < data_len: output_word = 0 cur_data = (data[(idx * 2) + 1] << 8) | data[(idx * 2)] cur_bit = 0 while cur_bit < 8: even_bit_shift = (cur_bit * 2) & 0xff odd_bit_shift = (cur_bit * 2 + 1) & 0xff is_even_bit_set = int((cur_data & (1 << even_bit_shift))!= 0) is_odd_bit_set = int((cur_data & (1 << odd_bit_shift))!= 0) is_key_bit_set = int((key[idx % key_len] & (1 << cur_bit))!= 0) is_scramble_bit_set = int((scramble[idx % scramble_len] & (1 << cur_bit))!= 0) is_counter_bit_set = int((counter & (1 << cur_bit))!= 0) is_counter_bit_inv_set = int(counter & (1 << ((7 - cur_bit) & 0xff))!= 0) if is_scramble_bit_set == 1: is_even_bit_set, is_odd_bit_set = is_odd_bit_set, is_even_bit_set if ((is_even_bit_set ^ is_counter_bit_inv_set ^ is_key_bit_set)) == 1: output_word |= 1 << even_bit_shift if (is_odd_bit_set ^ is_counter_bit_set) == 1: output_word |= 1 << odd_bit_shift cur_bit += 1 output_data[output_idx] = (output_word >> 8) & 0xff output_data[output_idx+1] = output_word & 0xff output_idx += 2 counter += counter_step idx += 1 return output_data cpdef bytearray encrypt(unsigned char *data, int data_len, unsigned char *key, int key_len, unsigned char *scramble, int scramble_len, unsigned char counter, int counter_step=1): cdef unsigned int output_idx = 0 cdef unsigned int idx = 0 cdef unsigned int even_bit_shift = 0 cdef unsigned int odd_bit_shift = 0 cdef unsigned int is_even_bit_set = 0 cdef unsigned int is_odd_bit_set = 0 cdef unsigned int is_key_bit_set = 0 cdef unsigned int is_scramble_bit_set = 0 cdef unsigned int is_counter_bit_set = 0 cdef unsigned int is_counter_bit_inv_set = 0 cdef unsigned int cur_bit = 0 cdef unsigned int output_word = 0 cdef unsigned int set_even_bit = 0 cdef unsigned int set_odd_bit = 0 output_data = bytearray(data_len * 2) while idx < data_len: output_word = 0 cur_data = (data[(idx * 2)] << 8) | data[(idx * 2) + 1] cur_bit = 0 while cur_bit < 8: even_bit_shift = (cur_bit * 2) & 0xff odd_bit_shift
Cython
= (cur_bit * 2 + 1) & 0xff is_even_bit_set = int((cur_data & (1 << even_bit_shift))!= 0) is_odd_bit_set = int((cur_data & (1 << odd_bit_shift))!= 0) is_key_bit_set = int((key[idx % key_len] & (1 << cur_bit))!= 0) is_scramble_bit_set = int((scramble[idx % scramble_len] & (1 << cur_bit))!= 0) is_counter_bit_set = int((counter & (1 << cur_bit))!= 0) is_counter_bit_inv_set = int(counter & (1 << ((7 - cur_bit) & 0xff))!= 0) set_even_bit = is_even_bit_set ^ is_counter_bit_inv_set ^ is_key_bit_set set_odd_bit = is_odd_bit_set ^ is_counter_bit_set if is_scramble_bit_set == 1: set_even_bit, set_odd_bit = set_odd_bit, set_even_bit if set_even_bit == 1: output_word |= 1 << even_bit_shift if set_odd_bit == 1: output_word |= 1 << odd_bit_shift cur_bit += 1 output_data[output_idx] = output_word & 0xff output_data[output_idx+1] = (output_word >> 8) & 0xff output_idx += 2 counter += counter_step idx += 1 return output_data <|end_of_text|># cython: language_level=3 cdef class MultiCast: cdef bytes _group cdef bytes _port cdef bytes _iface cdef bytes _ip<|end_of_text|># mode: run # tag: closures # preparse: id # preparse: def_to_cdef # # closure_tests_2.pyx # # Battery of tests for closures in Cython. Based on the collection of # compiler tests from P423/B629 at Indiana University, Spring 1999 and # Fall 2000. Special thanks to R. Kent Dybvig, Dan Friedman, Kevin # Millikin, and everyone else who helped to generate the original # tests. Converted into a collection of Python/Cython tests by Craig # Citro. # # Note: This set of tests is split (somewhat randomly) into several # files, simply because putting all the tests in a single file causes # gcc and g++ to buckle under the load. # def g1526(): """ >>> g1526() 2 """ x_1134 = 0 def g1525(): x_1136 = 1 z_1135 = x_1134 def g1524(y_1137): return (x_1136)+((z_1135)+(y_1137)) return g1524 f_1138 = g1525() return f_1138(f_1138(x_1134)) def g1535(): """ >>> g1535() 3050 """ def g1534(): def g1533(): def g1531(t_1141): def g1532(f_1142): return t_1141(f_1142(1000)) return g1532 return g1531 def g1530(): def g1529(x_1140): return (x_1140)+(50) return g1529 return g1533()(g1530()) def g1528(): def g1527(y_1139): return (y_1139)+(2000) return g1527 return g1534()(g1528()) def g1540(): """ >>> g1540() 2050 """ def g1539(): t_1143 = 50 def g1538(f_1144): return (t_1143)+(f_1144()) return g1538 def g1537(): def g1536(): return 2000 return g1536 return g1539()(g1537()) def g1547(): """ >>> g1547() 2050 """ def g1546(): def g1545(): def g1543(t_1145): def g1544(f_1146): return (t_1145)+(f_1146()) return g1544 return g1543 return g1545()(50) def g1542(): def g1541(): return 2000 return g1541 return g1546()(g1542()) def g1550(): """ >>> g1550() 700 """ def g1549(): x_1147 = 300 def g1548(y_1148): return (x_1147)+(y_1148) return g1548 return g1549()(400) def g1553(): """ >>> g1553() 0 """ x_1152 = 3 def g1552(): def g1551(x_1150, y_1149): return x_1150 return g1551 f_1151 = g1552() if (f_1151(0, 0)): return f_1151(f_1151(0, 0), x_1152) else: return 0 def g1562(): """ >>> g1562() False """ def g1561(): def g1556(x_1153): def g1560(): def g1559(): return isinstance(x_1153, list) if (g1559()): def g1558(): def g1557(): return (x_1153[0]) return (g1557() == 0) return (not g1558()) else: return False if (g1560()): return x_1153 else: return False return g1556 f_1154 = g1561() def g1555(): def g1554(): return [0,[]] return [0,g1554()] return f_1154(g1555()) def g1570(): """ >>> g1570() False """ def g1569(): def g1563(x_1155): def g1568(): if (x_1155): def g1567(): def g1566(): return isinstance(x_1155, list) if (g1566()): def g1565(): def g1564(): return (x_1155[0]) return (g1564() == 0) return (not g1565()) else: return False return (not g1567()) else: return False if (g1568()): return x_1155 else: return False return g1563 f_1156 = g1569() return f_1156(0) def g1575(): """ >>> g1575() [] """ def g1574(): def g1571(x_1157): def g1573(): def g1572(): return isinstance(x_1157, list) if (g1572()): return True else: return (x_1157 == []) if (g1573()): return x_1157 else: return [] return g1571 f_1158 = g1574() return f_1158(0) def g1578(): """ >>> g1578() 4 """ y_1159 = 4 def g1577(): def g1576(y_1160): return y_1160 return g1576 f_1161 = g1577() return f_1161(f_1161(y_1159)) def g1581(): """ >>> g1581() 0 """ y_1162 = 4 def g1580(): def g1579(x_1164, y_1163): return 0 return g1579 f_1165 = g1580() return f_1165(f_1165(y_1162, y_1162), f_1165(y_1162, y_1162)) def g1584(): """ >>> g1584() 0 """ y_1166 = 4 def g1583(): def g1582(x_1168, y_1167): return 0 return g1582 f_1169 = g1583() return f_1169(f_1169(y_1166, y_1166), f_1169(y_1166, f_1169(y_1166, y_1166))) def g1587(): """ >>> g1587() 0 """ y_1170 =
Cython
4 def g1586(): def g1585(x_1172, y_1171): return 0 return g1585 f_1173 = g1586() return f_1173(f_1173(y_1170, f_1173(y_1170, y_1170)), f_1173(y_1170, f_1173(y_1170, y_1170))) def g1594(): """ >>> g1594() 4 """ def g1593(): def g1588(y_1174): def g1592(): def g1591(f_1176): return f_1176(f_1176(y_1174)) return g1591 def g1590(): def g1589(y_1175): return y_1175 return g1589 return g1592()(g1590()) return g1588 return g1593()(4) def g1598(): """ >>> g1598() 23 """ def g1597(): def g1596(x_1177): return x_1177 return g1596 f_1178 = g1597() def g1595(): if (False): return 1 else: return f_1178(22) return (g1595()+1) def g1603(): """ >>> g1603() 22 """ def g1602(): def g1601(x_1179): return x_1179 return g1601 f_1180 = g1602() def g1600(): def g1599(): return 23 == 0 return f_1180(g1599()) if (g1600()): return 1 else: return 22 def g1611(): """ >>> g1611() 5061 """ def g1610(): def g1609(x_1182): if (x_1182): return (not x_1182) else: return x_1182 return g1609 f_1185 = g1610() def g1608(): def g1607(x_1181): return (10)*(x_1181) return g1607 f2_1184 = g1608() x_1183 = 23 def g1606(): def g1605(): def g1604(): return x_1183 == 0 return f_1185(g1604()) if (g1605()): return 1 else: return (x_1183)*(f2_1184((x_1183-1))) return (g1606()+1) def g1614(): """ >>> g1614() 1 """ def g1613(): def g1612(): return 0 return g1612 f_1186 = g1613() x_1187 = f_1186() return 1 def g1617(): """ >>> g1617() 1 """ def g1616(): def g1615(): return 0 return g1615 f_1188 = g1616() f_1188() return 1 def g1620(): """ >>> g1620() 4 """ def g1619(): def g1618(x_1189): return x_1189 return g1618 f_1190 = g1619() if (True): f_1190(3) return 4 else: return 5 def g1623(): """ >>> g1623() 6 """ def g1622(): def g1621(x_1191): return x_1191 return g1621 f_1192 = g1622() (f_1192(4)) if (True) else (5) return 6 def g1627(): """ >>> g1627() 120 """ def g1626(): def g1624(fact_1195, n_1194, acc_1193): def g1625(): return n_1194 == 0 if (g1625()): return acc_1193 else: return fact_1195(fact_1195, (n_1194-1), (n_1194)*(acc_1193)) return g1624 fact_1196 = g1626() return fact_1196(fact_1196, 5, 1) def g1632(): """ >>> g1632() 144 """ def g1631(): def g1628(b_1199, c_1198, a_1197): b_1203 = (b_1199)+(a_1197) def g1630(): def g1629(): a_1201 = (b_1199)+(b_1199) c_1200 = (c_1198)+(c_1198) return (a_1201)+(a_1201) return (a_1197)+(g1629()) a_1202 = g1630() return (a_1202)*(a_1202) return g1628 return g1631()(2, 3, 4) def g1639(): """ >>> g1639() 3 """ def g1638(): def g1636(x_1204): def g1637(): return x_1204() return g1637 return g1636 f_1205 = g1638() def g1635(): def g1634(): def g1633(): return 3 return g1633 return f_1205(g1634()) return g1635()() def g1646(): """ >>> g1646() 3628800 """ def g1645(): def g1643(x_1207): def g1644(): return x_1207 == 0 if (g1644()): return 1 else: return (x_1207)*(f_1206((x_1207)-(1))) return g1643 f_1206 = g1645() q_1208 = 17 def g1642(): def g1640(a_1209): q_1208 = 10 def g1641(): return a_1209(q_1208) return g1641 return g1640 g_1210 = g1642() return g_1210(f_1206)() <|end_of_text|># cython: language_level = 3, boundscheck = False from __future__ import absolute_import from._noncustomizable cimport noncustomizable cdef class saved_yields(noncustomizable): pass <|end_of_text|>""" Cython implementation for the 1D shock code """ from __future__ import division from scipy.special import erf, erfinv from numpy cimport ndarray, dtype import numpy as np; cimport numpy as np cimport cython; from cpython cimport bool # # Types # DTYPE = np.float64 ctypedef np.float64_t DTYPE_t # # Constants here and externs from math # cdef extern from "math.h": double sqrt(double m) double pow(double m, double n) double exp(double a) double fabs(double a) double M_PI bint isnan(double x) double log10(double x) double fmin(double, double) cdef double kk = 1.3806488e-16 cdef double ss = 5.670367e-5 # # Functions HERE # """ Decipher the input parameters from the gas and dust parameters """ cdef decipherW(ndarray[DTYPE_t, ndim=1] w, int nspecs, int ndust): """ Variables """ cdef int ig, id cdef ndarray[DTYPE_t, ndim=1] w1 = np.zeros(w.shape[0], dtype=DTYPE) # # First copy # for ig in range(w.shape[0]): w1[ig] = w[ig] # # modify gas # for ig in range(nspecs): w1[2+ig] = w[2+ig] # # modify dust: limit size # for id in range(ndust): if (w1[<unsigned int> (2+nspecs+4*id+3)] < 0.0): w1[2+nspecs+4*id+3] = 1e-30 return w1 """""" cdef double calcQdust(double Tg, double vdg, double Td, double mass,
Cython
README.md exists but content is empty.
Downloads last month
40