예제 #1
0
파일: IO.py 프로젝트: ANNarchy/ANNarchy
def load_parameters(filename, global_only=True, verbose=False, net_id=0):
    """
    Loads the global parameters of a network (flag ``population`` for neurons, ``projection`` for synapses) from a JSON file.

    *Parameters:*

    * **filename:** path to the JSON file.
    * **global_only:** True if only global parameters (flags ``population`` and ``projection``) should be loaded, the other values are ignored. (default: True)
    * **verbose**: True if the old and new values of the parameters should be printed (default: False).
    * **net_id:** ID of the network (default: 0, the global network).

    *Returns:*

    * a dictionary of additional parameters not related to populations or projections (keyword ``network`` in the JSON file).

    It is advised to generate the JSON file first with ``save_parameters()`` and later edit it manually.

    A strong restriction is that population/projection names cannot change between saving and loading.
    By default, they take names such as ``pop0`` or ``proj2``, we advise setting explicitly a name in their constructor for readability.

    If you add a parameter name to the JSON file but it does not exist in te neuron/synapse, it will be silently skipped.
    Enable ``verbose=True`` to see which parameters are effectively changed.

    If you set ``global_only`` to True, you will be able to set values for non-global parameters (e.g. synapse-specific), but a single value will be loaded for all.
    The JSON file cannot contain arrays.

    If you want to save/load the value of variables after a simulation, please refer to ``save()`` or ``load()``.
    """
    import json
    with open('network.json', 'r') as rfile:
        desc = json.load(rfile)

    if verbose:
        Global._print('Loading parameters from file', filename)
        Global._print('-'*40)

    # Populations
    try:
        populations = desc['populations']
    except:
        populations = {}
        if verbose:
            Global._print('load_parameters(): no population parameters.')
    for name, parameters in populations.items():
        # Get the population
        for pop in Global._network[net_id]['populations']:
            if pop.name == name:
                population = pop
                break
        else:
            Global._warning('The population', name, 'defined in the file', filename, 'does not exist in the current network.')

        if verbose:
            Global._print('Population', name)

        # Set the parameters
        for name, val in parameters.items():
            # Check that the variable indeed exists
            if not name in population.parameters:
                Global._print('  ', name, 'is not a global parameter of', population.name, ', skipping.')
                continue
            if global_only and not name in population.neuron_type.description['global']:
                Global._print('  ', name, 'is not a global parameter of', population.name, ', skipping.')
                continue

            if verbose:
                Global._print('  ', name, ':', population.get(name), '->', val)

            population.set({name: float(val)})

    # Projections
    try:
        projections = desc['projections']
    except:
        projections = {}
        if verbose:
            Global._print('load_parameters(): no projection parameters.')
    for name, parameters in projections.items():
        # Get the projection
        for proj in Global._network[net_id]['projections']:
            if proj.name == name:
                projection = proj
                break
        else:
            Global._warning('The projection', name, 'defined in the file', filename, 'does not exist in the current network.')

        if verbose:
            Global._print('Projection', name)

        # Set the parameters
        for name, val in parameters.items():
            # Check that the variable indeed exists
            if not name in projection.parameters:
                Global._print('  ', name, 'is not a global parameter of', population.name, ', skipping.')
                continue
            if global_only and not name in projection.synapse_type.description['global']:
                Global._print('  ', name, 'is not a global parameter of', population.name, ', skipping.')
                continue

            if verbose:
                Global._print('  ', name, ':', projection.get(name), '->', val)

            projection.set({name: float(val)})

    # Constants
    try:
        constants = desc['constants']
    except:
        constants = {}
        if verbose:
            Global._print('load_parameters(): no constants.')
    for name, value in constants.items():
        if name in Global.list_constants(): # modify it
            Global.get_constant(name).value = value
        else: # create it
            _ = Global.Constant(name, value)

    # Global user-defined parameters
    try:
        network_parameters = {}
        for name, val in desc['network'].items():
            network_parameters[name] = float(val)
    except:
        network_parameters = {}

    return network_parameters
예제 #2
0
def extract_boundsflags(constraint, equation="", extra_values={}):
    # Process the flags if any
    bounds, flags = extract_flags(constraint)

    # Get the type of the variable (float/int/bool)
    if 'int' in flags:
        ctype = 'int'
    elif 'bool' in flags:
        ctype = 'bool'
    else:
        ctype = Global.config['precision']

    # Get the init value if declared
    if 'init' in bounds.keys():  # Variables: explicitely set in init=xx
        init = bounds['init']
        if ctype == 'bool':
            if init in ['false', 'False', '0']:
                init = False
            elif init in ['true', 'True', '1']:
                init = True
        elif init in Global.list_constants():
            init = Global.get_constant(init)
        elif ctype == 'int':
            init = int(init)
        else:
            init = float(init)

    elif '=' in equation:  # Parameters: the value is in the equation
        init = equation.split('=')[1].strip()

        # Boolean
        if init in ['false', 'False']:
            init = False
            ctype = 'bool'
        elif init in ['true', 'True']:
            init = True
            ctype = 'bool'
        # Constants
        elif init in Global.list_constants():
            init = Global.get_constant(init)
        # Extra-args (obsolete)
        elif init.strip().startswith("'"):
            var = init.replace("'", "")
            init = extra_values[var]
        # Integers
        elif ctype == 'int':
            try:
                init = eval('int(' + init + ')')
            except:
                Global._print(equation)
                Global._error('The value of the parameter is not an integer.')
        # Floats
        else:
            try:
                init = eval('float(' + init + ')')
            except:
                Global._print(equation)
                Global._error('The value of the parameter is not a float.')

    else:  # Default = 0 according to ctype
        if ctype == 'bool':
            init = False
        elif ctype == 'int':
            init = 0
        elif ctype == 'double' or ctype == 'float':
            init = 0.0

    return bounds, flags, ctype, init
예제 #3
0
파일: IO.py 프로젝트: vitay/ANNarchy
def load_parameters(filename, global_only=True, verbose=False, net_id=0):
    """
    Loads the global parameters of a network (flag ``population`` for neurons, ``projection`` for synapses) from a JSON file.

    It is advised to generate the JSON file first with ``save_parameters()`` and later edit it manually.

    A strong restriction is that population/projection names cannot change between saving and loading.
    By default, they take names such as ``pop0`` or ``proj2``, we advise setting explicitly a name in their constructor for readability.

    If you add a parameter name to the JSON file but it does not exist in te neuron/synapse, it will be silently skipped.
    Enable ``verbose=True`` to see which parameters are effectively changed.

    If you set ``global_only`` to True, you will be able to set values for non-global parameters (e.g. synapse-specific), but a single value will be loaded for all.
    The JSON file cannot contain arrays.

    If you want to save/load the value of variables after a simulation, please refer to ``save()`` or ``load()``.

    :param filename: path to the JSON file.
    :param global_only: True if only global parameters (flags ``population`` and ``projection``) should be loaded, the other values are ignored. (default: True)
    :param verbose: True if the old and new values of the parameters should be printed (default: False).
    :param net_id: ID of the network (default: 0, the global network).
    :return: a dictionary of additional parameters not related to populations or projections (keyword ``network`` in the JSON file).

    """
    import json
    with open(filename, 'r') as rfile:
        desc = json.load(rfile)

    if verbose:
        Global._print('Loading parameters from file', filename)
        Global._print('-' * 40)

    # Populations
    try:
        populations = desc['populations']
    except:
        populations = {}
        if verbose:
            Global._print('load_parameters(): no population parameters.')
    for name, parameters in populations.items():
        # Get the population
        for pop in Global._network[net_id]['populations']:
            if pop.name == name:
                population = pop
                break
        else:
            Global._warning('The population', name, 'defined in the file',
                            filename, 'does not exist in the current network.')

        if verbose:
            Global._print('Population', name)

        # Set the parameters
        for name, val in parameters.items():
            # Check that the variable indeed exists
            if not name in population.parameters:
                Global._print('  ', name, 'is not a global parameter of',
                              population.name, ', skipping.')
                continue
            if global_only and not name in population.neuron_type.description[
                    'global']:
                Global._print('  ', name, 'is not a global parameter of',
                              population.name, ', skipping.')
                continue

            if verbose:
                Global._print('  ', name, ':', population.get(name), '->', val)

            population.set({name: float(val)})

    # Projections
    try:
        projections = desc['projections']
    except:
        projections = {}
        if verbose:
            Global._print('load_parameters(): no projection parameters.')
    for name, parameters in projections.items():
        # Get the projection
        for proj in Global._network[net_id]['projections']:
            if proj.name == name:
                projection = proj
                break
        else:
            Global._warning('The projection', name, 'defined in the file',
                            filename, 'does not exist in the current network.')

        if verbose:
            Global._print('Projection', name)

        # Set the parameters
        for name, val in parameters.items():
            # Check that the variable indeed exists
            if not name in projection.parameters:
                Global._print('  ', name, 'is not a global parameter of',
                              population.name, ', skipping.')
                continue
            if global_only and not name in projection.synapse_type.description[
                    'global']:
                Global._print('  ', name, 'is not a global parameter of',
                              population.name, ', skipping.')
                continue

            if verbose:
                Global._print('  ', name, ':', projection.get(name), '->', val)

            projection.set({name: float(val)})

    # Constants
    try:
        constants = desc['constants']
    except:
        constants = {}
        if verbose:
            Global._print('load_parameters(): no constants.')
    for name, value in constants.items():
        if name in Global.list_constants():  # modify it
            Global.get_constant(name).value = value
        else:  # create it
            _ = Global.Constant(name, value)

    # Global user-defined parameters
    try:
        network_parameters = {}
        for name, val in desc['network'].items():
            network_parameters[name] = float(val)
    except:
        network_parameters = {}

    return network_parameters
예제 #4
0
def extract_boundsflags(constraint, equation ="", extra_values={}):
        # Process the flags if any
        bounds, flags = extract_flags(constraint)

        # Get the type of the variable (float/int/bool)
        if 'int' in flags:
            ctype = 'int'
        elif 'bool' in flags:
            ctype = 'bool'
        else:
            ctype = Global.config['precision']

        # Get the init value if declared
        if 'init' in bounds.keys(): # Variables: explicitely set in init=xx
            init = bounds['init']
            if ctype == 'bool':
                if init in ['false', 'False', '0']:
                    init = False
                elif init in ['true', 'True', '1']:
                    init = True
            elif init in Global.list_constants():
                init = Global.get_constant(init)
            elif ctype == 'int':
                init = int(init)
            else:
                init = float(init)

        elif '=' in equation: # Parameters: the value is in the equation
            init = equation.split('=')[1].strip()

            # Boolean
            if init in ['false', 'False']:
                init = False
                ctype = 'bool'
            elif init in ['true', 'True']:
                init = True
                ctype = 'bool'
            # Constants
            elif init in Global.list_constants():
                init = Global.get_constant(init)
            # Extra-args (obsolete)
            elif init.strip().startswith("'"):   
                var = init.replace("'","")
                init = extra_values[var]
            # Integers
            elif ctype == 'int':
                try:
                    init = eval('int(' + init + ')')
                except:
                    Global._print(equation)
                    Global._error('The value of the parameter is not an integer.')
            # Floats
            else:
                try:
                    init = eval('float(' + init + ')')
                except:
                    Global._print(equation)
                    Global._error('The value of the parameter is not a float.')

        else: # Default = 0 according to ctype
            if ctype == 'bool':
                init = False
            elif ctype == 'int':
                init = 0
            elif ctype == 'double' or ctype == 'float':
                init = 0.0

        return bounds, flags, ctype, init