def run_mode(self, mode): current_idx = c_int.in_dll(_dll, 'run_mode') for idx, mode_value in _RUN_MODES.items(): if mode_value == mode: current_idx.value = idx break else: raise ValueError('Invalid run mode: {}'.format(mode))
def get_default_compiler(): global _default_compiler, _default_flags if _default_compiler: return _default_compiler from ctypes import c_int from .baseconfig import camblib try: c_int.in_dll(camblib, "modelparams_mp_threadnum_") import platform _default_compiler = 'ifort' if platform.system() == 'Darwin': _default_flags = "-dynamiclib -fpic -O1 -W0 -WB" else: _default_flags = "-shared -fpic -O1 -W0 -WB" except: _default_compiler = 'gfortran' _default_flags = "-shared -fPIC -O1 -fmax-errors=4" # _default_flags="-shared -fPIC -g -fbounds-check -fbacktrace -ffpe-trap=invalid,overflow,zero", return _default_compiler
def check_namespaces_available_status(self): """ On rhel6/7, the kernel default does not enable all namespaces that it supports. """ if self._namespaces_available_status_checked: return unshare = self.functions["unshare"].func EINVAL = 22 r, w = os.pipe() pid0 = _fork() if pid0 == 0: pid1 = _fork() if pid1 == 0: os.close(r) tmpfile = os.fdopen(w, 'wb') keys = [] for ns in self.namespaces.namespaces: ns_obj = getattr(self.namespaces, ns) val = ns_obj.value res = unshare(c_int(val)) _errno_c_int = c_int.in_dll(pythonapi, "errno") if res == -1: if _errno_c_int.value != EINVAL: keys.append(ns) else: keys.append(ns) pickle.dump(keys, tmpfile) tmpfile.close() sys.exit(0) else: os.waitpid(pid1, 0) sys.exit(0) else: os.close(w) tmpfile = os.fdopen(r, 'rb') os.waitpid(pid0, 0) keys = pickle.load(tmpfile) tmpfile.close() for ns_name in self.namespaces.namespaces: if ns_name not in keys: ns_obj = getattr(self.namespaces, ns_name) ns_obj.available = False self._namespaces_available_status_checked = True
def c_func_wrapper(*args, **context): tmp_args = [] for arg in args: if is_string_or_unicode(arg): tmp_args.append(to_bytes(arg)) else: tmp_args.append(arg) res = c_func(*tmp_args) c_int_errno = c_int.in_dll(pythonapi, "errno") if func_obj.failed(res): if c_int_errno.value == EPERM: raise NamespaceRequireSuperuserPrivilege() else: raise CFunctionCallFailed(os.strerror(c_int_errno.value)) return res
import sys import ctypes from math import log10 import win32gui import win32con import win32api from PIL import Image, ImageTk, ImageColor from mutagen import File from mutagen.flac import FLAC from mutagen.mp4 import MP4 import win32com.client import sys if __doc__ is None and hasattr(sys, 'frozen'): from ctypes import c_int, pythonapi c_int.in_dll(pythonapi, 'Py_OptimizeFlag').value = 2 import numpy as np # Connect to foobar2k program = "Foobar2000.Application.0.7" try: f2k = win32com.client.Dispatch(program) except Exception: win32api.MessageBox( 0, "Could not connect to Foobar 2000 COM server. Please refer to the included README file.", "FoobarMiniplayer - Error") sys.exit() playback = f2k.Playback
from unittest.mock import MagicMock camblib = MagicMock() import_property = MagicMock() else: if not osp.isfile(CAMBL): sys.exit( 'Library file %s does not exist.\nMake sure you have installed or built the camb package ' '(e.g. using "python setup.py make"); or remove any old conflicting installation and install again.' % CAMBL) camblib = ctypes.LibraryLoader(IfortGfortranLoader).LoadLibrary(CAMBL) try: c_int.in_dll(camblib, "handles_mp_set_cls_template_") gfortran = False except Exception: pass class _dll_value: __slots__ = ['f'] def __init__(self, f): self.f = f def __get__(self, instance, owner): return self.f.value def __set__(self, instance, value):
def set_int(lib: CDLL, name: str, value: int): try: c_int.in_dll(lib, name).value = value except Exception as e: log.w(f"set_int failed: {e}") raise CException(e)
def _fork(): pid = os.fork() _errno_c_int = c_int.in_dll(pythonapi, "errno") if pid == - 1: raise RuntimeError(os.strerror(_errno_c_int.value)) return pid
def geterrno(cls): return c_int.in_dll(cls.libc, 'errno').value
def errcode(s): return c_int.in_dll(_dll, s).value
def run_mode(self): i = c_int.in_dll(_dll, 'run_mode').value try: return _RUN_MODES[i] except KeyError: return None
def initialize_library(): """Prepare the stellarEvolution library for use.""" library_fname = find_library('stellarEvolution') if library_fname is None: raise OSError('Unable to find POET\'s stellarEvolution library.') result = cdll.LoadLibrary(library_fname) num_quantities = c_int.in_dll(result, 'NUM_QUANTITIES').value result.create_interpolator.argtypes = [ c_char_p, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, shape=(num_quantities, ), flags='C_CONTIGUOUS'), numpy.ctypeslib.ndpointer(dtype=c_int, ndim=1, shape=(num_quantities, ), flags='C_CONTIGUOUS'), numpy.ctypeslib.ndpointer(dtype=c_bool, ndim=1, shape=(num_quantities, ), flags='C_CONTIGUOUS'), numpy.ctypeslib.ndpointer(dtype=c_bool, ndim=1, shape=(num_quantities, ), flags='C_CONTIGUOUS'), c_uint ] result.create_interpolator.restype = c_interpolator_p result.destroy_interpolator.argtypes = [result.create_interpolator.restype] result.destroy_interpolator.restype = None result.create_quantity.argtypes = [ result.create_interpolator.restype, c_int, c_double, c_double ] result.create_quantity.restype = c_quantity_p result.destroy_quantity.argtypes = [c_quantity_p] result.destroy_quantity.restype = None result.evaluate_quantity.argtypes = [c_quantity_p, c_double] result.evaluate_quantity.restype = c_double result.evaluate_quantity_array.argtypes = [ c_quantity_p, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'), c_uint, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'), ] result.quantity_min_age.restype = c_double result.quantity_max_age.restype = c_double result.quantity_continuous_range.restype = None result.save_interpolator.argtypes = [ result.create_interpolator.restype, c_char_p ] result.save_interpolator.restype = None result.load_interpolator.argtypes = [c_char_p] result.load_interpolator.restype = result.create_interpolator.restype result.differentiate_quantity.argtypes = [ c_quantity_p, c_double, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS') ] result.differentiate_quantity_array.argtypes = [ c_quantity_p, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS'), c_uint, numpy.ctypeslib.ndpointer(dtype=c_double, ndim=1, flags='C_CONTIGUOUS') ] result.default_smoothing.argtypes = [c_int] result.default_smoothing.restype = c_double result.default_vs_log_age.argtypes = [c_int] result.default_vs_log_age.restype = c_bool result.default_nodes.argtypes = [c_int] result.default_nodes.restype = c_int result.metallicity_from_feh.argtypes = [c_double] result.metallicity_from_feh.restype = c_double result.feh_from_metallicity.argtypes = [c_double] result.feh_from_metallicity.restype = c_double result.feh_from_z.argtypes = [c_double] result.feh_from_z.restype = c_double result.z_from_feh.argtypes = [c_double] result.z_from_feh.restype = c_double return result
class MESAInterpolator: """A class for interpolating among a set of MESA tracks.""" quantity_list = ['RADIUS', 'ICONV', 'LUM', 'IRAD', 'MRAD', 'RRAD'] quantity_ids = {q: c_int.in_dll(library, q).value for q in quantity_list} quantity_names = {c_int.in_dll(library, q).value: q for q in quantity_list} default_smoothing = { q_name: library.default_smoothing(q_id) for q_name, q_id in quantity_ids.items() } default_nodes = { q_name: library.default_nodes(q_id) for q_name, q_id in quantity_ids.items() } default_vs_log_age = { q_name: library.default_vs_log_age(q_id) for q_name, q_id in quantity_ids.items() } default_log_quantity = { q_name: library.default_log_quantity(q_id) for q_name, q_id in quantity_ids.items() } def __init__(self, **kwargs): """ Prepare a MESA based interpolation. Args: mesa_dir: A directory contaning a grid (mass and metallicity) of MESA tracks to base the interpolation on. Must not be specified if interpolator_fname is. smoothing: A numpy float array of the smoothing arguments to use for the interpolation of each quantity. Should be in the order defined by quantity_ids. nodes: A numpy integer array of the nodes to use for the interpolation of each quantity. Same order as smoothing. vs_log_age: A numpy boolean array indicating whether the interpolation for each quantity should be done vs log(age) instead of age. log_quantity: A numpy boolean array indicating whether the interpolation for each quantity should be of log(quantity) instead of quantity. interpolator_fname: The filename of a previously saved interpolator state. Must not be specified together with mesa_dir. If passed, the smoothing and nodes arguments are ignored. num_threads: The number of simultaneous threads to use when constructing the interpolation. Returns: None. """ if 'mesa_dir' in kwargs: self.interpolator = library.create_interpolator( kwargs['mesa_dir'].encode('ascii'), kwargs['smoothing'], kwargs['nodes'], kwargs['vs_log_age'], kwargs['log_quantity'], kwargs['num_threads']) else: assert 'interpolator_fname' in kwargs self.filename = kwargs['interpolator_fname'] self.interpolator = library.load_interpolator( kwargs['interpolator_fname'].encode('ascii')) def delete(self): """Free the resources allocated at construction.""" library.destroy_interpolator(self.interpolator) def save(self, filename): """ Save the interpolator created to the given file for faster creation. Args: filename: The name of the file to use for saving the state. Overwritten if exists. Returns: None """ self.filename = filename library.save_interpolator(self.interpolator, filename.encode('ascii')) def __call__(self, quantity, mass, feh): """ Return a stellar quantity interpolated to the given mass and [Fe/H]. Args: quantity: A string identifying the quantity to interpolate. The following values are allowed: 'radius', 'iconv', 'lum', 'irad', 'mrad', 'rrad'. This is a case insensitive argument. mass: The mass of the star for which this quantity should be defined in solar masses. feh: The [Fe/H] of the star for which this quantity should be defined. Returns: Quantity: callable with an age parameter evaluating to the quantity at the given age. """ return Quantity( library.create_quantity(self.interpolator, self.quantity_ids[quantity.upper()], c_double(mass), c_double(feh)))
def geterrno(cls): if sys.hexversion >= 0x02060000: from ctypes import get_errno return get_errno() # breaks on NetBSD return c_int.in_dll(cls.libc, 'errno').value
def __init__(self, name): self._dll = CDLL(name) self.Py_BytesWarningFlag = c_int.in_dll(self._dll, "Py_BytesWarningFlag") self.Py_DebugFlag = c_int.in_dll(self._dll, "Py_DebugFlag") self.Py_DontWriteBytecodeFlag = c_int.in_dll( self._dll, "Py_DontWriteBytecodeFlag") self.Py_IgnoreEnvironmentFlag = c_int.in_dll( self._dll, "Py_IgnoreEnvironmentFlag") self.Py_FrozenFlag = c_int.in_dll(self._dll, "Py_FrozenFlag") self.Py_InspectFlag = c_int.in_dll(self._dll, "Py_InspectFlag") self.Py_InteractiveFlag = c_int.in_dll(self._dll, "Py_InteractiveFlag") self.Py_NoSiteFlag = c_int.in_dll(self._dll, "Py_NoSiteFlag") self.Py_OptimizeFlag = c_int.in_dll(self._dll, "Py_OptimizeFlag") self.Py_UseClassExceptionsFlag = c_int.in_dll( self._dll, "Py_UseClassExceptionsFlag") self.Py_VerboseFlag = c_int.in_dll(self._dll, "Py_VerboseFlag") if not PY3: self.Py_DivisionWarningFlag = c_int.in_dll( self._dll, "Py_DivisionWarningFlag") self.Py_Py3kWarningFlag = c_int.in_dll(self._dll, "Py_Py3kWarningFlag") self.Py_TabcheckFlag = c_int.in_dll(self._dll, "Py_TabcheckFlag") self.Py_UnicodeFlag = c_int.in_dll(self._dll, "Py_UnicodeFlag") self.Py_SetProgramName = self._dll.Py_SetProgramName self.Py_SetProgramName.restype = None self.Py_SetProgramName.argtypes = [STRING] self.Py_SetPythonHome = self._dll.Py_SetPythonHome self.Py_SetPythonHome.restype = None self.Py_SetPythonHome.argtypes = [STRING] self.Py_GetPath = self._dll.Py_GetPath self.Py_GetPath.restype = STRING self.Py_GetPath.argtypes = [] self.Py_Initialize = self._dll.Py_Initialize self.Py_Initialize.restype = None self.Py_Initialize.argtypes = [] self.PyRun_SimpleStringFlags = self._dll.PyRun_SimpleStringFlags self.PyRun_SimpleStringFlags.restype = c_int self.PyRun_SimpleStringFlags.argtypes = [c_char_p, c_void_p]
# # SPDX-License-Identifier: GPL-2.0-or-later # ============================================================================ from ctypes import c_int, c_bool from pydecor import export from pyGHDL.libghdl import libghdl from pyGHDL.libghdl._types import SourceFileEntry, NameId __all__ = ["Current_Token", "Flag_Comment"] # This is a c_int, so you want to use its .value Current_Token = c_int.in_dll(libghdl, "vhdl__scanner__current_token") Flag_Comment = c_bool.in_dll(libghdl, "vhdl__scanner__flag_comment") @export def Set_File(SourceFile: SourceFileEntry) -> None: """ Initialize the scanner with file :obj:`SourceFile`. :param SourceFile: File to scan. """ libghdl.vhdl__scanner__set_file(SourceFile) @export def Close_File() -> None:
from unittest.mock import MagicMock isitgrlib = MagicMock() import_property = MagicMock() else: if not osp.isfile(CAMBL): sys.exit( 'Library file %s does not exist.\nMake sure you have installed or built the camb package ' '(e.g. using "python setup.py make"); or remove any old conflicting installation and install again.' % CAMBL) isitgrlib = ctypes.LibraryLoader(IfortGfortranLoader).LoadLibrary(CAMBL) try: c_int.in_dll(isitgrlib, "handles_mp_set_cls_template_") gfortran = False except Exception: pass class _dll_value(object): __slots__ = ['f'] def __init__(self, f): self.f = f def __get__(self, instance, owner): return self.f.value def __set__(self, instance, value):
def __init__(self, name): self._dll = CDLL(name) self.Py_BytesWarningFlag = c_int.in_dll(self._dll, "Py_BytesWarningFlag") self.Py_DebugFlag = c_int.in_dll(self._dll, "Py_DebugFlag") self.Py_DontWriteBytecodeFlag = c_int.in_dll(self._dll, "Py_DontWriteBytecodeFlag") self.Py_IgnoreEnvironmentFlag = c_int.in_dll(self._dll, "Py_IgnoreEnvironmentFlag") self.Py_FrozenFlag = c_int.in_dll(self._dll, "Py_FrozenFlag") self.Py_InspectFlag = c_int.in_dll(self._dll, "Py_InspectFlag") self.Py_InteractiveFlag = c_int.in_dll(self._dll, "Py_InteractiveFlag") self.Py_NoSiteFlag = c_int.in_dll(self._dll, "Py_NoSiteFlag") self.Py_OptimizeFlag = c_int.in_dll(self._dll, "Py_OptimizeFlag") self.Py_UseClassExceptionsFlag = c_int.in_dll(self._dll, "Py_UseClassExceptionsFlag") self.Py_VerboseFlag = c_int.in_dll(self._dll, "Py_VerboseFlag") if not PY3: self.Py_DivisionWarningFlag = c_int.in_dll(self._dll, "Py_DivisionWarningFlag") self.Py_Py3kWarningFlag = c_int.in_dll(self._dll, "Py_Py3kWarningFlag") self.Py_TabcheckFlag = c_int.in_dll(self._dll, "Py_TabcheckFlag") self.Py_UnicodeFlag = c_int.in_dll(self._dll, "Py_UnicodeFlag") self.Py_SetProgramName = self._dll.Py_SetProgramName self.Py_SetProgramName.restype = None self.Py_SetProgramName.argtypes = [STRING] self.Py_SetPythonHome = self._dll.Py_SetPythonHome self.Py_SetPythonHome.restype = None self.Py_SetPythonHome.argtypes = [STRING] self.Py_GetPath = self._dll.Py_GetPath self.Py_GetPath.restype = STRING self.Py_GetPath.argtypes = [] self.Py_Initialize = self._dll.Py_Initialize self.Py_Initialize.restype = None self.Py_Initialize.argtypes = [] self.PyRun_SimpleStringFlags = self._dll.PyRun_SimpleStringFlags self.PyRun_SimpleStringFlags.restype = c_int self.PyRun_SimpleStringFlags.argtypes = [c_char_p, c_void_p]
def confirm_flag(test, name): flag = c_int.in_dll(test.mock, name) flag.value = 0 yield test.assertTrue(flag.value, "Expected flag %s to be true" % name)
''' from ctypes import CDLL, c_int, c_char_p, c_ulonglong, byref from secrets import token_bytes import time, os, os.path class ValidityException(Exception): pass if os.name == 'nt': drgc = CDLL("dragoncrypt.dll") else: drgc = CDLL(os.path.join(os.getcwd(), 'dragoncrypt.so')) KEY_SIZE = c_int.in_dll(drgc, 'dragoncryptKeySize').value def encrypt(input: bytes, key: int, iv_size: int) -> bytes: ''' Encrypts the byte array `input` with the provided `key`, prepending the message with an initialization vector with `iv_size` random bytes. `iv_size` must be the same when decrypting, to read back the data properly. ''' size = len(input) input_p = c_char_p(input) iv = token_bytes(iv_size) iv_ptr = c_char_p(iv) output = bytes(size + KEY_SIZE + iv_size) output_p = c_char_p(output)
def c_func_wrapper(*args, **context): res = c_func(*args) c_int_errno = c_int.in_dll(pythonapi, "errno") if func_obj.failed(res): raise RuntimeError(os.strerror(c_int_errno.value)) return res
def c_pair(mem): c_name = prefix + mem + suffix c_var = c_int.in_dll(libshade, c_name) c_value = c_var.value return (mem, c_value)
class Binary: """A class for binaries POET can evolve.""" evolution_modes = ['LOCKED_SURFACE_SPIN', 'BINARY', 'SINGLE', 'TABULATION'] _evolution_mode_ids = { mode: c_int.in_dll(library, mode + '_EVOL_MODE').value for mode in evolution_modes } def _get_evolution_quantities(self): """ Return the list of quantities in the evolution of the binary. Args: None Returns: [str]: A list of the evolution quantities tracked for an evolution of the current system. """ evolution_quantities = ['age', 'semimajor', 'eccentricity'] star_float_quantities = ['envelope_inclination', 'core_inclination', 'envelope_periapsis', 'core_periapsis', 'envelope_angmom', 'core_angmom'] secondary_is_star = isinstance(self.secondary, EvolvingStar) if secondary_is_star: for quantity in star_float_quantities: evolution_quantities.append('primary_' + quantity) for quantity in star_float_quantities: evolution_quantities.append('secondary_' + quantity) else: evolution_quantities.extend(star_float_quantities + [ 'planet_inclination', 'planet_periapsis', 'planet_angmom' ]) rate_quantities = ( [q + '_rate' for q in evolution_quantities[1:]] ) evolution_quantities.append('evolution_mode') if secondary_is_star: evolution_quantities.extend(['primary_wind_saturation', 'secondary_wind_saturation']) else: evolution_quantities.append('wind_saturation') evolution_quantities.extend(rate_quantities) return evolution_quantities @staticmethod def evolution_quantity_c_type(quantity): """Return the ctypes type of the given evolution quantity.""" if quantity == 'evolution_mode': return c_int if quantity.endswith('wind_saturation'): return c_bool return c_double #TODO: revive c-code creation def _create_c_code(self, c_code_fname, *, final_age, max_time_step, precision, eccentricity_expansion_fname): """Create a c++ file calculating the currently set-up evolution.""" assert eccentricity_expansion_fname c_code_substitutions = dict( poet_include_path=os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__) ) ), 'poet_src' ), feh=self.primary.metallicity, secondary_radius=(numpy.nan if isinstance(self.secondary, EvolvingStar) else self.secondary.radius), secondary_is_star=isinstance(self.secondary, EvolvingStar), dissipative_primary=bool(self.primary.dissipation), dissipative_secondary=bool(self.secondary.dissipation), final_age=final_age, max_time_step=max_time_step, precision=precision, eccentricity_expansion_fname=os.path.abspath( eccentricity_expansion_fname ).decode(), **self.initial_conditions ) ( c_code_substitutions['initial_secondary_envelope_angmom'], c_code_substitutions['initial_secondary_core_angmom'] ) = (self.secondary.spin_angmom if isinstance(self.secondary, EvolvingStar) else (numpy.nan, numpy.nan)) for component_name in ['primary', 'secondary']: component = getattr(self, component_name) c_code_substitutions[component_name + '_mass'] = component.mass if component.dissipation: assert set(component.dissipation.keys()) == set([0]) for param, value in component.dissipation[0].items(): if param != 'reference_phase_lag': value = ( '{}' if value is None else ( '{' + ', '.join('%.16e' % v for v in value) + '}' ) ) c_code_substitutions[ component_name + '_' + param ] = value for dependence in ['spin', 'tidal']: for tail in ['breaks', 'powers']: value_list = component.dissipation[0][dependence + '_frequency_' + tail] if value_list is None: value_list = [] c_code_substitutions[ component_name + dependence + '_frequency_' + tail ] = ( '{' + ', '.join([repr(value) for value in value_list]) + '}' ) for param in ['wind_strength', 'wind_saturation_frequency', 'diff_rot_coupling_timescale']: c_code_substitutions[component_name + '_' + param] = ( getattr(component, param) if isinstance(component, EvolvingStar) else numpy.nan ) c_code_substitutions[component_name + '_interpolator_fname'] = ( os.path.abspath(component.interpolator.filename) if isinstance(component, EvolvingStar) else '' ) with open(c_code_fname, 'w') as c_code: c_code.write( open( os.path.join( os.path.dirname(__file__), 'calculate_evolution_template.cpp' ) ).read() % c_code_substitutions ) def _get_required_age_indices(self, evolution_ages): """Return the indices within evolution_ages of `self._required_ages`.""" indices = dict() for side in ['left', 'right']: indices[side] = numpy.searchsorted(evolution_ages, self._required_ages, side=side) indices[side][indices[side] == evolution_ages.size] = ( evolution_ages.size - 1 ) return numpy.unique( numpy.where( numpy.abs(evolution_ages[indices['right']] - self._required_ages) < numpy.abs(evolution_ages[indices['left']] - self._required_ages), indices['right'], indices['left'] ) ) def __init__(self, primary, secondary, *, disk_lock_frequency, disk_dissipation_age, initial_semimajor=None, initial_orbital_period=None, initial_eccentricity=0.0, initial_inclination=0.0, secondary_formation_age=None): """ Create a binary system out of two bodies. Args: - primary: The first body in the system. Assumed to always be there, so for a star-planet system this should be the star. - secondary: The second body in the system, initially may not be there and later may be engulfed by the first body. - disk_lock_frequency: Frequency of the surface spin of the primary when disk is present in rad/day. - disk_dissipation_age: Age when disk dissipates in Gyrs. - initial_semimajor: The semimajor axis of the orbit at which the secondary forms in solar radii. If omitted, initial_orbital_period must be specified. - initial_orbital_period: Alternative to specifying the initial semimajor axis. - initial_eccentricity: The eccentricity of the orbit at which the secondary forms. - initial_inclination: Inclination between surface zone of primary and initial orbit in radians. - secondary_formation_age: Age when the secondary forms. Returns: None """ assert isinstance(primary, EvolvingStar) self.primary = primary self.secondary = secondary if initial_semimajor is None: initial_semimajor = self.semimajor(initial_orbital_period) if secondary_formation_age is None: secondary_formation_age = disk_dissipation_age self.initial_conditions = dict( initial_eccentricity=initial_eccentricity, initial_inclination=initial_inclination, disk_dissipation_age=disk_dissipation_age, disk_lock_frequency=disk_lock_frequency, initial_semimajor=initial_semimajor, secondary_formation_age=secondary_formation_age ) self.evolution_quantities = self._get_evolution_quantities() if isinstance(secondary, LockedPlanet): c_create_func = library.create_star_planet_system self._c_get_evolution_func = library.get_star_planet_evolution self._c_get_final_state = library.get_star_planet_final_state else: assert isinstance(secondary, EvolvingStar) c_create_func = library.create_star_star_system self._c_get_evolution_func = library.get_star_star_evolution self._c_get_final_state = library.get_star_star_final_state self.c_binary = c_create_func( primary.c_body, secondary.c_body, initial_semimajor, initial_eccentricity, initial_inclination, disk_lock_frequency, disk_dissipation_age, secondary_formation_age ) self.num_evolution_steps = 0 self.c_solver = None self._required_ages = None def delete(self): """Destroy the binary created at construction.""" if hasattr(self.primary, 'destroy_star'): self.primary.destroy_star() self.primary = None if hasattr(self.secondary, 'destroy_star'): self.secondary.destroy_star() self.secondary = None library.destroy_binary(self.c_binary) if hasattr(self, 'c_solver'): library.destroy_solver(self.c_solver) def configure(self, *, age, semimajor, eccentricity, spin_angmom, inclination, periapsis, evolution_mode): """ Set the current state (orbit) of a system. Args: - age: The age to set the system to. - semimajor: The semimajor axis of the orbit in solar radii. - eccentricity: The eccentricity of the orbit. - spin_angmom: The spin angular momenta of the zones of the bodies (body 1 first, outermost zone to innermost, followed by body 2). - inclination: The inclinations of the zones of the bodies (same order as spin_angmom). The surface zone inclination must be omitted for single body systems. - periapsis: The arguments of periapsis of the zones of the bodies (same order as spin_angmom, but not including the surface zone of the first body). - evolution_mode: The evolution mode to assume. Must be one of the constants defined. Returns: None """ library.configure_system(self.c_binary, age, semimajor, eccentricity, spin_angmom, inclination, periapsis, self._evolution_mode_ids[evolution_mode]) def evolve(self, final_age, max_time_step, precision, required_ages, *, print_progress=False, create_c_code='', eccentricity_expansion_fname=None, timeout=0): """ Evolve the system forward from its current state. Args: - final_age: The age at which to stop the evolution in Gyrs. The starting age must be already set for the system through configure. - max_time_step: The maximum size of the time step allowed in Gyrs. - precision: The precision to require of the solution. - required_ages: Ages at which the evolution must stop precisely. - print_progress: Should output be created to show the progress in time steps. - create_c_code: The name of a file to create which when compiled will calculate the exact evolution currently set-up for this binary. If empty, no such file is created. - eccentricity_expansion_fname: The filename from which eccentricity expansion coefficients were read. Only used if create_c_code is not empty. - timeout: The maximum number of seconds the evolution is allowed to run. Non-positive value results in no timeout. Partially cumputed evolutions that time out can still be querried. Returnns: None """ if create_c_code: self._create_c_code( create_c_code, final_age=final_age, max_time_step=max_time_step, precision=precision, eccentricity_expansion_fname=eccentricity_expansion_fname ) self._required_ages = required_ages #The point is to check if previous call defined the member #pylint: disable=access-member-before-definition if hasattr(self, 'c_solver'): library.destroy_solver(self.c_solver) #pylint: enable=access-member-before-definition self.c_solver = library.evolve_system( self.c_binary, final_age, max_time_step, precision, required_ages, (0 if required_ages is None else required_ages.size), print_progress, timeout ) self.num_evolution_steps = library.num_evolution_steps(self.c_solver) def get_evolution(self, quantities=None, required_ages_only=False): """ Return the last calculated evolution. Args: quantities: An iterable of quantities to read the evolution of. The evolution of omitted quantities can still be obtained later by subsequent calls to this method. The allowed entries are in the star_star_evolution_quantities for binary star systems or in star_planet_evolution_quantities for a star-planet system. If None, it defaults to the full list of quantities for the given system. required_ages_only(bool): If True, the evolution returned contains only the values of the quantities at the `required_ages` specified when evolve() was called. Returns: Sturture: A structure with mebers named the same way as the input list of quantities containing the values of the corresponding quantity at each evolution step. The order is always in increasing age. """ result = SimpleNamespace() if quantities is None: quantities = self.evolution_quantities for quantity_name in quantities: setattr( result, quantity_name, numpy.empty( self.num_evolution_steps, dtype=self.evolution_quantity_c_type(quantity_name) ) ) get_evol_args = [self.c_solver, self.c_binary, self.primary.c_body, self.secondary.c_body] get_evol_args.extend([getattr(result, quantity, None) for quantity in self.evolution_quantities]) self._c_get_evolution_func(*get_evol_args) if required_ages_only: keep_indices = self._get_required_age_indices(result.age) for quantity_name in quantities: setattr( result, quantity_name, getattr(result, quantity_name)[keep_indices] ) return result def final_state(self): """Return the final evolution state of a system (all quantities).""" result = SimpleNamespace() library_final_state = [self.evolution_quantity_c_type(q)() for q in self.evolution_quantities] self._c_get_final_state(self.c_solver, self.c_binary, self.primary.c_body, self.secondary.c_body, *library_final_state) for quantity, library_value in zip(self.evolution_quantities, library_final_state): setattr(result, quantity, library_value.value) return result def orbital_frequency(self, semimajor): """ The orbital frequency of the system for the given semimajor axis. Args: - semimajor: The semimajor axis at which the system's orbital period is required in solar radii. Returns: The orbital period in days if the two bodies of this system are in an orbit with the given semimajor axis. """ return calc_orbital_frequency(self.primary.mass, self.secondary.mass, semimajor) def orbital_period(self, semimajor): """ The orbital period of the system for the given semimajor axis. Args: - semimajor: The semimajor axis at which the system's orbital period is required in solar radii. Returns: The orbital period in days if the two bodies of this system are in an orbit with the given semimajor axis. """ return 2.0 * numpy.pi / self.orbital_frequency(semimajor) def semimajor(self, orbital_period): """ The semimajor axis of the system for the given orbital period. Args: - orbital_period: The orbital period at which the system's orbital period is required in days. Returns: The semimajor axis in solar radii if the two bodies of this system are in an orbit with the given period. """ return calc_semimajor(self.primary.mass, self.secondary.mass, orbital_period) def orbital_angular_momentum(self, semimajor, eccentricity): """ The orbital agular momentum for the given semimajor/eccentricity. Args: - semimajor: The semimajor axis of the system. - eccentricity: The orbital eccentricity. Returns: The orbital angular momentum if the two bodies are in an orbit with the given semimajor axis and eccentricity in solar units. """ return calc_orbital_angular_momentum(self.primary.mass, self.secondary.mass, semimajor, eccentricity)
from ctypes import cdll, Structure, c_int, POINTER, byref, c_double, c_char_p libt3ns = cdll.LoadLibrary("libT3NS.so") MAX_SYMMETRIES = c_int.in_dll(libt3ns, "maxsymmetries").value def translate_symmgroup(symmetry): which_symmgroup = libt3ns.which_symmgroup which_symmgroup.argtypes = [c_char_p, POINTER(c_int)] which_symmgroup.restype = c_int if hasattr(symmetry, '__iter__') and not isinstance(symmetry, str): result = [] for s in symmetry: r = c_int(0) if which_symmgroup(s.encode('utf-8'), byref(r)) != 1: raise ValueError(f'{s} is not a value symmetry') result.append(r.value) return result else: r = c_int(0) s = symmetry if which_symmgroup(s.encode('utf-8'), byref(r)) != 1: raise ValueError(f'{s} is not a value symmetry') return r.value def translate_irrep(irrep, symmetry): def tl_one_irrep(ir, sym): if not isinstance(sym, int):
def get_int(lib: CDLL, name: str) -> int: try: return c_int.in_dll(lib, name).value except Exception as e: log.w(f"get_int failed: {e}") raise CException(e)
if mock_load: from unittest.mock import MagicMock camblib = MagicMock() import_property = MagicMock() else: if not osp.isfile(CAMBL): sys.exit('Library file %s does not exist.\nMake sure you have installed or built the camb package ' '(e.g. using "python setup.py make"); or remove any old conflicting installation and install again.' % ( CAMBL)) camblib = ctypes.LibraryLoader(ifort_gfortran_loader).LoadLibrary(CAMBL) try: c_int.in_dll(camblib, "handles_mp_set_cls_template_") gfortran = False except Exception: pass class _dll_value(object): __slots__ = ['f'] def __init__(self, f): self.f = f def __get__(self, instance, owner): return self.f.value def __set__(self, instance, value):
def learn_with_libc(): """ XXX ctypes 库只会自动转换 integer、string 和 bytes 这三种类型。所有其它类型需要用 c_xxx 之类的方法手动转换。 """ print(f'sizeof(c_int): {sizeof(_int)}') libc = cdll.LoadLibrary('libc.so.6') printf = libc.printf print(type(printf), printf) timestamp = libc.time(None) print(type(timestamp), timestamp) print(_int(10)) printf(b'Damn it %s. %f\n', b'nicely', Strange(3.14)) # XXX 指定函数的 argtypes 字段之后,就必须按指定类型传值。 printf.argtypes = [_char_p, _char_p, _int, _int] printf(b'hello, %s, %d, %d\n', b'hello', 1, 2) try: printf(0.1) assert False except TypeError: pass strchr = libc.strchr print(strchr(b'abcdef', ord('d'))) # XXX 指定函数的 restype 字段之后,返回值会被转换成相应类型。restype 可以设置成方法用于添加类型检测。 strchr.restype = _char_p print(strchr(b'abcdef', ord('d'))) i = _int() f = c_float() s = create_string_buffer(0, 32) print(i.value, f.value, s.value) # XXX byref 与 pointer 功能相似,但 byref 要简单和快一些。pointer 会真正创建一个指针并做许多其它事情。 libc.sscanf(b'999 3.14 hello', b'%d %f %s', byref(i), byref(f), s) print(i.value, f.value, s.value) p = Point(x=_double(10), y=_double(20)) print('Structure a', p.x, p.y) r = Rect(tl=Point(_double(1), _double(1))) print('Structure b', r.tl.x, r.br.y) s = Smart(int=10) print('Union a', s.double) s = Smart(double=10) print('Union b', s.int) c = Clever(number=0) c.flags.a = 1 print(f'c: {c.number}, p: {c.flags.p}') c.flags.n = 1 print(f'c: {c.number}') t = TenPointsArrayType() print(f'len(t): {len(t)}') ten_ints = _int * 10 ii = ten_ints(0, 2, 4, 6, 8, 1, 3, 5, 7, 9) print(f'[i for i in ii]: {[i for i in ii]}') ptr = pointer(i) print(f'ptr.contents: {ptr.contents}, ptr[0]: {ptr[0]}') # XXX 指针的 contents 不会返回原始值,使用它的 contents 时,会创建新的相等的值。 print(f'ptr.contents is i: {ptr.contents is i}') # noinspection PyTypeChecker ptr[0] = 22 print(f'i: {i}') c1 = Cell(name=b'hello') c2 = Cell(name=b'world') c1.next = pointer(c2) c2.next = pointer(c1) p = c1 for i in range(5): print(p.name, end=' ') p = p.next[0] print(f'End incomplete types example.') int_array5 = _int * 5 ia = int_array5(9, 7, 5, 3, 1) print(f'[i for i in ia]: {[i for i in ia]}') qsort = libc.qsort qsort.restype = None qsort(ia, len(ia), sizeof(_int), c_cmp_func) print(f'[i for i in ia]: {[i for i in ia]}') # XXX 访问动态库中的值。 opt_flag = _int.in_dll(pythonapi, 'Py_OptimizeFlag') print(f'opt_flag: {opt_flag}') table = frozen_table.in_dll(pythonapi, 'PyImport_FrozenModules') for item in table: # noinspection PyUnresolvedReferences if item.name is None: break # noinspection PyUnresolvedReferences print( f'item.name: {item.name.decode("ascii")}, item.size: {item.size}') # XXX 调整数组大小。 short_array = (_int * 4)() print(f'sizeof(short_array): {sizeof(short_array)}') resize(short_array, 32) print(f'sizeof(short_array): {sizeof(short_array)}')
class EvolvingStar(DissipatingBody): """A class for stars following interpolated stellar evolution tracks.""" deriv_list = ['NO', 'AGE', 'SPIN_FREQUENCY', 'ORBITAL_FREQUENCY'] deriv_ids = { d: c_int.in_dll(library, d + '_DERIV').value for d in deriv_list } lib_configure_body = orbital_evolution_library.configure_star def _evaluate_stellar_property(self, property_name, age, deriv_order=None): """Evaluate a library function at a single age or array of ages.""" if isinstance(age, numpy.ndarray): result = numpy.empty(dtype=c_double, shape=(age.size, ), order='C') c_function = getattr(library, property_name + '_array') if deriv_order is None: c_function(self.c_body, age, age.size, result) else: c_function(self.c_body, age, deriv_order, age.size, result) return result if deriv_order is None: return getattr(library, property_name)(self.c_body, age) return getattr(library, property_name)(self.c_body, age, deriv_order) def __init__(self, *, mass, metallicity, wind_strength, wind_saturation_frequency, diff_rot_coupling_timescale, interpolator): """ Create a star with the given properties and evolution. Args: - mass: The mass of the star in solar masses. - metallicity: The metallicity ([Fe/H]) of the star. - wind_strength: The efficiency of the wind carrying away angular momentum. - wind_saturation_frequency: The frequency at which the wind loss saturates in rad/day. - diff_rot_coupling_timescale: The timescale for differential rotation coupling. - interpolator: An instance of stellar_evolution.MESAInterpolator to base the stellar evolution on. Returns: None """ super().__init__() if (mass < interpolator.mass_range()[0] or mass > interpolator.mass_range()[1]): raise ValueError( ('Stellar mass: %s is outside the range supported by the ' 'stelalr evolution interpolator: %s - %s') % (repr(mass), repr(interpolator.mass_range()[0]), repr(interpolator.mass_range()[1]))) if (metallicity < interpolator.feh_range()[0] or metallicity > interpolator.feh_range()[1]): raise ValueError( ('Stellar metallicity: %s is outside the range supported by ' 'the stelalr evolution interpolator: %s - %s') % (repr(metallicity), repr(interpolator.feh_range()[0]), repr(interpolator.feh_range()[1]))) self.mass = mass self.metallicity = metallicity self.wind_strength = wind_strength self.wind_saturation_frequency = wind_saturation_frequency self.diff_rot_coupling_timescale = diff_rot_coupling_timescale self.interpolator = interpolator self.c_body = library.create_star(mass, metallicity, wind_strength, wind_saturation_frequency, diff_rot_coupling_timescale, interpolator.interpolator) def delete(self): """Destroy the library star object created at construction.""" library.destroy_star(self.c_body) #The parent method simply saves the parameters, so it need not name them. #pylint: disable=arguments-differ def set_dissipation(self, *, zone_index, tidal_frequency_breaks, spin_frequency_breaks, tidal_frequency_powers, spin_frequency_powers, reference_phase_lag, inertial_mode_enhancement=1.0, inertial_mode_sharpness=10.0): """ Set the dissipative properties of one of the zones of a star. Args: - zone_index: Which zone to set the dissiaption for (0 - envelope, 1 - core). - tidal_frequency_breaks: The locations of the breaks in tidal frequency in rad/day. Entries should be sorted. - spin_frequency_breaks: The locations of the breaks in spin frequency in rad/day. Entries should be sorted. - tidal_frequency_powers: The powerlaw indices for the tidal frequency dependence. Should be indexed in the same order as tidal_frequency_breaks, but must contain an additional starting entry for the powerlaw index before the first break. - spin_frequency_powers: The powerlaw indices for the spin frequency dependence. Should be indexed in the same order as spin_frequency_breaks, but must contain an additional starting entry for the powerlaw index before the first break. - reference_phase_lag: The phase lag at the first tidal and first spin frequency break. The rest are calculated by imposing continuity. - inertial_mode_enhancement: A factor by which the dissipation is enhanced in the inertial mode range. Must be >= 1 (1 for no enhancement). - inertial_mode_sharpness: Parameter controlling how sharp the transition between enhanced and non-enhanced dissipation is. Returns: None """ library.set_star_dissipation( self.c_body, zone_index, tidal_frequency_powers.size - 1, spin_frequency_powers.size - 1, tidal_frequency_breaks, spin_frequency_breaks, tidal_frequency_powers, spin_frequency_powers, reference_phase_lag, inertial_mode_enhancement, inertial_mode_sharpness) super().set_dissipation( zone_index=zone_index, tidal_frequency_breaks=tidal_frequency_breaks, tidal_frequency_powers=tidal_frequency_powers, spin_frequency_breaks=spin_frequency_breaks, spin_frequency_powers=spin_frequency_powers, reference_phase_lag=reference_phase_lag, inertial_mode_enhancement=inertial_mode_enhancement, inertial_mode_sharpness=inertial_mode_sharpness) #pylint: enable=arguments-differ def detect_stellar_wind_saturation(self): """Tell a fully configured star to set its wind saturation state.""" library.detect_stellar_wind_saturation(self.c_body) def select_interpolation_region(self, age): """ Prepare for interpolating stellar quantities around the given age. Args: - age: The age around which interpolation will be needed. Returns: None """ library.select_interpolation_region(self.c_body, age) def modified_phase_lag(self, *, zone_index, orbital_frequency_multiplier, spin_frequency_multiplier, forcing_frequency, deriv): """ Return the phase lag times the love number. The spin of the star must be set by calling the configure method. Args: - zone_index: The index of the zone whose lag to return. - orbital_frequency_multiplier: The multiplier of the orbital frequency in the expression for the forcing frequency. - spin_frequency_multiplier: The multiplier of the spin frequency in the expression for the forcing frequency. - forcing_frequency: The forcing frequency for which to return the phase lag. - deriv: One of the derivative IDs in self.deriv_ids identifying what derivative of the phase lag to return. Returns: The phase lag times the love number for the given parameters. If the forcing frequency is exactly 0.0, two values are returned, the first for infinitesimal positive and the second for infinitesimal negative forcing frequencies. """ above_lock_value = c_double() below_lock_value = library.modified_phase_lag( self.c_body, c_uint(zone_index), c_int(orbital_frequency_multiplier), c_int(spin_frequency_multiplier), c_double(forcing_frequency), c_int(deriv), byref(above_lock_value)) if forcing_frequency == 0: return below_lock_value, above_lock_value.value return below_lock_value def core_formation_age(self): """Return the age at which the core of the star forms in Gyrs.""" return library.core_formation_age(self.c_body) def lifetime(self): """Return the maximum age at which the star can be queried.""" return library.lifetime(self.c_body) def luminosity(self, age): """Return the luminosity of the star at the given age.""" return self._evaluate_stellar_property('luminosity', age) def core_inertia(self, age, deriv_order=0): """ Return the moment of inertia of the stellar core at the given age. """ return self._evaluate_stellar_property('core_inertia_deriv', age, deriv_order) def envelope_inertia(self, age, deriv_order=0): """ Return the moment of inertia of the stellar env. at the given age. """ return self._evaluate_stellar_property('envelope_inertia_deriv', age, deriv_order) def radius(self, age): """Return the luminosity of the star at the given age.""" return self._evaluate_stellar_property('star_radius', age)
def _errno(self): """Returns the last error ID :rtype: int """ return c_int.in_dll(self.lib, "i_errno").value
# libmit.mit_profile_reset.argtypes = None # libmit.mit_profile_dump.argtypes = [c_int] def is_aligned(addr): return (addr & (word_bytes - 1)) == 0 def sign_extend(x): if x & sign_bit: x |= -1 & ~uword_max return x argc = c_int.in_dll(libmit, "mit_argc") argv = POINTER(c_char_p).in_dll(libmit, "mit_argv") def register_args(*args): ''' Set `mit_argc` and `mit_argv`. - args - an iterable of `str` and/or `bytes`. ''' bargs = [] for arg in args: if isinstance(arg, str): arg = bytes(arg, 'utf-8') assert isinstance(arg, bytes) bargs.append(arg)
def get_cluster(self): return c_int.in_dll(self.libmicrocontroller, 'clusterID').value
def init_hamiltonian(self, doci): from pyT3NS.bookkeeper import translate_irrep ham = c_int.in_dll(libt3ns, 'ham') # only qchem or doci allowed atm. DOCI == 3, qchem == 1 nham = 1 + doci * 2 if nham != ham.value: libt3ns.destroy_hamiltonian() else: return ham.value = nham if not hasattr(self, '_nuc'): self._nuc = self._mol.energy_nuc() if not hasattr(self, '_eri'): self._eri = pyscf.ao2mo.kernel(self._mol, self._c) if not hasattr(self, '_h1e'): self._h1e = self._c.T @ pyscf.scf.hf.get_hcore(self._mol) @ self._c h1e = self._h1e.astype(numpy.float64).reshape(self._h1e.shape, order='F') assert h1e.ctypes.data % 16 == 0 # Check alignment h1e = h1e.ctypes.data_as(POINTER(c_double)) norb = self._c.shape[1] if self._eri.size == norb**4 or doci: fulleri = self._eri else: fulleri = pyscf.ao2mo.restore(1, self._eri, norb) if not doci: fulleri = fulleri.astype(numpy.float64).reshape(fulleri.shape, order='F') assert fulleri.ctypes.data % 16 == 0 # Check alignment fulleri = fulleri.ctypes.data_as(POINTER(c_double)) if doci: libt3ns.DOCI_ham_from_integrals.argtypes = \ [c_int, POINTER(c_double), POINTER(c_double), c_double] libt3ns.DOCI_ham_from_integrals(norb, h1e, fulleri, self._nuc) else: libt3ns.QC_ham_from_integrals.argtypes = \ [c_int, POINTER(c_int), POINTER(c_double), POINTER(c_double), c_double, c_int, c_int, c_int] irrep = None if self._pg_irrep is not None: for s in self.symmetries: if s in supported_pgs: irrep = (c_int * norb)(*translate_irrep(self._pg_irrep, s)) libt3ns.QC_ham_from_integrals( norb, irrep, h1e, fulleri, self._nuc, 3, int('SU2' in self.symmetries), int('SENIORITY' in self.symmetries), )
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <gnu.org/licenses>. # # SPDX-License-Identifier: GPL-2.0-or-later # ============================================================================ from ctypes import c_int from pyGHDL.libghdl import libghdl __all__ = ["Std_Logic_1164_Pkg", "Std_Logic_Type", "Std_Logic_Vector_Type"] Std_Logic_1164_Pkg = c_int.in_dll( libghdl, "vhdl__ieee__std_logic_1164__std_logic_1164_pkg") # Get value Std_Logic_Type = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__std_logic_type") # Get value Std_Logic_Vector_Type = c_int.in_dll( libghdl, "vhdl__ieee__std_logic_1164__std_logic_vector_type") # Get value # Rising_Edge = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__rising_edge") # Get value # Falling_Edge = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__falling_edge")
from libghdl import libghdl from ctypes import c_int Std_Logic_1164_Pkg = c_int.in_dll( libghdl, "vhdl__ieee__std_logic_1164__std_logic_1164_pkg") # Get value Std_Logic_Type = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__std_logic_type") # Get value Std_Logic_Vector_Type = c_int.in_dll( libghdl, "vhdl__ieee__std_logic_1164__std_logic_vector_type") # Get value Rising_Edge = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__rising_edge") # Get value Falling_Edge = c_int.in_dll(libghdl, "vhdl__ieee__std_logic_1164__falling_edge")
def get_concurrency(self): """Returns the number of threads used for computations.""" return c_int.in_dll(self.libvips, "vips__concurrency").value
import numpy from numpy import ctypeslib import os import platform import subprocess from .grammar import _gpu_funcs, indent_source from .utils import get_arg_type from .build_module import LIBEXT def import_driver(): parent = os.path.dirname(__file__) return ctypeslib.load_library('_driver', parent) _driver = import_driver() emulating = c_int.in_dll(_driver, 'emulating') _driver.drv_alloc.argtypes = [c_int] _driver.drv_alloc.restype = c_void_p _driver.drv_free.argtypes = [c_void_p] _driver.drv_free.restype = c_int _driver.drv_htod.argtypes = [c_void_p, ctypeslib.ndpointer(), c_int] _driver.drv_htod.restype = c_int _driver.drv_dtoh.argtypes = [ctypeslib.ndpointer(), c_void_p, c_int] _driver.drv_dtoh.restype = c_int class GPUError(Exception): pass
def __len__(self): return c_int.in_dll(_dll, 'n_nuclides').value
def set_addr_param(self, sensor_name): c_addr = c_int.in_dll(self.nxt.libanxt, "nxt_"+sensor_name+"_i2c_addr") c_addr = c_int(self.addr)
from ctypes import c_char_p, c_long, c_int, c_void_p, c_int32, c_int64, byref, c_uint from datetime import datetime from objc_tools.objc_json import objc_to_py from objc_tools.c.objc_handler import chandle __all__ = ['Battery'] IOServiceMatching = c.IOServiceMatching IOServiceMatching.argtypes=[c_char_p] IOServiceMatching.restype = c_long IOServiceMatching.errcheck = chandle IORegistryGetRootEntry = c.IORegistryGetRootEntry IORegistryGetRootEntry.argtypes = [c_int] IORegistryGetRootEntry.restype = c_void_p kIOMasterPortDefault=c_int.in_dll(c,'kIOMasterPortDefault') # srv=ObjCInstance(IOServiceMatching(b"IOPMPowerSource")) srv=IOServiceMatching(b"IOPMPowerSource") IOServiceGetMatchingService = c.IOServiceGetMatchingService IOServiceGetMatchingService.argtypes=[c_int, c_void_p] IOServiceGetMatchingService.restype = c_uint powerSource = IOServiceGetMatchingService(kIOMasterPortDefault, srv); #c.IOServiceGetMatchingService IORegistryEntryCreateCFProperties = c.IORegistryEntryCreateCFProperties IORegistryEntryCreateCFProperties.argtypes=[c_int64 ,c_void_p, c_void_p, c_int32 ] IORegistryEntryCreateCFProperty = c.IORegistryEntryCreateCFProperty IORegistryEntryCreateCFProperty.argtypes = [c_void_p, c_void_p, c_void_p, c_int32]
class Result(object): SUCCESS = c_int.in_dll( tablib, "TAB_RESULT_Success").value # Successful function call OUT_OF_MEMORY = c_int.in_dll(tablib, "TAB_RESULT_OutOfMemory").value # PERMISSION_DENIED = c_int.in_dll(tablib, "TAB_RESULT_PermissionDenied").value # INVALID_FILE = c_int.in_dll(tablib, "TAB_RESULT_InvalidFile").value # FILE_EXISTS = c_int.in_dll(tablib, "TAB_RESULT_FileExists").value # TOO_MANY_FILES = c_int.in_dll(tablib, "TAB_RESULT_TooManyFiles").value # FILE_NOT_FOUND = c_int.in_dll(tablib, "TAB_RESULT_FileNotFound").value # FISK_FULL = c_int.in_dll(tablib, "TAB_RESULT_DiskFull").value # DIRECTORY_NOT_EMPTY = c_int.in_dll(tablib, "TAB_RESULT_DirectoryNotEmpty").value # NO_SUCH_DATABASE = c_int.in_dll( tablib, "TAB_RESULT_NoSuchDatabase").value # Data Engine errors start at 200. QUERY_ERROR = c_int.in_dll(tablib, "TAB_RESULT_QueryError").value # NULL_ARGUMENT = c_int.in_dll(tablib, "TAB_RESULT_NullArgument").value # DATA_ENGINE_ERROR = c_int.in_dll(tablib, "TAB_RESULT_DataEngineError").value # CANCELLED = c_int.in_dll(tablib, "TAB_RESULT_Cancelled").value # BAD_INDEX = c_int.in_dll(tablib, "TAB_RESULT_BadIndex").value # PROTOCOL_ERROR = c_int.in_dll(tablib, "TAB_RESULT_ProtocolError").value # NETWORK_ERROR = c_int.in_dll(tablib, "TAB_RESULT_NetworkError").value # INTERNAL_ERROR = c_int.in_dll( tablib, "TAB_RESULT_InternalError").value # 300+: other error codes WRONG_TYPE = c_int.in_dll(tablib, "TAB_RESULT_WrongType").value # USAGE_ERROR = c_int.in_dll(tablib, "TAB_RESULT_UsageError").value # INVALID_ARGUMENT = c_int.in_dll(tablib, "TAB_RESULT_InvalidArgument").value # BAD_HANDLE = c_int.in_dll(tablib, "TAB_RESULT_BadHandle").value # UNKNOWN_ERROR = c_int.in_dll(tablib, "TAB_RESULT_UnknownError").value #
class Collation(object): BINARY = c_int.in_dll( tablib, "TAB_COLLATION_Binary").value # Internal binary representation AR = c_int.in_dll(tablib, "TAB_COLLATION_ar").value # Arabic CS = c_int.in_dll(tablib, "TAB_COLLATION_cs").value # Czech CS_CI = c_int.in_dll( tablib, "TAB_COLLATION_cs_CI").value # Czech (Case Insensitive) CS_CI_AI = c_int.in_dll( tablib, "TAB_COLLATION_cs_CI_AI").value # Czech (Case/Accent Insensitive DA = c_int.in_dll(tablib, "TAB_COLLATION_da").value # Danish DE = c_int.in_dll(tablib, "TAB_COLLATION_de").value # German EL = c_int.in_dll(tablib, "TAB_COLLATION_el").value # Greek EN_GB = c_int.in_dll( tablib, "TAB_COLLATION_en_GB").value # English (Great Britain) EN_US = c_int.in_dll(tablib, "TAB_COLLATION_en_US").value # English (US) EN_US_CI = c_int.in_dll( tablib, "TAB_COLLATION_en_US_CI").value # English (US, Case Insensitive) ES = c_int.in_dll(tablib, "TAB_COLLATION_es").value # Spanish ES_CI_AI = c_int.in_dll( tablib, "TAB_COLLATION_es_CI_AI").value # Spanish (Case/Accent Insensitive) ET = c_int.in_dll(tablib, "TAB_COLLATION_et").value # Estonian FI = c_int.in_dll(tablib, "TAB_COLLATION_fi").value # Finnish FR_CA = c_int.in_dll(tablib, "TAB_COLLATION_fr_CA").value # French (Canada) FR_FR = c_int.in_dll(tablib, "TAB_COLLATION_fr_FR").value # French (France) FR_FR_CI_AI = c_int.in_dll( tablib, "TAB_COLLATION_fr_FR_CI_AI" ).value # French (France, Case/Accent Insensitive) HE = c_int.in_dll(tablib, "TAB_COLLATION_he").value # Hebrew HU = c_int.in_dll(tablib, "TAB_COLLATION_hu").value # Hungarian IS = c_int.in_dll(tablib, "TAB_COLLATION_is").value # Icelandic IT = c_int.in_dll(tablib, "TAB_COLLATION_it").value # Italian JA = c_int.in_dll(tablib, "TAB_COLLATION_ja").value # Japanese JA_JIS = c_int.in_dll(tablib, "TAB_COLLATION_ja_JIS").value # Japanese (JIS) KO = c_int.in_dll(tablib, "TAB_COLLATION_ko").value # Korean LT = c_int.in_dll(tablib, "TAB_COLLATION_lt").value # Lithuanian LV = c_int.in_dll(tablib, "TAB_COLLATION_lv").value # Latvian NL_NL = c_int.in_dll(tablib, "TAB_COLLATION_nl_NL").value # Dutch (Netherlands) NN = c_int.in_dll(tablib, "TAB_COLLATION_nn").value # Norwegian PL = c_int.in_dll(tablib, "TAB_COLLATION_pl").value # Polish PT_BR = c_int.in_dll(tablib, "TAB_COLLATION_pt_BR").value # Portuguese (Brazil) PT_BR_CI_AI = c_int.in_dll( tablib, "TAB_COLLATION_pt_BR_CI_AI" ).value # Portuguese (Brazil Case/Accent Insensitive) PT_PT = c_int.in_dll(tablib, "TAB_COLLATION_pt_PT").value # Portuguese (Portugal) ROOT = c_int.in_dll(tablib, "TAB_COLLATION_root").value # Root RU = c_int.in_dll(tablib, "TAB_COLLATION_ru").value # Russian SL = c_int.in_dll(tablib, "TAB_COLLATION_sl").value # Slovenian SV_FI = c_int.in_dll(tablib, "TAB_COLLATION_sv_FI").value # Swedish (Finland) SV_SE = c_int.in_dll(tablib, "TAB_COLLATION_sv_SE").value # Swedish (Sweden) TR = c_int.in_dll(tablib, "TAB_COLLATION_tr").value # Turkish UK = c_int.in_dll(tablib, "TAB_COLLATION_uk").value # Ukrainian VI = c_int.in_dll(tablib, "TAB_COLLATION_vi").value # Vietnamese ZH_HANS_CN = c_int.in_dll( tablib, "TAB_COLLATION_zh_Hans_CN").value # Chinese (Simplified, China) ZH_HANT_TW = c_int.in_dll( tablib, "TAB_COLLATION_zh_Hant_TW").value # Chinese (Traditional, Taiwan)
def _coord_levels(): return c_int.in_dll(_dll, "n_coord_levels").value
def main(fn: Path, testrun=False): global abort start = time.perf_counter() if not fn.with_suffix(".bin").exists(): if not testrun: with open(fn.with_suffix(".yaml")) as f: parameters = Parameters(**yaml.safe_load(f)) else: parameters = Parameters( massloss_method="rbf", initcon_file="initcon/conditions_many.input") # set up a fresh simulation sim = Simulation() sim.units = ('yr', 'AU', 'kg') # sim.boundary = "open" # boxsize = 100 # sim.configure_box(boxsize) sim.integrator = "mercurius" sim.dt = 1e-2 sim.ri_ias15.min_dt = 0.0001 / 365 if not parameters.no_merging: sim.collision = "direct" sim.ri_mercurius.hillfac = 3. sim.testparticle_type = 1 tmax = 200 * mega num_savesteps = 20000 if testrun: tmax /= 200000 num_savesteps /= 1000 per_savestep = tmax / num_savesteps extradata = ExtraData() # times = np.linspace(0., tmax, savesteps) extradata.meta.tmax = tmax extradata.meta.per_savestep = per_savestep extradata.meta.num_savesteps = num_savesteps extradata.meta.git_hash = git_hash() extradata.meta.rebound_hash = rebound.__githash__ extradata.meta.massloss_method = parameters.massloss_method extradata.meta.initcon_file = parameters.initcon_file extradata.meta.no_merging = parameters.no_merging num_planetesimals, num_embryos = \ add_particles_from_conditions_file(sim, extradata, parameters.initcon_file, testrun) sim.move_to_com() extradata.meta.initial_N = sim.N extradata.meta.initial_N_planetesimal = num_planetesimals extradata.meta.initial_N_embryo = num_embryos extradata.history.append(energy=sim.calculate_energy(), momentum=total_momentum(sim), total_mass=total_mass(sim), time=sim.t, N=sim.N, N_active=sim.N_active) cputimeoffset = walltimeoffset = 0 t = 0 else: if fn.with_suffix(".lock").exists(): raise FileExistsError( "Lock file found, is the simulation currently running?") copy(fn.with_suffix(".bin"), fn.with_suffix(".bak.bin")) copy(fn.with_suffix(".extra.json"), fn.with_suffix(".extra.bak.json")) sa = SimulationArchive(str(fn.with_suffix(".bin"))) extradata = ExtraData.load(fn) tmax = extradata.meta.tmax per_savestep = extradata.meta.per_savestep sim = sa[-1] t = round(sim.t + per_savestep) print(f"continuing from {t}") sim.move_to_com() sim.ri_mercurius.recalculate_coordinates_this_timestep = 1 sim.integrator_synchronize() if extradata.meta.git_hash != git_hash(): print( "warning: The saved output was originally run with another version of the code" ) print(f"original: {extradata.meta.git_hash}") print(f"current: {git_hash()}") num_savesteps = extradata.meta.num_savesteps cputimeoffset = extradata.meta.cputime walltimeoffset = extradata.meta.walltime check_heartbeat_needs_recompile() clibheartbeat = cdll.LoadLibrary("heartbeat/heartbeat.so") clibheartbeat.init_logfile.argtypes = [c_char_p] logfile = create_string_buffer(128) logfile.value = str(fn.with_suffix(".energylog.csv")).encode() clibheartbeat.init_logfile(logfile) sim.heartbeat = clibheartbeat.heartbeat innermost_semimajor_axis = third_kepler_law( orbital_period=sim.dt * year * MIN_TIMESTEP_PER_ORBIT) / astronomical_unit * 1.1 print(f"innermost semimajor axis is {innermost_semimajor_axis}") c_double.in_dll( clibheartbeat, "min_distance_from_sun_squared").value = innermost_semimajor_axis**2 c_double.in_dll(clibheartbeat, "max_distance_from_sun_squared").value = 150**2 assert sim.dt < innermost_period(sim) / MIN_TIMESTEP_PER_ORBIT def collision_resolve_handler(sim_p: POINTER_REB_SIM, collision: reb_collision) -> int: global abort # needed as exceptions don't halt integration try: return merge_particles(sim_p, collision, ed=extradata) except BaseException as exception: print("exception during collision_resolve") print(exception) abort = True sim_p.contents._status = 1 raise exception sim.collision_resolve = collision_resolve_handler # show_orbits(sim) fn.with_suffix(".lock").touch() print("start") while t <= tmax: print() print(f"{t / tmax * 100:.2f}%") set_process_title(fn, t / tmax, sim.N) try: print(f"integrating until {t}") sim.integrate(t, exact_finish_time=0) print("dt", sim.dt) print("t", t) t += per_savestep except NoParticles: print("No Particles left") abort = True print("N", sim.N) print("N_active", sim.N_active) print("fraction", innermost_period(sim) / MIN_TIMESTEP_PER_ORBIT) assert sim.dt < innermost_period(sim) / MIN_TIMESTEP_PER_ORBIT escape: hb_event wide_orbit: hb_event sun_collision: hb_event for escape in hb_event_list.in_dll(clibheartbeat, "hb_escapes"): if not escape.new: continue print("escape:", escape.time, escape.hash) extradata.pdata[escape.hash].escaped = escape.time escape.new = 0 # make sure to not handle it again c_int.in_dll(clibheartbeat, "hb_escape_index").value = 0 for sun_collision in hb_event_list.in_dll(clibheartbeat, "hb_sun_collisions"): if not sun_collision.new: continue print("sun collision:", sun_collision.time, sun_collision.hash) extradata.pdata[ sun_collision.hash].collided_with_sun = sun_collision.time sun_collision.new = 0 c_int.in_dll(clibheartbeat, "hb_sun_collision_index").value = 0 for wide_orbit in hb_event_list.in_dll(clibheartbeat, "hb_wide_orbits"): if not wide_orbit.new: continue print("wide orbit:", wide_orbit.time, wide_orbit.hash) extradata.pdata[wide_orbit.hash].wide_orbit = wide_orbit.time wide_orbit.new = 0 c_int.in_dll(clibheartbeat, "hb_sun_collision_index").value = 0 sim.simulationarchive_snapshot(str(fn.with_suffix(".bin"))) extradata.meta.walltime = time.perf_counter() - start + walltimeoffset extradata.meta.cputime = time.process_time() + cputimeoffset extradata.meta.current_time = t extradata.history.append(energy=sim.calculate_energy(), momentum=total_momentum(sim), total_mass=total_mass(sim), time=sim.t, N=sim.N, N_active=sim.N_active) extradata.save(fn) if abort: print("aborted") exit(1) print("finished") fn.with_suffix(".lock").unlink()