コード例 #1
0
ファイル: preferences.py プロジェクト: brian-team/brian2
 def check_all_validated(self):
     '''
     Checks that all preferences that have been set have been validated.
     
     Logs a warning if not. Should be called by `Network.run` or other
     key Brian functions.
     '''
     if len(self.prefs_unvalidated):
         from brian2.utils.logger import get_logger
         logger = get_logger(__name__)
         logger.warn("The following preferences values have been set but "
                     "are not registered preferences:\n%s\nThis is usually "
                     "because of a spelling mistake or missing library "
                     "import." % ', '.join(self.prefs_unvalidated.keys()),
                     once=True)
コード例 #2
0
ファイル: preferences.py プロジェクト: ttxtea/brian2
 def check_all_validated(self):
     '''
     Checks that all preferences that have been set have been validated.
     
     Logs a warning if not. Should be called by `Network.run` or other
     key Brian functions.
     '''
     if len(self.prefs_unvalidated):
         from brian2.utils.logger import get_logger
         logger = get_logger(__name__)
         logger.warn("The following preferences values have been set but "
                     "are not registered preferences:\n%s\nThis is usually "
                     "because of a spelling mistake or missing library "
                     "import." % ', '.join(self.prefs_unvalidated.keys()),
                     once=True)
コード例 #3
0
ファイル: preferences.py プロジェクト: brian-team/brian2
    def load_preferences(self):
        """
        Load all the preference files, but do not validate them.
    
        Preference files are read in the following order:

        1. ``~/.brian/user_preferences`` from the user's home directory
        2. ``./brian_preferences`` from the current directory
        
        Files that are missing are ignored. Preferences read at each step
        override preferences from previous steps.
        
        See Also
        --------        
        read_preference_file
        """
        user_dir = os.path.join(os.path.expanduser('~'), '.brian')
        user_prefs = os.path.join(user_dir, 'user_preferences')
        cur_prefs = 'brian_preferences'

        files = [user_prefs, cur_prefs]
        for file in files:
            try:
                self.read_preference_file(file)
            except IOError:
                pass

        # The "default_preferences" file is no longer used, but we raise a
        # warning if it is present (note that we do this after reading the
        # preference files, since they can affect the preferences of the logger
        # itself)
        curdir, _ = os.path.split(__file__)
        basedir = os.path.normpath(os.path.join(curdir, '..'))
        default_prefs = os.path.join(basedir, 'default_preferences')
        if os.path.exists(default_prefs):
            from brian2.utils.logger import get_logger
            logger = get_logger(__name__)
            logger.warn(f"Brian no longer loads preferences from the "
                        f"'default_preferences' file (in '{basedir}'). Use a "
                        f"'user_preferences' file in "
                        f"'{user_dir}', "
                        f"or a 'brian_preferences' file in the current "
                        f"directory instead.",
                        name_suffix='deprecated_default_preferences',
                        once=True)
コード例 #4
0
ファイル: weave_rt.py プロジェクト: ttxtea/brian2
                                   AttributeVariable, AuxiliaryVariable,
                                   Subexpression)
from brian2.core.preferences import prefs, BrianPreference
from brian2.core.functions import DEFAULT_FUNCTIONS
from brian2.utils.logger import std_silent, get_logger

from ...codeobject import CodeObject
from ...templates import Templater
from ...generators.cpp_generator import CPPCodeGenerator
from ...targets import codegen_targets
from ...cpp_prefs import get_compiler_and_args

__all__ = ['WeaveCodeObject', 'WeaveCodeGenerator']


logger = get_logger(__name__)


def weave_data_type(dtype):
    '''
    Gives the C language specifier for numpy data types using weave. For example,
    ``numpy.int32`` maps to ``long`` in C.
    '''
    # this handles the case where int is specified, it will be int32 or int64
    # depending on platform
    if dtype is int:
        dtype = numpy.array([1]).dtype.type
    if dtype is float:
        dtype = numpy.array([1.]).dtype.type
    try:
        dtype = numpy.empty(0, dtype=dtype).dtype.char
コード例 #5
0
import time

import brian2
from brian2.tests.features import (Configuration, DefaultConfiguration,
                                   run_feature_tests, run_single_feature_test)
from brian2.utils.logger import get_logger
from brian2.devices import device, set_device, get_device
from brian2 import prefs
from brian2.tests.features.base import SpeedTest

try:
    import brian2genn
except ImportError:
    pass

logger = get_logger('brian2.devices.cuda_standalone.cuda_configuration')

__all__ = ['CUDAStandaloneConfiguration']


# Get information about the environment this script is run in
_slurm_cluster = os.environ.get("SLURM_CLUSTER_NAME", default=None)
_num_available_threads = len(os.sched_getaffinity(0))


SETUP_TIMER = '''
std::chrono::high_resolution_clock::time_point _benchmark_start, _benchmark_now;
_benchmark_start = std::chrono::high_resolution_clock::now();
std::ofstream _benchmark_file;
_benchmark_file.open("{fname}");
'''
コード例 #6
0
decorators (mainly "__host__ __device__") to allow operation in a CUDA context.
'''

from six import iteritems
from brian2.utils.stringtools import (deindent, stripped_deindented_lines,
                                      word_substitute)
from brian2.utils.logger import get_logger
from brian2.parsing.rendering import CPPNodeRenderer
from brian2.core.functions import Function, DEFAULT_FUNCTIONS
from brian2.core.preferences import prefs
from brian2.core.variables import ArrayVariable
from brian2.codegen.generators.base import CodeGenerator
from brian2.codegen.generators.cpp_generator import c_data_type
from brian2genn.insyn import check_pre_code

logger = get_logger('brian2.devices.genn')

__all__ = ['GeNNCodeGenerator']


def get_var_ndim(v, default_value=None):
    '''
    Helper function to get the ``ndim`` attribute of a `DynamicArrayVariable`,
    falling back to the previous name ``dimensions`` if necessary.

    Parameters
    ----------
    v : `ArrayVariable`
        The variable for which to retrieve the number of dimensions.
    default_value : optional
        A default value if the attribute does not exist
コード例 #7
0
ファイル: cuda_generator.py プロジェクト: nigroup/brian2cuda
from brian2.utils.logger import get_logger
from brian2.utils.stringtools import get_identifiers
from brian2.parsing.rendering import CPPNodeRenderer
from brian2.core.functions import Function, DEFAULT_FUNCTIONS
from brian2.core.preferences import prefs, BrianPreference
from brian2.core.variables import ArrayVariable
from brian2.core.core_preferences import default_float_dtype_validator, dtype_repr
from brian2.codegen.generators.cpp_generator import c_data_type
from brian2.codegen.generators.base import CodeGenerator

__all__ = ['CUDACodeGenerator',
           'CUDAAtomicsCodeGenerator'
           'c_data_type'
           ]

logger = get_logger('brian2.codegen.generators.cuda_generator')

class ParallelisationError(Exception):
    pass


# Preferences
prefs.register_preferences(
    'codegen.generators.cuda',
    'CUDA codegen preferences',

    default_functions_integral_convertion=BrianPreference(
        docs='''The floating point precision to which integral types will be converted when
        passed as arguments to default functions that have no integral type overload in device
        code (sin, cos, tan, sinh, cosh, tanh, exp, log, log10, sqrt, ceil, floor, arcsin, arccos, arctan)."
        NOTE: Convertion from 32bit and 64bit integral types to single precision (32bit) floating-point
コード例 #8
0
from brian2.codegen.cpp_prefs import get_compiler_and_args
from brian2.utils.logger import get_logger

from brian2.codegen.runtime.cython_rt.extension_manager import cython_extension_manager
try:
    import Cython
except ImportError:
    Cython = None

from .filterbank import Filterbank, RestructureFilterbank



__all__ = ['LinearFilterbank']

logger = get_logger('brian2.'+__name__) # bit of a hack, but fine

def _scipy_apply_linear_filterbank(b, a, x, zi):
    '''
    Parallel version of scipy lfilter command for a bank of n sequences of length 1
    
    In scipy.lfilter, you can apply a filter to multiple sounds at the same time,
    but you can't apply a bank of filters at the same time. This command does
    that. The coeffs b, a must be of shape (n,m,p), x must be of shape (s, n),
    and zi must be of shape (n,m-1,p). Here n is the number of channels in the
    filterbank, m is the order of the filter, p is the number of filters in
    a chain (cascade) to apply (you do first with (:,:,0) then (:,:,1), etc.),
    and s is the size of the buffer segment.
    '''
    alf_cache_b00 = [0]*zi.shape[2]
    alf_cache_a1 = [0]*zi.shape[2]
コード例 #9
0
ファイル: device.py プロジェクト: gitter-badger/brian2cuda
from brian2.parsing.rendering import CPPNodeRenderer
from brian2.devices.device import all_devices
from brian2.synapses.synapses import Synapses, SynapticPathway
from brian2.utils.filetools import copy_directory, ensure_directory
from brian2.codegen.generators.cpp_generator import c_data_type
from brian2.utils.logger import get_logger
from brian2.units import second

from .codeobject import CUDAStandaloneCodeObject
from brian2.devices.cpp_standalone.device import CPPWriter, CPPStandaloneDevice
from brian2.monitors.statemonitor import StateMonitor
from brian2.groups.neurongroup import Thresholder

__all__ = []

logger = get_logger('brian2.devices.cuda_standalone')

# Preferences
prefs.register_preferences(
    'devices.cuda_standalone',
    'CUDA standalone preferences',
    SM_multiplier=BrianPreference(
        default=1,
        docs='''
        The number of blocks per SM. By default, this value is set to 1.
        ''',
    ),
    random_number_generator_type=BrianPreference(
        docs=
        '''Generator type (str) that cuRAND uses for random number generation.
            Setting the generator type automatically resets the generator ordering
コード例 #10
0
ファイル: cuda_prefs.py プロジェクト: brian-team/brian2cuda
'''
Preferences that relate to the brian2cuda interface.
'''
import numpy as np

from brian2.core.preferences import prefs, BrianPreference
from brian2.core.core_preferences import default_float_dtype_validator, dtype_repr
from brian2.utils.logger import get_logger

logger = get_logger('brian2.devices.cuda_standalone.cuda_prefs')


def validate_bundle_size_expression(string):
    known_vars = ['mean', 'std', 'max', 'min']
    try:
        # Try formatting all known_vars with 0
        formatted = string.format(**dict(zip(known_vars, [0] *
                                             len(known_vars))))
    except KeyError as error:
        logger.error(
            f"Unknown formatting variable {error}. Known variables are:"
            f" {known_vars}")
        return False

    # Replase names from C++ std with numpy version for eval test below
    formatted = formatted.replace("ceil", "np.ceil")
    formatted = formatted.replace("floor", "np.floor")

    try:
        eval(formatted)
    except Exception:
コード例 #11
0
'''

import itertools
import numpy
from brian2.utils.stringtools import (deindent, stripped_deindented_lines,
                                      word_substitute)
from brian2.utils.logger import get_logger
from brian2.parsing.rendering import CPPNodeRenderer
from brian2.core.functions import Function, DEFAULT_FUNCTIONS
from brian2.core.preferences import prefs, BrianPreference
from brian2.core.variables import ArrayVariable
from brian2.codegen.generators.base import CodeGenerator
from brian2.codegen.generators.cpp_generator import c_data_type, CPPCodeGenerator
from brian2genn.insyn import check_pre_code

logger = get_logger('brian2.devices.genn')

__all__ = ['GeNNCodeGenerator'
           ]

class GeNNCodeGenerator(CodeGenerator):
    '''
    "GeNN language"
    
    For user-defined functions, there are two keys to provide:
    
    ``support_code``
        The function definition which will be added to the support code.
    ``hashdefine_code``
        The ``#define`` code added to the main loop.
    '''
コード例 #12
0
ファイル: test_logger.py プロジェクト: brian-team/brian2
import multiprocessing
import os

from brian2.utils.logger import BrianLogger, get_logger
from brian2.core.preferences import prefs

import pytest

logger = get_logger('brian2.tests.test_logger')

@pytest.mark.codegen_independent
def test_file_logging():
    logger.error('error message xxx')
    logger.warn('warning message xxx')
    logger.info('info message xxx')
    logger.debug('debug message xxx')
    logger.diagnostic('diagnostic message xxx')
    BrianLogger.file_handler.flush()
    # By default, only >= debug messages should show up
    assert os.path.isfile(BrianLogger.tmp_log)
    with open(BrianLogger.tmp_log, 'r') as f:
        log_content = f.readlines()
    for level, line in zip(['error', 'warning', 'info', 'debug'], log_content[-4:]):
        assert 'brian2.tests.test_logger' in line
        assert f"{level} message xxx" in line
        assert level.upper() in line

def run_in_process(x):
    logger.info(f"subprocess info message {x}")

def run_in_process_with_logger(x):