partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
get_parser
Return appropriate parser for given type. :param typ: Type to get parser for. :return function: Parser
bananas/environment.py
def get_parser(typ): """ Return appropriate parser for given type. :param typ: Type to get parser for. :return function: Parser """ try: return { str: parse_str, bool: parse_bool, int: parse_int, tuple: parse_tuple, list: parse_list, set: parse_set, }[typ] except KeyError: raise NotImplementedError("Unsupported setting type: %r", typ)
def get_parser(typ): """ Return appropriate parser for given type. :param typ: Type to get parser for. :return function: Parser """ try: return { str: parse_str, bool: parse_bool, int: parse_int, tuple: parse_tuple, list: parse_list, set: parse_set, }[typ] except KeyError: raise NotImplementedError("Unsupported setting type: %r", typ)
[ "Return", "appropriate", "parser", "for", "given", "type", "." ]
5monkeys/django-bananas
python
https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/environment.py#L87-L104
[ "def", "get_parser", "(", "typ", ")", ":", "try", ":", "return", "{", "str", ":", "parse_str", ",", "bool", ":", "parse_bool", ",", "int", ":", "parse_int", ",", "tuple", ":", "parse_tuple", ",", "list", ":", "parse_list", ",", "set", ":", "parse_set", ",", "}", "[", "typ", "]", "except", "KeyError", ":", "raise", "NotImplementedError", "(", "\"Unsupported setting type: %r\"", ",", "typ", ")" ]
cfd318c737f6c4580036c13d2acf32bca96654bf
test
get_settings
Get and parse prefixed django settings from env. TODO: Implement support for complex settings DATABASES = {} CACHES = {} INSTALLED_APPS -> EXCLUDE_APPS ? :return dict:
bananas/environment.py
def get_settings(): """ Get and parse prefixed django settings from env. TODO: Implement support for complex settings DATABASES = {} CACHES = {} INSTALLED_APPS -> EXCLUDE_APPS ? :return dict: """ settings = {} prefix = environ.get("DJANGO_SETTINGS_PREFIX", "DJANGO_") for key, value in environ.items(): _, _, key = key.partition(prefix) if key: if key in UNSUPPORTED_ENV_SETTINGS: raise ValueError( 'Django setting "{}" can not be ' "configured through environment.".format(key) ) default_value = getattr(global_settings, key, UNDEFINED) if default_value is not UNDEFINED: if default_value is None and key in SETTINGS_TYPES.keys(): # Handle typed django settings defaulting to None parse = get_parser(SETTINGS_TYPES[key]) else: # Determine parser by django setting type parse = get_parser(type(default_value)) value = parse(value) settings[key] = value return settings
def get_settings(): """ Get and parse prefixed django settings from env. TODO: Implement support for complex settings DATABASES = {} CACHES = {} INSTALLED_APPS -> EXCLUDE_APPS ? :return dict: """ settings = {} prefix = environ.get("DJANGO_SETTINGS_PREFIX", "DJANGO_") for key, value in environ.items(): _, _, key = key.partition(prefix) if key: if key in UNSUPPORTED_ENV_SETTINGS: raise ValueError( 'Django setting "{}" can not be ' "configured through environment.".format(key) ) default_value = getattr(global_settings, key, UNDEFINED) if default_value is not UNDEFINED: if default_value is None and key in SETTINGS_TYPES.keys(): # Handle typed django settings defaulting to None parse = get_parser(SETTINGS_TYPES[key]) else: # Determine parser by django setting type parse = get_parser(type(default_value)) value = parse(value) settings[key] = value return settings
[ "Get", "and", "parse", "prefixed", "django", "settings", "from", "env", "." ]
5monkeys/django-bananas
python
https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/environment.py#L107-L144
[ "def", "get_settings", "(", ")", ":", "settings", "=", "{", "}", "prefix", "=", "environ", ".", "get", "(", "\"DJANGO_SETTINGS_PREFIX\"", ",", "\"DJANGO_\"", ")", "for", "key", ",", "value", "in", "environ", ".", "items", "(", ")", ":", "_", ",", "_", ",", "key", "=", "key", ".", "partition", "(", "prefix", ")", "if", "key", ":", "if", "key", "in", "UNSUPPORTED_ENV_SETTINGS", ":", "raise", "ValueError", "(", "'Django setting \"{}\" can not be '", "\"configured through environment.\"", ".", "format", "(", "key", ")", ")", "default_value", "=", "getattr", "(", "global_settings", ",", "key", ",", "UNDEFINED", ")", "if", "default_value", "is", "not", "UNDEFINED", ":", "if", "default_value", "is", "None", "and", "key", "in", "SETTINGS_TYPES", ".", "keys", "(", ")", ":", "# Handle typed django settings defaulting to None", "parse", "=", "get_parser", "(", "SETTINGS_TYPES", "[", "key", "]", ")", "else", ":", "# Determine parser by django setting type", "parse", "=", "get_parser", "(", "type", "(", "default_value", ")", ")", "value", "=", "parse", "(", "value", ")", "settings", "[", "key", "]", "=", "value", "return", "settings" ]
cfd318c737f6c4580036c13d2acf32bca96654bf
test
ModelDict.from_model
Work-in-progress constructor, consuming fields and values from django model instance.
bananas/models.py
def from_model(cls, model, *fields, **named_fields): """ Work-in-progress constructor, consuming fields and values from django model instance. """ d = ModelDict() if not (fields or named_fields): # Default to all fields fields = [f.attname for f in model._meta.concrete_fields] not_found = object() for name, field in chain(zip(fields, fields), named_fields.items()): _fields = field.split("__") value = model for i, _field in enumerate(_fields, start=1): # NOTE: we don't want to rely on hasattr here previous_value = value value = getattr(previous_value, _field, not_found) if value is not_found: if _field in dir(previous_value): raise ValueError( "{!r}.{} had an AttributeError exception".format( previous_value, _field ) ) else: raise AttributeError( "{!r} does not have {!r} attribute".format( previous_value, _field ) ) elif value is None: if name not in named_fields: name = "__".join(_fields[:i]) break d[name] = value return d
def from_model(cls, model, *fields, **named_fields): """ Work-in-progress constructor, consuming fields and values from django model instance. """ d = ModelDict() if not (fields or named_fields): # Default to all fields fields = [f.attname for f in model._meta.concrete_fields] not_found = object() for name, field in chain(zip(fields, fields), named_fields.items()): _fields = field.split("__") value = model for i, _field in enumerate(_fields, start=1): # NOTE: we don't want to rely on hasattr here previous_value = value value = getattr(previous_value, _field, not_found) if value is not_found: if _field in dir(previous_value): raise ValueError( "{!r}.{} had an AttributeError exception".format( previous_value, _field ) ) else: raise AttributeError( "{!r} does not have {!r} attribute".format( previous_value, _field ) ) elif value is None: if name not in named_fields: name = "__".join(_fields[:i]) break d[name] = value return d
[ "Work", "-", "in", "-", "progress", "constructor", "consuming", "fields", "and", "values", "from", "django", "model", "instance", "." ]
5monkeys/django-bananas
python
https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/models.py#L83-L125
[ "def", "from_model", "(", "cls", ",", "model", ",", "*", "fields", ",", "*", "*", "named_fields", ")", ":", "d", "=", "ModelDict", "(", ")", "if", "not", "(", "fields", "or", "named_fields", ")", ":", "# Default to all fields", "fields", "=", "[", "f", ".", "attname", "for", "f", "in", "model", ".", "_meta", ".", "concrete_fields", "]", "not_found", "=", "object", "(", ")", "for", "name", ",", "field", "in", "chain", "(", "zip", "(", "fields", ",", "fields", ")", ",", "named_fields", ".", "items", "(", ")", ")", ":", "_fields", "=", "field", ".", "split", "(", "\"__\"", ")", "value", "=", "model", "for", "i", ",", "_field", "in", "enumerate", "(", "_fields", ",", "start", "=", "1", ")", ":", "# NOTE: we don't want to rely on hasattr here", "previous_value", "=", "value", "value", "=", "getattr", "(", "previous_value", ",", "_field", ",", "not_found", ")", "if", "value", "is", "not_found", ":", "if", "_field", "in", "dir", "(", "previous_value", ")", ":", "raise", "ValueError", "(", "\"{!r}.{} had an AttributeError exception\"", ".", "format", "(", "previous_value", ",", "_field", ")", ")", "else", ":", "raise", "AttributeError", "(", "\"{!r} does not have {!r} attribute\"", ".", "format", "(", "previous_value", ",", "_field", ")", ")", "elif", "value", "is", "None", ":", "if", "name", "not", "in", "named_fields", ":", "name", "=", "\"__\"", ".", "join", "(", "_fields", "[", ":", "i", "]", ")", "break", "d", "[", "name", "]", "=", "value", "return", "d" ]
cfd318c737f6c4580036c13d2acf32bca96654bf
test
URLSecretField.y64_encode
Implementation of Y64 non-standard URL-safe base64 variant. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table :return: base64-encoded result with substituted ``{"+", "/", "="} => {".", "_", "-"}``.
bananas/models.py
def y64_encode(s): """ Implementation of Y64 non-standard URL-safe base64 variant. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table :return: base64-encoded result with substituted ``{"+", "/", "="} => {".", "_", "-"}``. """ first_pass = base64.urlsafe_b64encode(s) return first_pass.translate(bytes.maketrans(b"+/=", b"._-"))
def y64_encode(s): """ Implementation of Y64 non-standard URL-safe base64 variant. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table :return: base64-encoded result with substituted ``{"+", "/", "="} => {".", "_", "-"}``. """ first_pass = base64.urlsafe_b64encode(s) return first_pass.translate(bytes.maketrans(b"+/=", b"._-"))
[ "Implementation", "of", "Y64", "non", "-", "standard", "URL", "-", "safe", "base64", "variant", "." ]
5monkeys/django-bananas
python
https://github.com/5monkeys/django-bananas/blob/cfd318c737f6c4580036c13d2acf32bca96654bf/bananas/models.py#L247-L257
[ "def", "y64_encode", "(", "s", ")", ":", "first_pass", "=", "base64", ".", "urlsafe_b64encode", "(", "s", ")", "return", "first_pass", ".", "translate", "(", "bytes", ".", "maketrans", "(", "b\"+/=\"", ",", "b\"._-\"", ")", ")" ]
cfd318c737f6c4580036c13d2acf32bca96654bf
test
create_field
Create a field by field info dict.
validator/fields.py
def create_field(field_info): """ Create a field by field info dict. """ field_type = field_info.get('type') if field_type not in FIELDS_NAME_MAP: raise ValueError(_('not support this field: {}').format(field_type)) field_class = FIELDS_NAME_MAP.get(field_type) params = dict(field_info) params.pop('type') return field_class.from_dict(params)
def create_field(field_info): """ Create a field by field info dict. """ field_type = field_info.get('type') if field_type not in FIELDS_NAME_MAP: raise ValueError(_('not support this field: {}').format(field_type)) field_class = FIELDS_NAME_MAP.get(field_type) params = dict(field_info) params.pop('type') return field_class.from_dict(params)
[ "Create", "a", "field", "by", "field", "info", "dict", "." ]
ausaki/python-validator
python
https://github.com/ausaki/python-validator/blob/a3e591b1eae6d7a70f894c203dbd7195f929baa8/validator/fields.py#L29-L39
[ "def", "create_field", "(", "field_info", ")", ":", "field_type", "=", "field_info", ".", "get", "(", "'type'", ")", "if", "field_type", "not", "in", "FIELDS_NAME_MAP", ":", "raise", "ValueError", "(", "_", "(", "'not support this field: {}'", ")", ".", "format", "(", "field_type", ")", ")", "field_class", "=", "FIELDS_NAME_MAP", ".", "get", "(", "field_type", ")", "params", "=", "dict", "(", "field_info", ")", "params", ".", "pop", "(", "'type'", ")", "return", "field_class", ".", "from_dict", "(", "params", ")" ]
a3e591b1eae6d7a70f894c203dbd7195f929baa8
test
create_validator
create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance
validator/validator.py
def create_validator(data_struct_dict, name=None): """ create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance """ if name is None: name = 'FromDictValidator' attrs = {} for field_name, field_info in six.iteritems(data_struct_dict): field_type = field_info['type'] if field_type == DictField.FIELD_TYPE_NAME and isinstance(field_info.get('validator'), dict): field_info['validator'] = create_validator(field_info['validator']) attrs[field_name] = create_field(field_info) name = force_str(name) return type(name, (Validator, ), attrs)
def create_validator(data_struct_dict, name=None): """ create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance """ if name is None: name = 'FromDictValidator' attrs = {} for field_name, field_info in six.iteritems(data_struct_dict): field_type = field_info['type'] if field_type == DictField.FIELD_TYPE_NAME and isinstance(field_info.get('validator'), dict): field_info['validator'] = create_validator(field_info['validator']) attrs[field_name] = create_field(field_info) name = force_str(name) return type(name, (Validator, ), attrs)
[ "create", "a", "Validator", "instance", "from", "data_struct_dict" ]
ausaki/python-validator
python
https://github.com/ausaki/python-validator/blob/a3e591b1eae6d7a70f894c203dbd7195f929baa8/validator/validator.py#L138-L157
[ "def", "create_validator", "(", "data_struct_dict", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'FromDictValidator'", "attrs", "=", "{", "}", "for", "field_name", ",", "field_info", "in", "six", ".", "iteritems", "(", "data_struct_dict", ")", ":", "field_type", "=", "field_info", "[", "'type'", "]", "if", "field_type", "==", "DictField", ".", "FIELD_TYPE_NAME", "and", "isinstance", "(", "field_info", ".", "get", "(", "'validator'", ")", ",", "dict", ")", ":", "field_info", "[", "'validator'", "]", "=", "create_validator", "(", "field_info", "[", "'validator'", "]", ")", "attrs", "[", "field_name", "]", "=", "create_field", "(", "field_info", ")", "name", "=", "force_str", "(", "name", ")", "return", "type", "(", "name", ",", "(", "Validator", ",", ")", ",", "attrs", ")" ]
a3e591b1eae6d7a70f894c203dbd7195f929baa8
test
cartesian_product
Generates a Cartesian product of the input parameter dictionary. For example: >>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]}) {'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]} :param parameter_dict: Dictionary containing parameter names as keys and iterables of data to explore. :param combined_parameters: Tuple of tuples. Defines the order of the parameters and parameters that are linked together. If an inner tuple contains only a single item, you can spare the inner tuple brackets. For example: >>> print cartesian_product( {'param1': [42.0, 52.5], 'param2':['a', 'b'], 'param3' : [1,2,3]}, ('param3',('param1', 'param2'))) {param3':[1,1,2,2,3,3],'param1' : [42.0,52.5,42.0,52.5,42.0,52.5], 'param2':['a','b','a','b','a','b']} :returns: Dictionary with cartesian product lists.
pypet/utils/explore.py
def cartesian_product(parameter_dict, combined_parameters=()): """ Generates a Cartesian product of the input parameter dictionary. For example: >>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]}) {'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]} :param parameter_dict: Dictionary containing parameter names as keys and iterables of data to explore. :param combined_parameters: Tuple of tuples. Defines the order of the parameters and parameters that are linked together. If an inner tuple contains only a single item, you can spare the inner tuple brackets. For example: >>> print cartesian_product( {'param1': [42.0, 52.5], 'param2':['a', 'b'], 'param3' : [1,2,3]}, ('param3',('param1', 'param2'))) {param3':[1,1,2,2,3,3],'param1' : [42.0,52.5,42.0,52.5,42.0,52.5], 'param2':['a','b','a','b','a','b']} :returns: Dictionary with cartesian product lists. """ if not combined_parameters: combined_parameters = list(parameter_dict) else: combined_parameters = list(combined_parameters) for idx, item in enumerate(combined_parameters): if isinstance(item, str): combined_parameters[idx] = (item,) iterator_list = [] for item_tuple in combined_parameters: inner_iterator_list = [parameter_dict[key] for key in item_tuple] zipped_iterator = zip(*inner_iterator_list) iterator_list.append(zipped_iterator) result_dict = {} for key in parameter_dict: result_dict[key] = [] cartesian_iterator = itools.product(*iterator_list) for cartesian_tuple in cartesian_iterator: for idx, item_tuple in enumerate(combined_parameters): for inneridx, key in enumerate(item_tuple): result_dict[key].append(cartesian_tuple[idx][inneridx]) return result_dict
def cartesian_product(parameter_dict, combined_parameters=()): """ Generates a Cartesian product of the input parameter dictionary. For example: >>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]}) {'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]} :param parameter_dict: Dictionary containing parameter names as keys and iterables of data to explore. :param combined_parameters: Tuple of tuples. Defines the order of the parameters and parameters that are linked together. If an inner tuple contains only a single item, you can spare the inner tuple brackets. For example: >>> print cartesian_product( {'param1': [42.0, 52.5], 'param2':['a', 'b'], 'param3' : [1,2,3]}, ('param3',('param1', 'param2'))) {param3':[1,1,2,2,3,3],'param1' : [42.0,52.5,42.0,52.5,42.0,52.5], 'param2':['a','b','a','b','a','b']} :returns: Dictionary with cartesian product lists. """ if not combined_parameters: combined_parameters = list(parameter_dict) else: combined_parameters = list(combined_parameters) for idx, item in enumerate(combined_parameters): if isinstance(item, str): combined_parameters[idx] = (item,) iterator_list = [] for item_tuple in combined_parameters: inner_iterator_list = [parameter_dict[key] for key in item_tuple] zipped_iterator = zip(*inner_iterator_list) iterator_list.append(zipped_iterator) result_dict = {} for key in parameter_dict: result_dict[key] = [] cartesian_iterator = itools.product(*iterator_list) for cartesian_tuple in cartesian_iterator: for idx, item_tuple in enumerate(combined_parameters): for inneridx, key in enumerate(item_tuple): result_dict[key].append(cartesian_tuple[idx][inneridx]) return result_dict
[ "Generates", "a", "Cartesian", "product", "of", "the", "input", "parameter", "dictionary", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/explore.py#L9-L63
[ "def", "cartesian_product", "(", "parameter_dict", ",", "combined_parameters", "=", "(", ")", ")", ":", "if", "not", "combined_parameters", ":", "combined_parameters", "=", "list", "(", "parameter_dict", ")", "else", ":", "combined_parameters", "=", "list", "(", "combined_parameters", ")", "for", "idx", ",", "item", "in", "enumerate", "(", "combined_parameters", ")", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "combined_parameters", "[", "idx", "]", "=", "(", "item", ",", ")", "iterator_list", "=", "[", "]", "for", "item_tuple", "in", "combined_parameters", ":", "inner_iterator_list", "=", "[", "parameter_dict", "[", "key", "]", "for", "key", "in", "item_tuple", "]", "zipped_iterator", "=", "zip", "(", "*", "inner_iterator_list", ")", "iterator_list", ".", "append", "(", "zipped_iterator", ")", "result_dict", "=", "{", "}", "for", "key", "in", "parameter_dict", ":", "result_dict", "[", "key", "]", "=", "[", "]", "cartesian_iterator", "=", "itools", ".", "product", "(", "*", "iterator_list", ")", "for", "cartesian_tuple", "in", "cartesian_iterator", ":", "for", "idx", ",", "item_tuple", "in", "enumerate", "(", "combined_parameters", ")", ":", "for", "inneridx", ",", "key", "in", "enumerate", "(", "item_tuple", ")", ":", "result_dict", "[", "key", "]", ".", "append", "(", "cartesian_tuple", "[", "idx", "]", "[", "inneridx", "]", ")", "return", "result_dict" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
find_unique_points
Takes a list of explored parameters and finds unique parameter combinations. If parameter ranges are hashable operates in O(N), otherwise O(N**2). :param explored_parameters: List of **explored** parameters :return: List of tuples, first entry being the parameter values, second entry a list containing the run position of the unique combination.
pypet/utils/explore.py
def find_unique_points(explored_parameters): """Takes a list of explored parameters and finds unique parameter combinations. If parameter ranges are hashable operates in O(N), otherwise O(N**2). :param explored_parameters: List of **explored** parameters :return: List of tuples, first entry being the parameter values, second entry a list containing the run position of the unique combination. """ ranges = [param.f_get_range(copy=False) for param in explored_parameters] zipped_tuples = list(zip(*ranges)) try: unique_elements = OrderedDict() for idx, val_tuple in enumerate(zipped_tuples): if val_tuple not in unique_elements: unique_elements[val_tuple] = [] unique_elements[val_tuple].append(idx) return list(unique_elements.items()) except TypeError: logger = logging.getLogger('pypet.find_unique') logger.error('Your parameter entries could not be hashed, ' 'now I am sorting slowly in O(N**2).') unique_elements = [] for idx, val_tuple in enumerate(zipped_tuples): matches = False for added_tuple, pos_list in unique_elements: matches = True for idx2, val in enumerate(added_tuple): if not explored_parameters[idx2]._equal_values(val_tuple[idx2], val): matches = False break if matches: pos_list.append(idx) break if not matches: unique_elements.append((val_tuple, [idx])) return unique_elements
def find_unique_points(explored_parameters): """Takes a list of explored parameters and finds unique parameter combinations. If parameter ranges are hashable operates in O(N), otherwise O(N**2). :param explored_parameters: List of **explored** parameters :return: List of tuples, first entry being the parameter values, second entry a list containing the run position of the unique combination. """ ranges = [param.f_get_range(copy=False) for param in explored_parameters] zipped_tuples = list(zip(*ranges)) try: unique_elements = OrderedDict() for idx, val_tuple in enumerate(zipped_tuples): if val_tuple not in unique_elements: unique_elements[val_tuple] = [] unique_elements[val_tuple].append(idx) return list(unique_elements.items()) except TypeError: logger = logging.getLogger('pypet.find_unique') logger.error('Your parameter entries could not be hashed, ' 'now I am sorting slowly in O(N**2).') unique_elements = [] for idx, val_tuple in enumerate(zipped_tuples): matches = False for added_tuple, pos_list in unique_elements: matches = True for idx2, val in enumerate(added_tuple): if not explored_parameters[idx2]._equal_values(val_tuple[idx2], val): matches = False break if matches: pos_list.append(idx) break if not matches: unique_elements.append((val_tuple, [idx])) return unique_elements
[ "Takes", "a", "list", "of", "explored", "parameters", "and", "finds", "unique", "parameter", "combinations", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/explore.py#L66-L108
[ "def", "find_unique_points", "(", "explored_parameters", ")", ":", "ranges", "=", "[", "param", ".", "f_get_range", "(", "copy", "=", "False", ")", "for", "param", "in", "explored_parameters", "]", "zipped_tuples", "=", "list", "(", "zip", "(", "*", "ranges", ")", ")", "try", ":", "unique_elements", "=", "OrderedDict", "(", ")", "for", "idx", ",", "val_tuple", "in", "enumerate", "(", "zipped_tuples", ")", ":", "if", "val_tuple", "not", "in", "unique_elements", ":", "unique_elements", "[", "val_tuple", "]", "=", "[", "]", "unique_elements", "[", "val_tuple", "]", ".", "append", "(", "idx", ")", "return", "list", "(", "unique_elements", ".", "items", "(", ")", ")", "except", "TypeError", ":", "logger", "=", "logging", ".", "getLogger", "(", "'pypet.find_unique'", ")", "logger", ".", "error", "(", "'Your parameter entries could not be hashed, '", "'now I am sorting slowly in O(N**2).'", ")", "unique_elements", "=", "[", "]", "for", "idx", ",", "val_tuple", "in", "enumerate", "(", "zipped_tuples", ")", ":", "matches", "=", "False", "for", "added_tuple", ",", "pos_list", "in", "unique_elements", ":", "matches", "=", "True", "for", "idx2", ",", "val", "in", "enumerate", "(", "added_tuple", ")", ":", "if", "not", "explored_parameters", "[", "idx2", "]", ".", "_equal_values", "(", "val_tuple", "[", "idx2", "]", ",", "val", ")", ":", "matches", "=", "False", "break", "if", "matches", ":", "pos_list", ".", "append", "(", "idx", ")", "break", "if", "not", "matches", ":", "unique_elements", ".", "append", "(", "(", "val_tuple", ",", "[", "idx", "]", ")", ")", "return", "unique_elements" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
_change_logging_kwargs
Helper function to turn the simple logging kwargs into a `log_config`.
pypet/pypetlogging.py
def _change_logging_kwargs(kwargs): """ Helper function to turn the simple logging kwargs into a `log_config`.""" log_levels = kwargs.pop('log_level', None) log_folder = kwargs.pop('log_folder', 'logs') logger_names = kwargs.pop('logger_names', '') if log_levels is None: log_levels = kwargs.pop('log_levels', logging.INFO) log_multiproc = kwargs.pop('log_multiproc', True) if not isinstance(logger_names, (tuple, list)): logger_names = [logger_names] if not isinstance(log_levels, (tuple, list)): log_levels = [log_levels] if len(log_levels) == 1: log_levels = [log_levels[0] for _ in logger_names] # We don't want to manipulate the original dictionary dictionary = copy.deepcopy(LOGGING_DICT) prefixes = [''] if not log_multiproc: for key in list(dictionary.keys()): if key.startswith('multiproc_'): del dictionary[key] else: prefixes.append('multiproc_') # Add all handlers to all loggers for prefix in prefixes: for handler_dict in dictionary[prefix + 'handlers'].values(): if 'filename' in handler_dict: filename = os.path.join(log_folder, handler_dict['filename']) filename = os.path.normpath(filename) handler_dict['filename'] = filename dictionary[prefix + 'loggers'] = {} logger_dict = dictionary[prefix + 'loggers'] for idx, logger_name in enumerate(logger_names): logger_dict[logger_name] = { 'level': log_levels[idx], 'handlers': list(dictionary[prefix + 'handlers'].keys()) } kwargs['log_config'] = dictionary
def _change_logging_kwargs(kwargs): """ Helper function to turn the simple logging kwargs into a `log_config`.""" log_levels = kwargs.pop('log_level', None) log_folder = kwargs.pop('log_folder', 'logs') logger_names = kwargs.pop('logger_names', '') if log_levels is None: log_levels = kwargs.pop('log_levels', logging.INFO) log_multiproc = kwargs.pop('log_multiproc', True) if not isinstance(logger_names, (tuple, list)): logger_names = [logger_names] if not isinstance(log_levels, (tuple, list)): log_levels = [log_levels] if len(log_levels) == 1: log_levels = [log_levels[0] for _ in logger_names] # We don't want to manipulate the original dictionary dictionary = copy.deepcopy(LOGGING_DICT) prefixes = [''] if not log_multiproc: for key in list(dictionary.keys()): if key.startswith('multiproc_'): del dictionary[key] else: prefixes.append('multiproc_') # Add all handlers to all loggers for prefix in prefixes: for handler_dict in dictionary[prefix + 'handlers'].values(): if 'filename' in handler_dict: filename = os.path.join(log_folder, handler_dict['filename']) filename = os.path.normpath(filename) handler_dict['filename'] = filename dictionary[prefix + 'loggers'] = {} logger_dict = dictionary[prefix + 'loggers'] for idx, logger_name in enumerate(logger_names): logger_dict[logger_name] = { 'level': log_levels[idx], 'handlers': list(dictionary[prefix + 'handlers'].keys()) } kwargs['log_config'] = dictionary
[ "Helper", "function", "to", "turn", "the", "simple", "logging", "kwargs", "into", "a", "log_config", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L105-L146
[ "def", "_change_logging_kwargs", "(", "kwargs", ")", ":", "log_levels", "=", "kwargs", ".", "pop", "(", "'log_level'", ",", "None", ")", "log_folder", "=", "kwargs", ".", "pop", "(", "'log_folder'", ",", "'logs'", ")", "logger_names", "=", "kwargs", ".", "pop", "(", "'logger_names'", ",", "''", ")", "if", "log_levels", "is", "None", ":", "log_levels", "=", "kwargs", ".", "pop", "(", "'log_levels'", ",", "logging", ".", "INFO", ")", "log_multiproc", "=", "kwargs", ".", "pop", "(", "'log_multiproc'", ",", "True", ")", "if", "not", "isinstance", "(", "logger_names", ",", "(", "tuple", ",", "list", ")", ")", ":", "logger_names", "=", "[", "logger_names", "]", "if", "not", "isinstance", "(", "log_levels", ",", "(", "tuple", ",", "list", ")", ")", ":", "log_levels", "=", "[", "log_levels", "]", "if", "len", "(", "log_levels", ")", "==", "1", ":", "log_levels", "=", "[", "log_levels", "[", "0", "]", "for", "_", "in", "logger_names", "]", "# We don't want to manipulate the original dictionary", "dictionary", "=", "copy", ".", "deepcopy", "(", "LOGGING_DICT", ")", "prefixes", "=", "[", "''", "]", "if", "not", "log_multiproc", ":", "for", "key", "in", "list", "(", "dictionary", ".", "keys", "(", ")", ")", ":", "if", "key", ".", "startswith", "(", "'multiproc_'", ")", ":", "del", "dictionary", "[", "key", "]", "else", ":", "prefixes", ".", "append", "(", "'multiproc_'", ")", "# Add all handlers to all loggers", "for", "prefix", "in", "prefixes", ":", "for", "handler_dict", "in", "dictionary", "[", "prefix", "+", "'handlers'", "]", ".", "values", "(", ")", ":", "if", "'filename'", "in", "handler_dict", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "log_folder", ",", "handler_dict", "[", "'filename'", "]", ")", "filename", "=", "os", ".", "path", ".", "normpath", "(", "filename", ")", "handler_dict", "[", "'filename'", "]", "=", "filename", "dictionary", "[", "prefix", "+", "'loggers'", "]", "=", "{", "}", "logger_dict", "=", "dictionary", "[", "prefix", "+", "'loggers'", "]", "for", "idx", ",", "logger_name", "in", "enumerate", "(", "logger_names", ")", ":", "logger_dict", "[", "logger_name", "]", "=", "{", "'level'", ":", "log_levels", "[", "idx", "]", ",", "'handlers'", ":", "list", "(", "dictionary", "[", "prefix", "+", "'handlers'", "]", ".", "keys", "(", ")", ")", "}", "kwargs", "[", "'log_config'", "]", "=", "dictionary" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
simple_logging_config
Decorator to allow a simple logging configuration. This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`.
pypet/pypetlogging.py
def simple_logging_config(func): """Decorator to allow a simple logging configuration. This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`. """ @functools.wraps(func) def new_func(self, *args, **kwargs): if use_simple_logging(kwargs): if 'log_config' in kwargs: raise ValueError('Please do not specify `log_config` ' 'if you want to use the simple ' 'way of providing logging configuration ' '(i.e using `log_folder`, `logger_names` and/or `log_levels`).') _change_logging_kwargs(kwargs) return func(self, *args, **kwargs) return new_func
def simple_logging_config(func): """Decorator to allow a simple logging configuration. This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`. """ @functools.wraps(func) def new_func(self, *args, **kwargs): if use_simple_logging(kwargs): if 'log_config' in kwargs: raise ValueError('Please do not specify `log_config` ' 'if you want to use the simple ' 'way of providing logging configuration ' '(i.e using `log_folder`, `logger_names` and/or `log_levels`).') _change_logging_kwargs(kwargs) return func(self, *args, **kwargs) return new_func
[ "Decorator", "to", "allow", "a", "simple", "logging", "configuration", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L155-L174
[ "def", "simple_logging_config", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "use_simple_logging", "(", "kwargs", ")", ":", "if", "'log_config'", "in", "kwargs", ":", "raise", "ValueError", "(", "'Please do not specify `log_config` '", "'if you want to use the simple '", "'way of providing logging configuration '", "'(i.e using `log_folder`, `logger_names` and/or `log_levels`).'", ")", "_change_logging_kwargs", "(", "kwargs", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
try_make_dirs
Tries to make directories for a given `filename`. Ignores any error but notifies via stderr.
pypet/pypetlogging.py
def try_make_dirs(filename): """ Tries to make directories for a given `filename`. Ignores any error but notifies via stderr. """ try: dirname = os.path.dirname(os.path.normpath(filename)) racedirs(dirname) except Exception as exc: sys.stderr.write('ERROR during log config file handling, could not create dirs for ' 'filename `%s` because of: %s' % (filename, repr(exc)))
def try_make_dirs(filename): """ Tries to make directories for a given `filename`. Ignores any error but notifies via stderr. """ try: dirname = os.path.dirname(os.path.normpath(filename)) racedirs(dirname) except Exception as exc: sys.stderr.write('ERROR during log config file handling, could not create dirs for ' 'filename `%s` because of: %s' % (filename, repr(exc)))
[ "Tries", "to", "make", "directories", "for", "a", "given", "filename", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L177-L188
[ "def", "try_make_dirs", "(", "filename", ")", ":", "try", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "normpath", "(", "filename", ")", ")", "racedirs", "(", "dirname", ")", "except", "Exception", "as", "exc", ":", "sys", ".", "stderr", ".", "write", "(", "'ERROR during log config file handling, could not create dirs for '", "'filename `%s` because of: %s'", "%", "(", "filename", ",", "repr", "(", "exc", ")", ")", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
get_strings
Returns all valid python strings inside a given argument string.
pypet/pypetlogging.py
def get_strings(args): """Returns all valid python strings inside a given argument string.""" string_list = [] for elem in ast.walk(ast.parse(args)): if isinstance(elem, ast.Str): string_list.append(elem.s) return string_list
def get_strings(args): """Returns all valid python strings inside a given argument string.""" string_list = [] for elem in ast.walk(ast.parse(args)): if isinstance(elem, ast.Str): string_list.append(elem.s) return string_list
[ "Returns", "all", "valid", "python", "strings", "inside", "a", "given", "argument", "string", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L191-L197
[ "def", "get_strings", "(", "args", ")", ":", "string_list", "=", "[", "]", "for", "elem", "in", "ast", ".", "walk", "(", "ast", ".", "parse", "(", "args", ")", ")", ":", "if", "isinstance", "(", "elem", ",", "ast", ".", "Str", ")", ":", "string_list", ".", "append", "(", "elem", ".", "s", ")", "return", "string_list" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
rename_log_file
Renames a given `filename` with valid wildcard placements. :const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the trajectory`s environment. :const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the trajectory. :const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current run. If the trajectory is not set to a run 'run_ALL' is used. :const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current run set. If the trajectory is not set to a run 'run_set_ALL' is used. :const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the current process. :const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host. :param filename: A filename string :param traj: A trajectory container, leave `None` if you provide all the parameters below :param env_name: Name of environemnt, leave `None` to get it from `traj` :param traj_name: Name of trajectory, leave `None` to get it from `traj` :param set_name: Name of run set, leave `None` to get it from `traj` :param run_name: Name of run, leave `None` to get it from `traj` :param process_name: The name of the desired process. If `None` the name of the current process is taken determined by the multiprocessing module. :param host_name: Name of host, leave `None` to determine it automatically with the platform module. :return: The new filename
pypet/pypetlogging.py
def rename_log_file(filename, trajectory=None, env_name=None, traj_name=None, set_name=None, run_name=None, process_name=None, host_name=None): """ Renames a given `filename` with valid wildcard placements. :const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the trajectory`s environment. :const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the trajectory. :const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current run. If the trajectory is not set to a run 'run_ALL' is used. :const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current run set. If the trajectory is not set to a run 'run_set_ALL' is used. :const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the current process. :const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host. :param filename: A filename string :param traj: A trajectory container, leave `None` if you provide all the parameters below :param env_name: Name of environemnt, leave `None` to get it from `traj` :param traj_name: Name of trajectory, leave `None` to get it from `traj` :param set_name: Name of run set, leave `None` to get it from `traj` :param run_name: Name of run, leave `None` to get it from `traj` :param process_name: The name of the desired process. If `None` the name of the current process is taken determined by the multiprocessing module. :param host_name: Name of host, leave `None` to determine it automatically with the platform module. :return: The new filename """ if pypetconstants.LOG_ENV in filename: if env_name is None: env_name = trajectory.v_environment_name filename = filename.replace(pypetconstants.LOG_ENV, env_name) if pypetconstants.LOG_TRAJ in filename: if traj_name is None: traj_name = trajectory.v_name filename = filename.replace(pypetconstants.LOG_TRAJ, traj_name) if pypetconstants.LOG_RUN in filename: if run_name is None: run_name = trajectory.f_wildcard('$') filename = filename.replace(pypetconstants.LOG_RUN, run_name) if pypetconstants.LOG_SET in filename: if set_name is None: set_name = trajectory.f_wildcard('$set') filename = filename.replace(pypetconstants.LOG_SET, set_name) if pypetconstants.LOG_PROC in filename: if process_name is None: process_name = multip.current_process().name + '-' + str(os.getpid()) filename = filename.replace(pypetconstants.LOG_PROC, process_name) if pypetconstants.LOG_HOST in filename: if host_name is None: host_name = socket.getfqdn().replace('.', '-') filename = filename.replace(pypetconstants.LOG_HOST, host_name) return filename
def rename_log_file(filename, trajectory=None, env_name=None, traj_name=None, set_name=None, run_name=None, process_name=None, host_name=None): """ Renames a given `filename` with valid wildcard placements. :const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the trajectory`s environment. :const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the trajectory. :const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current run. If the trajectory is not set to a run 'run_ALL' is used. :const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current run set. If the trajectory is not set to a run 'run_set_ALL' is used. :const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the current process. :const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host. :param filename: A filename string :param traj: A trajectory container, leave `None` if you provide all the parameters below :param env_name: Name of environemnt, leave `None` to get it from `traj` :param traj_name: Name of trajectory, leave `None` to get it from `traj` :param set_name: Name of run set, leave `None` to get it from `traj` :param run_name: Name of run, leave `None` to get it from `traj` :param process_name: The name of the desired process. If `None` the name of the current process is taken determined by the multiprocessing module. :param host_name: Name of host, leave `None` to determine it automatically with the platform module. :return: The new filename """ if pypetconstants.LOG_ENV in filename: if env_name is None: env_name = trajectory.v_environment_name filename = filename.replace(pypetconstants.LOG_ENV, env_name) if pypetconstants.LOG_TRAJ in filename: if traj_name is None: traj_name = trajectory.v_name filename = filename.replace(pypetconstants.LOG_TRAJ, traj_name) if pypetconstants.LOG_RUN in filename: if run_name is None: run_name = trajectory.f_wildcard('$') filename = filename.replace(pypetconstants.LOG_RUN, run_name) if pypetconstants.LOG_SET in filename: if set_name is None: set_name = trajectory.f_wildcard('$set') filename = filename.replace(pypetconstants.LOG_SET, set_name) if pypetconstants.LOG_PROC in filename: if process_name is None: process_name = multip.current_process().name + '-' + str(os.getpid()) filename = filename.replace(pypetconstants.LOG_PROC, process_name) if pypetconstants.LOG_HOST in filename: if host_name is None: host_name = socket.getfqdn().replace('.', '-') filename = filename.replace(pypetconstants.LOG_HOST, host_name) return filename
[ "Renames", "a", "given", "filename", "with", "valid", "wildcard", "placements", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L200-L268
[ "def", "rename_log_file", "(", "filename", ",", "trajectory", "=", "None", ",", "env_name", "=", "None", ",", "traj_name", "=", "None", ",", "set_name", "=", "None", ",", "run_name", "=", "None", ",", "process_name", "=", "None", ",", "host_name", "=", "None", ")", ":", "if", "pypetconstants", ".", "LOG_ENV", "in", "filename", ":", "if", "env_name", "is", "None", ":", "env_name", "=", "trajectory", ".", "v_environment_name", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_ENV", ",", "env_name", ")", "if", "pypetconstants", ".", "LOG_TRAJ", "in", "filename", ":", "if", "traj_name", "is", "None", ":", "traj_name", "=", "trajectory", ".", "v_name", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_TRAJ", ",", "traj_name", ")", "if", "pypetconstants", ".", "LOG_RUN", "in", "filename", ":", "if", "run_name", "is", "None", ":", "run_name", "=", "trajectory", ".", "f_wildcard", "(", "'$'", ")", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_RUN", ",", "run_name", ")", "if", "pypetconstants", ".", "LOG_SET", "in", "filename", ":", "if", "set_name", "is", "None", ":", "set_name", "=", "trajectory", ".", "f_wildcard", "(", "'$set'", ")", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_SET", ",", "set_name", ")", "if", "pypetconstants", ".", "LOG_PROC", "in", "filename", ":", "if", "process_name", "is", "None", ":", "process_name", "=", "multip", ".", "current_process", "(", ")", ".", "name", "+", "'-'", "+", "str", "(", "os", ".", "getpid", "(", ")", ")", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_PROC", ",", "process_name", ")", "if", "pypetconstants", ".", "LOG_HOST", "in", "filename", ":", "if", "host_name", "is", "None", ":", "host_name", "=", "socket", ".", "getfqdn", "(", ")", ".", "replace", "(", "'.'", ",", "'-'", ")", "filename", "=", "filename", ".", "replace", "(", "pypetconstants", ".", "LOG_HOST", ",", "host_name", ")", "return", "filename" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
HasLogger._set_logger
Adds a logger with a given `name`. If no name is given, name is constructed as `type(self).__name__`.
pypet/pypetlogging.py
def _set_logger(self, name=None): """Adds a logger with a given `name`. If no name is given, name is constructed as `type(self).__name__`. """ if name is None: cls = self.__class__ name = '%s.%s' % (cls.__module__, cls.__name__) self._logger = logging.getLogger(name)
def _set_logger(self, name=None): """Adds a logger with a given `name`. If no name is given, name is constructed as `type(self).__name__`. """ if name is None: cls = self.__class__ name = '%s.%s' % (cls.__module__, cls.__name__) self._logger = logging.getLogger(name)
[ "Adds", "a", "logger", "with", "a", "given", "name", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L311-L321
[ "def", "_set_logger", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "cls", "=", "self", ".", "__class__", "name", "=", "'%s.%s'", "%", "(", "cls", ".", "__module__", ",", "cls", ".", "__name__", ")", "self", ".", "_logger", "=", "logging", ".", "getLogger", "(", "name", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager.extract_replacements
Extracts the wildcards and file replacements from the `trajectory`
pypet/pypetlogging.py
def extract_replacements(self, trajectory): """Extracts the wildcards and file replacements from the `trajectory`""" self.env_name = trajectory.v_environment_name self.traj_name = trajectory.v_name self.set_name = trajectory.f_wildcard('$set') self.run_name = trajectory.f_wildcard('$')
def extract_replacements(self, trajectory): """Extracts the wildcards and file replacements from the `trajectory`""" self.env_name = trajectory.v_environment_name self.traj_name = trajectory.v_name self.set_name = trajectory.f_wildcard('$set') self.run_name = trajectory.f_wildcard('$')
[ "Extracts", "the", "wildcards", "and", "file", "replacements", "from", "the", "trajectory" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L359-L364
[ "def", "extract_replacements", "(", "self", ",", "trajectory", ")", ":", "self", ".", "env_name", "=", "trajectory", ".", "v_environment_name", "self", ".", "traj_name", "=", "trajectory", ".", "v_name", "self", ".", "set_name", "=", "trajectory", ".", "f_wildcard", "(", "'$set'", ")", "self", ".", "run_name", "=", "trajectory", ".", "f_wildcard", "(", "'$'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager.show_progress
Displays a progressbar
pypet/pypetlogging.py
def show_progress(self, n, total_runs): """Displays a progressbar""" if self.report_progress: percentage, logger_name, log_level = self.report_progress if logger_name == 'print': logger = 'print' else: logger = logging.getLogger(logger_name) if n == -1: # Compute the number of digits and avoid log10(0) digits = int(math.log10(total_runs + 0.1)) + 1 self._format_string = 'PROGRESS: Finished %' + '%d' % digits + 'd/%d runs ' fmt_string = self._format_string % (n + 1, total_runs) + '%s' reprint = log_level == 0 progressbar(n, total_runs, percentage_step=percentage, logger=logger, log_level=log_level, fmt_string=fmt_string, reprint=reprint)
def show_progress(self, n, total_runs): """Displays a progressbar""" if self.report_progress: percentage, logger_name, log_level = self.report_progress if logger_name == 'print': logger = 'print' else: logger = logging.getLogger(logger_name) if n == -1: # Compute the number of digits and avoid log10(0) digits = int(math.log10(total_runs + 0.1)) + 1 self._format_string = 'PROGRESS: Finished %' + '%d' % digits + 'd/%d runs ' fmt_string = self._format_string % (n + 1, total_runs) + '%s' reprint = log_level == 0 progressbar(n, total_runs, percentage_step=percentage, logger=logger, log_level=log_level, fmt_string=fmt_string, reprint=reprint)
[ "Displays", "a", "progressbar" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L375-L393
[ "def", "show_progress", "(", "self", ",", "n", ",", "total_runs", ")", ":", "if", "self", ".", "report_progress", ":", "percentage", ",", "logger_name", ",", "log_level", "=", "self", ".", "report_progress", "if", "logger_name", "==", "'print'", ":", "logger", "=", "'print'", "else", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "if", "n", "==", "-", "1", ":", "# Compute the number of digits and avoid log10(0)", "digits", "=", "int", "(", "math", ".", "log10", "(", "total_runs", "+", "0.1", ")", ")", "+", "1", "self", ".", "_format_string", "=", "'PROGRESS: Finished %'", "+", "'%d'", "%", "digits", "+", "'d/%d runs '", "fmt_string", "=", "self", ".", "_format_string", "%", "(", "n", "+", "1", ",", "total_runs", ")", "+", "'%s'", "reprint", "=", "log_level", "==", "0", "progressbar", "(", "n", ",", "total_runs", ",", "percentage_step", "=", "percentage", ",", "logger", "=", "logger", ",", "log_level", "=", "log_level", ",", "fmt_string", "=", "fmt_string", ",", "reprint", "=", "reprint", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._check_and_replace_parser_args
Searches for parser settings that define filenames. If such settings are found, they are renamed according to the wildcard rules. Moreover, it is also tried to create the corresponding folders. :param parser: A config parser :param section: A config section :param option: The section option :param rename_func: A function to rename found files :param make_dirs: If the directories of the file should be created.
pypet/pypetlogging.py
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True): """ Searches for parser settings that define filenames. If such settings are found, they are renamed according to the wildcard rules. Moreover, it is also tried to create the corresponding folders. :param parser: A config parser :param section: A config section :param option: The section option :param rename_func: A function to rename found files :param make_dirs: If the directories of the file should be created. """ args = parser.get(section, option, raw=True) strings = get_strings(args) replace = False for string in strings: isfilename = any(x in string for x in FILENAME_INDICATORS) if isfilename: newstring = rename_func(string) if make_dirs: try_make_dirs(newstring) # To work with windows path specifications we need this replacement: raw_string = string.replace('\\', '\\\\') raw_newstring = newstring.replace('\\', '\\\\') args = args.replace(raw_string, raw_newstring) replace = True if replace: parser.set(section, option, args)
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True): """ Searches for parser settings that define filenames. If such settings are found, they are renamed according to the wildcard rules. Moreover, it is also tried to create the corresponding folders. :param parser: A config parser :param section: A config section :param option: The section option :param rename_func: A function to rename found files :param make_dirs: If the directories of the file should be created. """ args = parser.get(section, option, raw=True) strings = get_strings(args) replace = False for string in strings: isfilename = any(x in string for x in FILENAME_INDICATORS) if isfilename: newstring = rename_func(string) if make_dirs: try_make_dirs(newstring) # To work with windows path specifications we need this replacement: raw_string = string.replace('\\', '\\\\') raw_newstring = newstring.replace('\\', '\\\\') args = args.replace(raw_string, raw_newstring) replace = True if replace: parser.set(section, option, args)
[ "Searches", "for", "parser", "settings", "that", "define", "filenames", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L417-L445
[ "def", "_check_and_replace_parser_args", "(", "parser", ",", "section", ",", "option", ",", "rename_func", ",", "make_dirs", "=", "True", ")", ":", "args", "=", "parser", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "True", ")", "strings", "=", "get_strings", "(", "args", ")", "replace", "=", "False", "for", "string", "in", "strings", ":", "isfilename", "=", "any", "(", "x", "in", "string", "for", "x", "in", "FILENAME_INDICATORS", ")", "if", "isfilename", ":", "newstring", "=", "rename_func", "(", "string", ")", "if", "make_dirs", ":", "try_make_dirs", "(", "newstring", ")", "# To work with windows path specifications we need this replacement:", "raw_string", "=", "string", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "raw_newstring", "=", "newstring", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "args", "=", "args", ".", "replace", "(", "raw_string", ",", "raw_newstring", ")", "replace", "=", "True", "if", "replace", ":", "parser", ".", "set", "(", "section", ",", "option", ",", "args", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._parser_to_string_io
Turns a ConfigParser into a StringIO stream.
pypet/pypetlogging.py
def _parser_to_string_io(parser): """Turns a ConfigParser into a StringIO stream.""" memory_file = StringIO() parser.write(memory_file) memory_file.flush() memory_file.seek(0) return memory_file
def _parser_to_string_io(parser): """Turns a ConfigParser into a StringIO stream.""" memory_file = StringIO() parser.write(memory_file) memory_file.flush() memory_file.seek(0) return memory_file
[ "Turns", "a", "ConfigParser", "into", "a", "StringIO", "stream", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L448-L454
[ "def", "_parser_to_string_io", "(", "parser", ")", ":", "memory_file", "=", "StringIO", "(", ")", "parser", ".", "write", "(", "memory_file", ")", "memory_file", ".", "flush", "(", ")", "memory_file", ".", "seek", "(", "0", ")", "return", "memory_file" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._find_multiproc_options
Searches for multiprocessing options within a ConfigParser. If such options are found, they are copied (without the `'multiproc_'` prefix) into a new parser.
pypet/pypetlogging.py
def _find_multiproc_options(parser): """ Searches for multiprocessing options within a ConfigParser. If such options are found, they are copied (without the `'multiproc_'` prefix) into a new parser. """ sections = parser.sections() if not any(section.startswith('multiproc_') for section in sections): return None mp_parser = NoInterpolationParser() for section in sections: if section.startswith('multiproc_'): new_section = section.replace('multiproc_', '') mp_parser.add_section(new_section) options = parser.options(section) for option in options: val = parser.get(section, option, raw=True) mp_parser.set(new_section, option, val) return mp_parser
def _find_multiproc_options(parser): """ Searches for multiprocessing options within a ConfigParser. If such options are found, they are copied (without the `'multiproc_'` prefix) into a new parser. """ sections = parser.sections() if not any(section.startswith('multiproc_') for section in sections): return None mp_parser = NoInterpolationParser() for section in sections: if section.startswith('multiproc_'): new_section = section.replace('multiproc_', '') mp_parser.add_section(new_section) options = parser.options(section) for option in options: val = parser.get(section, option, raw=True) mp_parser.set(new_section, option, val) return mp_parser
[ "Searches", "for", "multiprocessing", "options", "within", "a", "ConfigParser", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L457-L476
[ "def", "_find_multiproc_options", "(", "parser", ")", ":", "sections", "=", "parser", ".", "sections", "(", ")", "if", "not", "any", "(", "section", ".", "startswith", "(", "'multiproc_'", ")", "for", "section", "in", "sections", ")", ":", "return", "None", "mp_parser", "=", "NoInterpolationParser", "(", ")", "for", "section", "in", "sections", ":", "if", "section", ".", "startswith", "(", "'multiproc_'", ")", ":", "new_section", "=", "section", ".", "replace", "(", "'multiproc_'", ",", "''", ")", "mp_parser", ".", "add_section", "(", "new_section", ")", "options", "=", "parser", ".", "options", "(", "section", ")", "for", "option", "in", "options", ":", "val", "=", "parser", ".", "get", "(", "section", ",", "option", ",", "raw", "=", "True", ")", "mp_parser", ".", "set", "(", "new_section", ",", "option", ",", "val", ")", "return", "mp_parser" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._find_multiproc_dict
Searches for multiprocessing options in a given `dictionary`. If found they are copied (without the `'multiproc_'` prefix) into a new dictionary
pypet/pypetlogging.py
def _find_multiproc_dict(dictionary): """ Searches for multiprocessing options in a given `dictionary`. If found they are copied (without the `'multiproc_'` prefix) into a new dictionary """ if not any(key.startswith('multiproc_') for key in dictionary.keys()): return None mp_dictionary = {} for key in dictionary.keys(): if key.startswith('multiproc_'): new_key = key.replace('multiproc_', '') mp_dictionary[new_key] = dictionary[key] mp_dictionary['version'] = dictionary['version'] if 'disable_existing_loggers' in dictionary: mp_dictionary['disable_existing_loggers'] = dictionary['disable_existing_loggers'] return mp_dictionary
def _find_multiproc_dict(dictionary): """ Searches for multiprocessing options in a given `dictionary`. If found they are copied (without the `'multiproc_'` prefix) into a new dictionary """ if not any(key.startswith('multiproc_') for key in dictionary.keys()): return None mp_dictionary = {} for key in dictionary.keys(): if key.startswith('multiproc_'): new_key = key.replace('multiproc_', '') mp_dictionary[new_key] = dictionary[key] mp_dictionary['version'] = dictionary['version'] if 'disable_existing_loggers' in dictionary: mp_dictionary['disable_existing_loggers'] = dictionary['disable_existing_loggers'] return mp_dictionary
[ "Searches", "for", "multiprocessing", "options", "in", "a", "given", "dictionary", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L479-L496
[ "def", "_find_multiproc_dict", "(", "dictionary", ")", ":", "if", "not", "any", "(", "key", ".", "startswith", "(", "'multiproc_'", ")", "for", "key", "in", "dictionary", ".", "keys", "(", ")", ")", ":", "return", "None", "mp_dictionary", "=", "{", "}", "for", "key", "in", "dictionary", ".", "keys", "(", ")", ":", "if", "key", ".", "startswith", "(", "'multiproc_'", ")", ":", "new_key", "=", "key", ".", "replace", "(", "'multiproc_'", ",", "''", ")", "mp_dictionary", "[", "new_key", "]", "=", "dictionary", "[", "key", "]", "mp_dictionary", "[", "'version'", "]", "=", "dictionary", "[", "'version'", "]", "if", "'disable_existing_loggers'", "in", "dictionary", ":", "mp_dictionary", "[", "'disable_existing_loggers'", "]", "=", "dictionary", "[", "'disable_existing_loggers'", "]", "return", "mp_dictionary" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager.check_log_config
Checks and converts all settings if necessary passed to the Manager. Searches for multiprocessing options as well.
pypet/pypetlogging.py
def check_log_config(self): """ Checks and converts all settings if necessary passed to the Manager. Searches for multiprocessing options as well. """ if self.report_progress: if self.report_progress is True: self.report_progress = (5, 'pypet', logging.INFO) elif isinstance(self.report_progress, (int, float)): self.report_progress = (self.report_progress, 'pypet', logging.INFO) elif isinstance(self.report_progress, str): self.report_progress = (5, self.report_progress, logging.INFO) elif len(self.report_progress) == 2: self.report_progress = (self.report_progress[0], self.report_progress[1], logging.INFO) if self.log_config: if self.log_config == pypetconstants.DEFAULT_LOGGING: pypet_path = os.path.abspath(os.path.dirname(__file__)) init_path = os.path.join(pypet_path, 'logging') self.log_config = os.path.join(init_path, 'default.ini') if isinstance(self.log_config, str): if not os.path.isfile(self.log_config): raise ValueError('Could not find the logger init file ' '`%s`.' % self.log_config) parser = NoInterpolationParser() parser.read(self.log_config) elif isinstance(self.log_config, cp.RawConfigParser): parser = self.log_config else: parser = None if parser is not None: self._sp_config = self._parser_to_string_io(parser) self._mp_config = self._find_multiproc_options(parser) if self._mp_config is not None: self._mp_config = self._parser_to_string_io(self._mp_config) elif isinstance(self.log_config, dict): self._sp_config = self.log_config self._mp_config = self._find_multiproc_dict(self._sp_config) if self.log_stdout: if self.log_stdout is True: self.log_stdout = ('STDOUT', logging.INFO) if isinstance(self.log_stdout, str): self.log_stdout = (self.log_stdout, logging.INFO) if isinstance(self.log_stdout, int): self.log_stdout = ('STDOUT', self.log_stdout)
def check_log_config(self): """ Checks and converts all settings if necessary passed to the Manager. Searches for multiprocessing options as well. """ if self.report_progress: if self.report_progress is True: self.report_progress = (5, 'pypet', logging.INFO) elif isinstance(self.report_progress, (int, float)): self.report_progress = (self.report_progress, 'pypet', logging.INFO) elif isinstance(self.report_progress, str): self.report_progress = (5, self.report_progress, logging.INFO) elif len(self.report_progress) == 2: self.report_progress = (self.report_progress[0], self.report_progress[1], logging.INFO) if self.log_config: if self.log_config == pypetconstants.DEFAULT_LOGGING: pypet_path = os.path.abspath(os.path.dirname(__file__)) init_path = os.path.join(pypet_path, 'logging') self.log_config = os.path.join(init_path, 'default.ini') if isinstance(self.log_config, str): if not os.path.isfile(self.log_config): raise ValueError('Could not find the logger init file ' '`%s`.' % self.log_config) parser = NoInterpolationParser() parser.read(self.log_config) elif isinstance(self.log_config, cp.RawConfigParser): parser = self.log_config else: parser = None if parser is not None: self._sp_config = self._parser_to_string_io(parser) self._mp_config = self._find_multiproc_options(parser) if self._mp_config is not None: self._mp_config = self._parser_to_string_io(self._mp_config) elif isinstance(self.log_config, dict): self._sp_config = self.log_config self._mp_config = self._find_multiproc_dict(self._sp_config) if self.log_stdout: if self.log_stdout is True: self.log_stdout = ('STDOUT', logging.INFO) if isinstance(self.log_stdout, str): self.log_stdout = (self.log_stdout, logging.INFO) if isinstance(self.log_stdout, int): self.log_stdout = ('STDOUT', self.log_stdout)
[ "Checks", "and", "converts", "all", "settings", "if", "necessary", "passed", "to", "the", "Manager", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L498-L548
[ "def", "check_log_config", "(", "self", ")", ":", "if", "self", ".", "report_progress", ":", "if", "self", ".", "report_progress", "is", "True", ":", "self", ".", "report_progress", "=", "(", "5", ",", "'pypet'", ",", "logging", ".", "INFO", ")", "elif", "isinstance", "(", "self", ".", "report_progress", ",", "(", "int", ",", "float", ")", ")", ":", "self", ".", "report_progress", "=", "(", "self", ".", "report_progress", ",", "'pypet'", ",", "logging", ".", "INFO", ")", "elif", "isinstance", "(", "self", ".", "report_progress", ",", "str", ")", ":", "self", ".", "report_progress", "=", "(", "5", ",", "self", ".", "report_progress", ",", "logging", ".", "INFO", ")", "elif", "len", "(", "self", ".", "report_progress", ")", "==", "2", ":", "self", ".", "report_progress", "=", "(", "self", ".", "report_progress", "[", "0", "]", ",", "self", ".", "report_progress", "[", "1", "]", ",", "logging", ".", "INFO", ")", "if", "self", ".", "log_config", ":", "if", "self", ".", "log_config", "==", "pypetconstants", ".", "DEFAULT_LOGGING", ":", "pypet_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "init_path", "=", "os", ".", "path", ".", "join", "(", "pypet_path", ",", "'logging'", ")", "self", ".", "log_config", "=", "os", ".", "path", ".", "join", "(", "init_path", ",", "'default.ini'", ")", "if", "isinstance", "(", "self", ".", "log_config", ",", "str", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "log_config", ")", ":", "raise", "ValueError", "(", "'Could not find the logger init file '", "'`%s`.'", "%", "self", ".", "log_config", ")", "parser", "=", "NoInterpolationParser", "(", ")", "parser", ".", "read", "(", "self", ".", "log_config", ")", "elif", "isinstance", "(", "self", ".", "log_config", ",", "cp", ".", "RawConfigParser", ")", ":", "parser", "=", "self", ".", "log_config", "else", ":", "parser", "=", "None", "if", "parser", "is", "not", "None", ":", "self", ".", "_sp_config", "=", "self", ".", "_parser_to_string_io", "(", "parser", ")", "self", ".", "_mp_config", "=", "self", ".", "_find_multiproc_options", "(", "parser", ")", "if", "self", ".", "_mp_config", "is", "not", "None", ":", "self", ".", "_mp_config", "=", "self", ".", "_parser_to_string_io", "(", "self", ".", "_mp_config", ")", "elif", "isinstance", "(", "self", ".", "log_config", ",", "dict", ")", ":", "self", ".", "_sp_config", "=", "self", ".", "log_config", "self", ".", "_mp_config", "=", "self", ".", "_find_multiproc_dict", "(", "self", ".", "_sp_config", ")", "if", "self", ".", "log_stdout", ":", "if", "self", ".", "log_stdout", "is", "True", ":", "self", ".", "log_stdout", "=", "(", "'STDOUT'", ",", "logging", ".", "INFO", ")", "if", "isinstance", "(", "self", ".", "log_stdout", ",", "str", ")", ":", "self", ".", "log_stdout", "=", "(", "self", ".", "log_stdout", ",", "logging", ".", "INFO", ")", "if", "isinstance", "(", "self", ".", "log_stdout", ",", "int", ")", ":", "self", ".", "log_stdout", "=", "(", "'STDOUT'", ",", "self", ".", "log_stdout", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._handle_config_parsing
Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO)
pypet/pypetlogging.py
def _handle_config_parsing(self, log_config): """ Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO) """ parser = NoInterpolationParser() parser.readfp(log_config) rename_func = lambda string: rename_log_file(string, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name, run_name=self.run_name) sections = parser.sections() for section in sections: options = parser.options(section) for option in options: if option == 'args': self._check_and_replace_parser_args(parser, section, option, rename_func=rename_func) return parser
def _handle_config_parsing(self, log_config): """ Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO) """ parser = NoInterpolationParser() parser.readfp(log_config) rename_func = lambda string: rename_log_file(string, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name, run_name=self.run_name) sections = parser.sections() for section in sections: options = parser.options(section) for option in options: if option == 'args': self._check_and_replace_parser_args(parser, section, option, rename_func=rename_func) return parser
[ "Checks", "for", "filenames", "within", "a", "config", "file", "and", "translates", "them", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L550-L574
[ "def", "_handle_config_parsing", "(", "self", ",", "log_config", ")", ":", "parser", "=", "NoInterpolationParser", "(", ")", "parser", ".", "readfp", "(", "log_config", ")", "rename_func", "=", "lambda", "string", ":", "rename_log_file", "(", "string", ",", "env_name", "=", "self", ".", "env_name", ",", "traj_name", "=", "self", ".", "traj_name", ",", "set_name", "=", "self", ".", "set_name", ",", "run_name", "=", "self", ".", "run_name", ")", "sections", "=", "parser", ".", "sections", "(", ")", "for", "section", "in", "sections", ":", "options", "=", "parser", ".", "options", "(", "section", ")", "for", "option", "in", "options", ":", "if", "option", "==", "'args'", ":", "self", ".", "_check_and_replace_parser_args", "(", "parser", ",", "section", ",", "option", ",", "rename_func", "=", "rename_func", ")", "return", "parser" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager._handle_dict_config
Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary.
pypet/pypetlogging.py
def _handle_dict_config(self, log_config): """Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary. """ new_dict = dict() for key in log_config.keys(): if key == 'filename': filename = log_config[key] filename = rename_log_file(filename, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name, run_name=self.run_name) new_dict[key] = filename try_make_dirs(filename) elif isinstance(log_config[key], dict): inner_dict = self._handle_dict_config(log_config[key]) new_dict[key] = inner_dict else: new_dict[key] = log_config[key] return new_dict
def _handle_dict_config(self, log_config): """Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary. """ new_dict = dict() for key in log_config.keys(): if key == 'filename': filename = log_config[key] filename = rename_log_file(filename, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name, run_name=self.run_name) new_dict[key] = filename try_make_dirs(filename) elif isinstance(log_config[key], dict): inner_dict = self._handle_dict_config(log_config[key]) new_dict[key] = inner_dict else: new_dict[key] = log_config[key] return new_dict
[ "Recursively", "walks", "and", "copies", "the", "log_config", "dict", "and", "searches", "for", "filenames", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L576-L598
[ "def", "_handle_dict_config", "(", "self", ",", "log_config", ")", ":", "new_dict", "=", "dict", "(", ")", "for", "key", "in", "log_config", ".", "keys", "(", ")", ":", "if", "key", "==", "'filename'", ":", "filename", "=", "log_config", "[", "key", "]", "filename", "=", "rename_log_file", "(", "filename", ",", "env_name", "=", "self", ".", "env_name", ",", "traj_name", "=", "self", ".", "traj_name", ",", "set_name", "=", "self", ".", "set_name", ",", "run_name", "=", "self", ".", "run_name", ")", "new_dict", "[", "key", "]", "=", "filename", "try_make_dirs", "(", "filename", ")", "elif", "isinstance", "(", "log_config", "[", "key", "]", ",", "dict", ")", ":", "inner_dict", "=", "self", ".", "_handle_dict_config", "(", "log_config", "[", "key", "]", ")", "new_dict", "[", "key", "]", "=", "inner_dict", "else", ":", "new_dict", "[", "key", "]", "=", "log_config", "[", "key", "]", "return", "new_dict" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager.make_logging_handlers_and_tools
Creates logging handlers and redirects stdout.
pypet/pypetlogging.py
def make_logging_handlers_and_tools(self, multiproc=False): """Creates logging handlers and redirects stdout.""" log_stdout = self.log_stdout if sys.stdout is self._stdout_to_logger: # If we already redirected stdout we don't neet to redo it again log_stdout = False if self.log_config: if multiproc: proc_log_config = self._mp_config else: proc_log_config = self._sp_config if proc_log_config: if isinstance(proc_log_config, dict): new_dict = self._handle_dict_config(proc_log_config) dictConfig(new_dict) else: parser = self._handle_config_parsing(proc_log_config) memory_file = self._parser_to_string_io(parser) fileConfig(memory_file, disable_existing_loggers=False) if log_stdout: # Create a logging mock for stdout std_name, std_level = self.log_stdout stdout = StdoutToLogger(std_name, log_level=std_level) stdout.start() self._tools.append(stdout)
def make_logging_handlers_and_tools(self, multiproc=False): """Creates logging handlers and redirects stdout.""" log_stdout = self.log_stdout if sys.stdout is self._stdout_to_logger: # If we already redirected stdout we don't neet to redo it again log_stdout = False if self.log_config: if multiproc: proc_log_config = self._mp_config else: proc_log_config = self._sp_config if proc_log_config: if isinstance(proc_log_config, dict): new_dict = self._handle_dict_config(proc_log_config) dictConfig(new_dict) else: parser = self._handle_config_parsing(proc_log_config) memory_file = self._parser_to_string_io(parser) fileConfig(memory_file, disable_existing_loggers=False) if log_stdout: # Create a logging mock for stdout std_name, std_level = self.log_stdout stdout = StdoutToLogger(std_name, log_level=std_level) stdout.start() self._tools.append(stdout)
[ "Creates", "logging", "handlers", "and", "redirects", "stdout", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L600-L629
[ "def", "make_logging_handlers_and_tools", "(", "self", ",", "multiproc", "=", "False", ")", ":", "log_stdout", "=", "self", ".", "log_stdout", "if", "sys", ".", "stdout", "is", "self", ".", "_stdout_to_logger", ":", "# If we already redirected stdout we don't neet to redo it again", "log_stdout", "=", "False", "if", "self", ".", "log_config", ":", "if", "multiproc", ":", "proc_log_config", "=", "self", ".", "_mp_config", "else", ":", "proc_log_config", "=", "self", ".", "_sp_config", "if", "proc_log_config", ":", "if", "isinstance", "(", "proc_log_config", ",", "dict", ")", ":", "new_dict", "=", "self", ".", "_handle_dict_config", "(", "proc_log_config", ")", "dictConfig", "(", "new_dict", ")", "else", ":", "parser", "=", "self", ".", "_handle_config_parsing", "(", "proc_log_config", ")", "memory_file", "=", "self", ".", "_parser_to_string_io", "(", "parser", ")", "fileConfig", "(", "memory_file", ",", "disable_existing_loggers", "=", "False", ")", "if", "log_stdout", ":", "# Create a logging mock for stdout", "std_name", ",", "std_level", "=", "self", ".", "log_stdout", "stdout", "=", "StdoutToLogger", "(", "std_name", ",", "log_level", "=", "std_level", ")", "stdout", ".", "start", "(", ")", "self", ".", "_tools", ".", "append", "(", "stdout", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
LoggingManager.finalize
Finalizes the manager, closes and removes all handlers if desired.
pypet/pypetlogging.py
def finalize(self, remove_all_handlers=True): """Finalizes the manager, closes and removes all handlers if desired.""" for tool in self._tools: tool.finalize() self._tools = [] self._stdout_to_logger = None for config in (self._sp_config, self._mp_config): if hasattr(config, 'close'): config.close() self._sp_config = None self._mp_config = None if remove_all_handlers: self.tabula_rasa()
def finalize(self, remove_all_handlers=True): """Finalizes the manager, closes and removes all handlers if desired.""" for tool in self._tools: tool.finalize() self._tools = [] self._stdout_to_logger = None for config in (self._sp_config, self._mp_config): if hasattr(config, 'close'): config.close() self._sp_config = None self._mp_config = None if remove_all_handlers: self.tabula_rasa()
[ "Finalizes", "the", "manager", "closes", "and", "removes", "all", "handlers", "if", "desired", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L631-L643
[ "def", "finalize", "(", "self", ",", "remove_all_handlers", "=", "True", ")", ":", "for", "tool", "in", "self", ".", "_tools", ":", "tool", ".", "finalize", "(", ")", "self", ".", "_tools", "=", "[", "]", "self", ".", "_stdout_to_logger", "=", "None", "for", "config", "in", "(", "self", ".", "_sp_config", ",", "self", ".", "_mp_config", ")", ":", "if", "hasattr", "(", "config", ",", "'close'", ")", ":", "config", ".", "close", "(", ")", "self", ".", "_sp_config", "=", "None", "self", ".", "_mp_config", "=", "None", "if", "remove_all_handlers", ":", "self", ".", "tabula_rasa", "(", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
StdoutToLogger.start
Starts redirection of `stdout`
pypet/pypetlogging.py
def start(self): """Starts redirection of `stdout`""" if sys.stdout is not self: self._original_steam = sys.stdout sys.stdout = self self._redirection = True if self._redirection: print('Established redirection of `stdout`.')
def start(self): """Starts redirection of `stdout`""" if sys.stdout is not self: self._original_steam = sys.stdout sys.stdout = self self._redirection = True if self._redirection: print('Established redirection of `stdout`.')
[ "Starts", "redirection", "of", "stdout" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L684-L691
[ "def", "start", "(", "self", ")", ":", "if", "sys", ".", "stdout", "is", "not", "self", ":", "self", ".", "_original_steam", "=", "sys", ".", "stdout", "sys", ".", "stdout", "=", "self", "self", ".", "_redirection", "=", "True", "if", "self", ".", "_redirection", ":", "print", "(", "'Established redirection of `stdout`.'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
StdoutToLogger.write
Writes data from buffer to logger
pypet/pypetlogging.py
def write(self, buf): """Writes data from buffer to logger""" if not self._recursion: self._recursion = True try: for line in buf.rstrip().splitlines(): self._logger.log(self._log_level, line.rstrip()) finally: self._recursion = False else: # If stderr is redirected to stdout we can avoid further recursion by sys.__stderr__.write('ERROR: Recursion in Stream redirection!')
def write(self, buf): """Writes data from buffer to logger""" if not self._recursion: self._recursion = True try: for line in buf.rstrip().splitlines(): self._logger.log(self._log_level, line.rstrip()) finally: self._recursion = False else: # If stderr is redirected to stdout we can avoid further recursion by sys.__stderr__.write('ERROR: Recursion in Stream redirection!')
[ "Writes", "data", "from", "buffer", "to", "logger" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L693-L704
[ "def", "write", "(", "self", ",", "buf", ")", ":", "if", "not", "self", ".", "_recursion", ":", "self", ".", "_recursion", "=", "True", "try", ":", "for", "line", "in", "buf", ".", "rstrip", "(", ")", ".", "splitlines", "(", ")", ":", "self", ".", "_logger", ".", "log", "(", "self", ".", "_log_level", ",", "line", ".", "rstrip", "(", ")", ")", "finally", ":", "self", ".", "_recursion", "=", "False", "else", ":", "# If stderr is redirected to stdout we can avoid further recursion by", "sys", ".", "__stderr__", ".", "write", "(", "'ERROR: Recursion in Stream redirection!'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
StdoutToLogger.finalize
Disables redirection
pypet/pypetlogging.py
def finalize(self): """Disables redirection""" if self._original_steam is not None and self._redirection: sys.stdout = self._original_steam print('Disabled redirection of `stdout`.') self._redirection = False self._original_steam = None
def finalize(self): """Disables redirection""" if self._original_steam is not None and self._redirection: sys.stdout = self._original_steam print('Disabled redirection of `stdout`.') self._redirection = False self._original_steam = None
[ "Disables", "redirection" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L710-L716
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "_original_steam", "is", "not", "None", "and", "self", ".", "_redirection", ":", "sys", ".", "stdout", "=", "self", ".", "_original_steam", "print", "(", "'Disabled redirection of `stdout`.'", ")", "self", ".", "_redirection", "=", "False", "self", ".", "_original_steam", "=", "None" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
results_equal
Compares two result instances Checks full name and all data. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no result instances
pypet/utils/comparisons.py
def results_equal(a, b): """Compares two result instances Checks full name and all data. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no result instances """ if a.v_is_parameter and b.v_is_parameter: raise ValueError('Both inputs are not results.') if a.v_is_parameter or b.v_is_parameter: return False if a.v_full_name != b.v_full_name: return False if hasattr(a, '_data') and not hasattr(b, '_data'): return False if hasattr(a, '_data'): akeyset = set(a._data.keys()) bkeyset = set(b._data.keys()) if akeyset != bkeyset: return False for key in a._data: val = a._data[key] bval = b._data[key] if not nested_equal(val, bval): return False return True
def results_equal(a, b): """Compares two result instances Checks full name and all data. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no result instances """ if a.v_is_parameter and b.v_is_parameter: raise ValueError('Both inputs are not results.') if a.v_is_parameter or b.v_is_parameter: return False if a.v_full_name != b.v_full_name: return False if hasattr(a, '_data') and not hasattr(b, '_data'): return False if hasattr(a, '_data'): akeyset = set(a._data.keys()) bkeyset = set(b._data.keys()) if akeyset != bkeyset: return False for key in a._data: val = a._data[key] bval = b._data[key] if not nested_equal(val, bval): return False return True
[ "Compares", "two", "result", "instances" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/comparisons.py#L14-L50
[ "def", "results_equal", "(", "a", ",", "b", ")", ":", "if", "a", ".", "v_is_parameter", "and", "b", ".", "v_is_parameter", ":", "raise", "ValueError", "(", "'Both inputs are not results.'", ")", "if", "a", ".", "v_is_parameter", "or", "b", ".", "v_is_parameter", ":", "return", "False", "if", "a", ".", "v_full_name", "!=", "b", ".", "v_full_name", ":", "return", "False", "if", "hasattr", "(", "a", ",", "'_data'", ")", "and", "not", "hasattr", "(", "b", ",", "'_data'", ")", ":", "return", "False", "if", "hasattr", "(", "a", ",", "'_data'", ")", ":", "akeyset", "=", "set", "(", "a", ".", "_data", ".", "keys", "(", ")", ")", "bkeyset", "=", "set", "(", "b", ".", "_data", ".", "keys", "(", ")", ")", "if", "akeyset", "!=", "bkeyset", ":", "return", "False", "for", "key", "in", "a", ".", "_data", ":", "val", "=", "a", ".", "_data", "[", "key", "]", "bval", "=", "b", ".", "_data", "[", "key", "]", "if", "not", "nested_equal", "(", "val", ",", "bval", ")", ":", "return", "False", "return", "True" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
parameters_equal
Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances
pypet/utils/comparisons.py
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): raise ValueError('Both inputs are not parameters') if (not b.v_is_parameter or not a.v_is_parameter): return False if a.v_full_name != b.v_full_name: return False if a.f_is_empty() and b.f_is_empty(): return True if a.f_is_empty() != b.f_is_empty(): return False if not a._values_of_same_type(a.f_get(), b.f_get()): return False if not a._equal_values(a.f_get(), b.f_get()): return False if a.f_has_range() != b.f_has_range(): return False if a.f_has_range(): if a.f_get_range_length() != b.f_get_range_length(): return False for myitem, bitem in zip(a.f_get_range(copy=False), b.f_get_range(copy=False)): if not a._values_of_same_type(myitem, bitem): return False if not a._equal_values(myitem, bitem): return False return True
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): raise ValueError('Both inputs are not parameters') if (not b.v_is_parameter or not a.v_is_parameter): return False if a.v_full_name != b.v_full_name: return False if a.f_is_empty() and b.f_is_empty(): return True if a.f_is_empty() != b.f_is_empty(): return False if not a._values_of_same_type(a.f_get(), b.f_get()): return False if not a._equal_values(a.f_get(), b.f_get()): return False if a.f_has_range() != b.f_has_range(): return False if a.f_has_range(): if a.f_get_range_length() != b.f_get_range_length(): return False for myitem, bitem in zip(a.f_get_range(copy=False), b.f_get_range(copy=False)): if not a._values_of_same_type(myitem, bitem): return False if not a._equal_values(myitem, bitem): return False return True
[ "Compares", "two", "parameter", "instances" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/comparisons.py#L53-L99
[ "def", "parameters_equal", "(", "a", ",", "b", ")", ":", "if", "(", "not", "b", ".", "v_is_parameter", "and", "not", "a", ".", "v_is_parameter", ")", ":", "raise", "ValueError", "(", "'Both inputs are not parameters'", ")", "if", "(", "not", "b", ".", "v_is_parameter", "or", "not", "a", ".", "v_is_parameter", ")", ":", "return", "False", "if", "a", ".", "v_full_name", "!=", "b", ".", "v_full_name", ":", "return", "False", "if", "a", ".", "f_is_empty", "(", ")", "and", "b", ".", "f_is_empty", "(", ")", ":", "return", "True", "if", "a", ".", "f_is_empty", "(", ")", "!=", "b", ".", "f_is_empty", "(", ")", ":", "return", "False", "if", "not", "a", ".", "_values_of_same_type", "(", "a", ".", "f_get", "(", ")", ",", "b", ".", "f_get", "(", ")", ")", ":", "return", "False", "if", "not", "a", ".", "_equal_values", "(", "a", ".", "f_get", "(", ")", ",", "b", ".", "f_get", "(", ")", ")", ":", "return", "False", "if", "a", ".", "f_has_range", "(", ")", "!=", "b", ".", "f_has_range", "(", ")", ":", "return", "False", "if", "a", ".", "f_has_range", "(", ")", ":", "if", "a", ".", "f_get_range_length", "(", ")", "!=", "b", ".", "f_get_range_length", "(", ")", ":", "return", "False", "for", "myitem", ",", "bitem", "in", "zip", "(", "a", ".", "f_get_range", "(", "copy", "=", "False", ")", ",", "b", ".", "f_get_range", "(", "copy", "=", "False", ")", ")", ":", "if", "not", "a", ".", "_values_of_same_type", "(", "myitem", ",", "bitem", ")", ":", "return", "False", "if", "not", "a", ".", "_equal_values", "(", "myitem", ",", "bitem", ")", ":", "return", "False", "return", "True" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
get_all_attributes
Returns an attribute value dictionary much like `__dict__` but incorporates `__slots__`
pypet/utils/comparisons.py
def get_all_attributes(instance): """Returns an attribute value dictionary much like `__dict__` but incorporates `__slots__`""" try: result_dict = instance.__dict__.copy() except AttributeError: result_dict = {} if hasattr(instance, '__all_slots__'): all_slots = instance.__all_slots__ else: all_slots = slots.get_all_slots(instance.__class__) for slot in all_slots: result_dict[slot] = getattr(instance, slot) result_dict.pop('__dict__', None) result_dict.pop('__weakref__', None) return result_dict
def get_all_attributes(instance): """Returns an attribute value dictionary much like `__dict__` but incorporates `__slots__`""" try: result_dict = instance.__dict__.copy() except AttributeError: result_dict = {} if hasattr(instance, '__all_slots__'): all_slots = instance.__all_slots__ else: all_slots = slots.get_all_slots(instance.__class__) for slot in all_slots: result_dict[slot] = getattr(instance, slot) result_dict.pop('__dict__', None) result_dict.pop('__weakref__', None) return result_dict
[ "Returns", "an", "attribute", "value", "dictionary", "much", "like", "__dict__", "but", "incorporates", "__slots__" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/comparisons.py#L102-L120
[ "def", "get_all_attributes", "(", "instance", ")", ":", "try", ":", "result_dict", "=", "instance", ".", "__dict__", ".", "copy", "(", ")", "except", "AttributeError", ":", "result_dict", "=", "{", "}", "if", "hasattr", "(", "instance", ",", "'__all_slots__'", ")", ":", "all_slots", "=", "instance", ".", "__all_slots__", "else", ":", "all_slots", "=", "slots", ".", "get_all_slots", "(", "instance", ".", "__class__", ")", "for", "slot", "in", "all_slots", ":", "result_dict", "[", "slot", "]", "=", "getattr", "(", "instance", ",", "slot", ")", "result_dict", ".", "pop", "(", "'__dict__'", ",", "None", ")", "result_dict", ".", "pop", "(", "'__weakref__'", ",", "None", ")", "return", "result_dict" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
nested_equal
Compares two objects recursively by their elements. Also handles numpy arrays, pandas data and sparse matrices. First checks if the data falls into the above categories. If not, it is checked if a or b are some type of sequence or mapping and the contained elements are compared. If this is not the case, it is checked if a or b do provide a custom `__eq__` that evaluates to a single boolean value. If this is not the case, the attributes of a and b are compared. If this does not help either, normal `==` is used. Assumes hashable items are not mutable in a way that affects equality. Based on the suggestion from HERE_, thanks again Lauritz V. Thaulow :-) .. _HERE: http://stackoverflow.com/questions/18376935/best-practice-for-equality-in-python
pypet/utils/comparisons.py
def nested_equal(a, b): """Compares two objects recursively by their elements. Also handles numpy arrays, pandas data and sparse matrices. First checks if the data falls into the above categories. If not, it is checked if a or b are some type of sequence or mapping and the contained elements are compared. If this is not the case, it is checked if a or b do provide a custom `__eq__` that evaluates to a single boolean value. If this is not the case, the attributes of a and b are compared. If this does not help either, normal `==` is used. Assumes hashable items are not mutable in a way that affects equality. Based on the suggestion from HERE_, thanks again Lauritz V. Thaulow :-) .. _HERE: http://stackoverflow.com/questions/18376935/best-practice-for-equality-in-python """ if a is b: return True if a is None or b is None: return False a_sparse = spsp.isspmatrix(a) b_sparse = spsp.isspmatrix(b) if a_sparse != b_sparse: return False if a_sparse: if a.nnz == 0: return b.nnz == 0 else: return not np.any((a != b).data) a_series = isinstance(a, pd.Series) b_series = isinstance(b, pd.Series) if a_series != b_series: return False if a_series: try: eq = (a == b).all() return eq except (TypeError, ValueError): # If Sequence itself contains numpy arrays we get here if not len(a) == len(b): return False for idx, itema in enumerate(a): itemb = b[idx] if not nested_equal(itema, itemb): return False return True a_frame = isinstance(a, pd.DataFrame) b_frame = isinstance(b, pd.DataFrame) if a_frame != b_frame: return False if a_frame: try: if a.empty and b.empty: return True new_frame = a == b new_frame = new_frame | (pd.isnull(a) & pd.isnull(b)) if isinstance(new_frame, pd.DataFrame): return np.all(new_frame.as_matrix()) except (ValueError, TypeError): # The Value Error can happen if the data frame is of dtype=object and contains # numpy arrays. Numpy array comparisons do not evaluate to a single truth value for name in a: cola = a[name] if not name in b: return False colb = b[name] if not len(cola) == len(colb): return False for idx, itema in enumerate(cola): itemb = colb[idx] if not nested_equal(itema, itemb): return False return True a_array = isinstance(a, np.ndarray) b_array = isinstance(b, np.ndarray) if a_array != b_array: return False if a_array: if a.shape != b.shape: return False return np.all(a == b) a_list = isinstance(a, (Sequence, list, tuple)) b_list = isinstance(b, (Sequence, list, tuple)) if a_list != b_list: return False if a_list: return all(nested_equal(x, y) for x, y in zip(a, b)) a_mapping = isinstance(a, (Mapping, dict)) b_mapping = isinstance(b, (Mapping, dict)) if a_mapping != b_mapping: return False if a_mapping: keys_a = a.keys() if set(keys_a) != set(b.keys()): return False return all(nested_equal(a[k], b[k]) for k in keys_a) # Equality for general objects # for types that support __eq__ or __cmp__ equality = NotImplemented try: equality = a.__eq__(b) except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: equality = b.__eq__(a) except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: cmp = a.__cmp__(b) if cmp is not NotImplemented: equality = cmp == 0 except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: cmp = b.__cmp__(a) if cmp is not NotImplemented: equality = cmp == 0 except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is not NotImplemented: try: return bool(equality) except (AttributeError, NotImplementedError, TypeError, ValueError): pass # Compare objects based on their attributes attributes_a = get_all_attributes(a) attributes_b = get_all_attributes(b) if len(attributes_a) != len(attributes_b): return False if len(attributes_a) > 0: keys_a = list(attributes_a.keys()) if set(keys_a) != set(attributes_b.keys()): return False return all(nested_equal(attributes_a[k], attributes_b[k]) for k in keys_a) # Ok they are really not equal return False
def nested_equal(a, b): """Compares two objects recursively by their elements. Also handles numpy arrays, pandas data and sparse matrices. First checks if the data falls into the above categories. If not, it is checked if a or b are some type of sequence or mapping and the contained elements are compared. If this is not the case, it is checked if a or b do provide a custom `__eq__` that evaluates to a single boolean value. If this is not the case, the attributes of a and b are compared. If this does not help either, normal `==` is used. Assumes hashable items are not mutable in a way that affects equality. Based on the suggestion from HERE_, thanks again Lauritz V. Thaulow :-) .. _HERE: http://stackoverflow.com/questions/18376935/best-practice-for-equality-in-python """ if a is b: return True if a is None or b is None: return False a_sparse = spsp.isspmatrix(a) b_sparse = spsp.isspmatrix(b) if a_sparse != b_sparse: return False if a_sparse: if a.nnz == 0: return b.nnz == 0 else: return not np.any((a != b).data) a_series = isinstance(a, pd.Series) b_series = isinstance(b, pd.Series) if a_series != b_series: return False if a_series: try: eq = (a == b).all() return eq except (TypeError, ValueError): # If Sequence itself contains numpy arrays we get here if not len(a) == len(b): return False for idx, itema in enumerate(a): itemb = b[idx] if not nested_equal(itema, itemb): return False return True a_frame = isinstance(a, pd.DataFrame) b_frame = isinstance(b, pd.DataFrame) if a_frame != b_frame: return False if a_frame: try: if a.empty and b.empty: return True new_frame = a == b new_frame = new_frame | (pd.isnull(a) & pd.isnull(b)) if isinstance(new_frame, pd.DataFrame): return np.all(new_frame.as_matrix()) except (ValueError, TypeError): # The Value Error can happen if the data frame is of dtype=object and contains # numpy arrays. Numpy array comparisons do not evaluate to a single truth value for name in a: cola = a[name] if not name in b: return False colb = b[name] if not len(cola) == len(colb): return False for idx, itema in enumerate(cola): itemb = colb[idx] if not nested_equal(itema, itemb): return False return True a_array = isinstance(a, np.ndarray) b_array = isinstance(b, np.ndarray) if a_array != b_array: return False if a_array: if a.shape != b.shape: return False return np.all(a == b) a_list = isinstance(a, (Sequence, list, tuple)) b_list = isinstance(b, (Sequence, list, tuple)) if a_list != b_list: return False if a_list: return all(nested_equal(x, y) for x, y in zip(a, b)) a_mapping = isinstance(a, (Mapping, dict)) b_mapping = isinstance(b, (Mapping, dict)) if a_mapping != b_mapping: return False if a_mapping: keys_a = a.keys() if set(keys_a) != set(b.keys()): return False return all(nested_equal(a[k], b[k]) for k in keys_a) # Equality for general objects # for types that support __eq__ or __cmp__ equality = NotImplemented try: equality = a.__eq__(b) except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: equality = b.__eq__(a) except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: cmp = a.__cmp__(b) if cmp is not NotImplemented: equality = cmp == 0 except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is NotImplemented: try: cmp = b.__cmp__(a) if cmp is not NotImplemented: equality = cmp == 0 except (AttributeError, NotImplementedError, TypeError, ValueError): pass if equality is not NotImplemented: try: return bool(equality) except (AttributeError, NotImplementedError, TypeError, ValueError): pass # Compare objects based on their attributes attributes_a = get_all_attributes(a) attributes_b = get_all_attributes(b) if len(attributes_a) != len(attributes_b): return False if len(attributes_a) > 0: keys_a = list(attributes_a.keys()) if set(keys_a) != set(attributes_b.keys()): return False return all(nested_equal(attributes_a[k], attributes_b[k]) for k in keys_a) # Ok they are really not equal return False
[ "Compares", "two", "objects", "recursively", "by", "their", "elements", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/comparisons.py#L123-L275
[ "def", "nested_equal", "(", "a", ",", "b", ")", ":", "if", "a", "is", "b", ":", "return", "True", "if", "a", "is", "None", "or", "b", "is", "None", ":", "return", "False", "a_sparse", "=", "spsp", ".", "isspmatrix", "(", "a", ")", "b_sparse", "=", "spsp", ".", "isspmatrix", "(", "b", ")", "if", "a_sparse", "!=", "b_sparse", ":", "return", "False", "if", "a_sparse", ":", "if", "a", ".", "nnz", "==", "0", ":", "return", "b", ".", "nnz", "==", "0", "else", ":", "return", "not", "np", ".", "any", "(", "(", "a", "!=", "b", ")", ".", "data", ")", "a_series", "=", "isinstance", "(", "a", ",", "pd", ".", "Series", ")", "b_series", "=", "isinstance", "(", "b", ",", "pd", ".", "Series", ")", "if", "a_series", "!=", "b_series", ":", "return", "False", "if", "a_series", ":", "try", ":", "eq", "=", "(", "a", "==", "b", ")", ".", "all", "(", ")", "return", "eq", "except", "(", "TypeError", ",", "ValueError", ")", ":", "# If Sequence itself contains numpy arrays we get here", "if", "not", "len", "(", "a", ")", "==", "len", "(", "b", ")", ":", "return", "False", "for", "idx", ",", "itema", "in", "enumerate", "(", "a", ")", ":", "itemb", "=", "b", "[", "idx", "]", "if", "not", "nested_equal", "(", "itema", ",", "itemb", ")", ":", "return", "False", "return", "True", "a_frame", "=", "isinstance", "(", "a", ",", "pd", ".", "DataFrame", ")", "b_frame", "=", "isinstance", "(", "b", ",", "pd", ".", "DataFrame", ")", "if", "a_frame", "!=", "b_frame", ":", "return", "False", "if", "a_frame", ":", "try", ":", "if", "a", ".", "empty", "and", "b", ".", "empty", ":", "return", "True", "new_frame", "=", "a", "==", "b", "new_frame", "=", "new_frame", "|", "(", "pd", ".", "isnull", "(", "a", ")", "&", "pd", ".", "isnull", "(", "b", ")", ")", "if", "isinstance", "(", "new_frame", ",", "pd", ".", "DataFrame", ")", ":", "return", "np", ".", "all", "(", "new_frame", ".", "as_matrix", "(", ")", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "# The Value Error can happen if the data frame is of dtype=object and contains", "# numpy arrays. Numpy array comparisons do not evaluate to a single truth value", "for", "name", "in", "a", ":", "cola", "=", "a", "[", "name", "]", "if", "not", "name", "in", "b", ":", "return", "False", "colb", "=", "b", "[", "name", "]", "if", "not", "len", "(", "cola", ")", "==", "len", "(", "colb", ")", ":", "return", "False", "for", "idx", ",", "itema", "in", "enumerate", "(", "cola", ")", ":", "itemb", "=", "colb", "[", "idx", "]", "if", "not", "nested_equal", "(", "itema", ",", "itemb", ")", ":", "return", "False", "return", "True", "a_array", "=", "isinstance", "(", "a", ",", "np", ".", "ndarray", ")", "b_array", "=", "isinstance", "(", "b", ",", "np", ".", "ndarray", ")", "if", "a_array", "!=", "b_array", ":", "return", "False", "if", "a_array", ":", "if", "a", ".", "shape", "!=", "b", ".", "shape", ":", "return", "False", "return", "np", ".", "all", "(", "a", "==", "b", ")", "a_list", "=", "isinstance", "(", "a", ",", "(", "Sequence", ",", "list", ",", "tuple", ")", ")", "b_list", "=", "isinstance", "(", "b", ",", "(", "Sequence", ",", "list", ",", "tuple", ")", ")", "if", "a_list", "!=", "b_list", ":", "return", "False", "if", "a_list", ":", "return", "all", "(", "nested_equal", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "a", ",", "b", ")", ")", "a_mapping", "=", "isinstance", "(", "a", ",", "(", "Mapping", ",", "dict", ")", ")", "b_mapping", "=", "isinstance", "(", "b", ",", "(", "Mapping", ",", "dict", ")", ")", "if", "a_mapping", "!=", "b_mapping", ":", "return", "False", "if", "a_mapping", ":", "keys_a", "=", "a", ".", "keys", "(", ")", "if", "set", "(", "keys_a", ")", "!=", "set", "(", "b", ".", "keys", "(", ")", ")", ":", "return", "False", "return", "all", "(", "nested_equal", "(", "a", "[", "k", "]", ",", "b", "[", "k", "]", ")", "for", "k", "in", "keys_a", ")", "# Equality for general objects", "# for types that support __eq__ or __cmp__", "equality", "=", "NotImplemented", "try", ":", "equality", "=", "a", ".", "__eq__", "(", "b", ")", "except", "(", "AttributeError", ",", "NotImplementedError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "if", "equality", "is", "NotImplemented", ":", "try", ":", "equality", "=", "b", ".", "__eq__", "(", "a", ")", "except", "(", "AttributeError", ",", "NotImplementedError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "if", "equality", "is", "NotImplemented", ":", "try", ":", "cmp", "=", "a", ".", "__cmp__", "(", "b", ")", "if", "cmp", "is", "not", "NotImplemented", ":", "equality", "=", "cmp", "==", "0", "except", "(", "AttributeError", ",", "NotImplementedError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "if", "equality", "is", "NotImplemented", ":", "try", ":", "cmp", "=", "b", ".", "__cmp__", "(", "a", ")", "if", "cmp", "is", "not", "NotImplemented", ":", "equality", "=", "cmp", "==", "0", "except", "(", "AttributeError", ",", "NotImplementedError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "if", "equality", "is", "not", "NotImplemented", ":", "try", ":", "return", "bool", "(", "equality", ")", "except", "(", "AttributeError", ",", "NotImplementedError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "# Compare objects based on their attributes", "attributes_a", "=", "get_all_attributes", "(", "a", ")", "attributes_b", "=", "get_all_attributes", "(", "b", ")", "if", "len", "(", "attributes_a", ")", "!=", "len", "(", "attributes_b", ")", ":", "return", "False", "if", "len", "(", "attributes_a", ")", ">", "0", ":", "keys_a", "=", "list", "(", "attributes_a", ".", "keys", "(", ")", ")", "if", "set", "(", "keys_a", ")", "!=", "set", "(", "attributes_b", ".", "keys", "(", ")", ")", ":", "return", "False", "return", "all", "(", "nested_equal", "(", "attributes_a", "[", "k", "]", ",", "attributes_b", "[", "k", "]", ")", "for", "k", "in", "keys_a", ")", "# Ok they are really not equal", "return", "False" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
manual_run
Can be used to decorate a function as a manual run function. This can be helpful if you want the run functionality without using an environment. :param turn_into_run: If the trajectory should become a `single run` with more specialized functionality during a single run. :param store_meta_data: If meta-data like runtime should be automatically stored :param clean_up: If all data added during the single run should be removed, only works if ``turn_into_run=True``.
pypet/utils/decorators.py
def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True): """Can be used to decorate a function as a manual run function. This can be helpful if you want the run functionality without using an environment. :param turn_into_run: If the trajectory should become a `single run` with more specialized functionality during a single run. :param store_meta_data: If meta-data like runtime should be automatically stored :param clean_up: If all data added during the single run should be removed, only works if ``turn_into_run=True``. """ def wrapper(func): @functools.wraps(func) def new_func(traj, *args, **kwargs): do_wrap = not traj._run_by_environment if do_wrap: traj.f_start_run(turn_into_run=turn_into_run) result = func(traj, *args, **kwargs) if do_wrap: traj.f_finalize_run(store_meta_data=store_meta_data, clean_up=clean_up) return result return new_func return wrapper
def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True): """Can be used to decorate a function as a manual run function. This can be helpful if you want the run functionality without using an environment. :param turn_into_run: If the trajectory should become a `single run` with more specialized functionality during a single run. :param store_meta_data: If meta-data like runtime should be automatically stored :param clean_up: If all data added during the single run should be removed, only works if ``turn_into_run=True``. """ def wrapper(func): @functools.wraps(func) def new_func(traj, *args, **kwargs): do_wrap = not traj._run_by_environment if do_wrap: traj.f_start_run(turn_into_run=turn_into_run) result = func(traj, *args, **kwargs) if do_wrap: traj.f_finalize_run(store_meta_data=store_meta_data, clean_up=clean_up) return result return new_func return wrapper
[ "Can", "be", "used", "to", "decorate", "a", "function", "as", "a", "manual", "run", "function", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L11-L45
[ "def", "manual_run", "(", "turn_into_run", "=", "True", ",", "store_meta_data", "=", "True", ",", "clean_up", "=", "True", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "traj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "do_wrap", "=", "not", "traj", ".", "_run_by_environment", "if", "do_wrap", ":", "traj", ".", "f_start_run", "(", "turn_into_run", "=", "turn_into_run", ")", "result", "=", "func", "(", "traj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "do_wrap", ":", "traj", ".", "f_finalize_run", "(", "store_meta_data", "=", "store_meta_data", ",", "clean_up", "=", "clean_up", ")", "return", "result", "return", "new_func", "return", "wrapper" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
deprecated
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning.
pypet/utils/decorators.py
def deprecated(msg=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): warning_string = "Call to deprecated function or property `%s`." % func.__name__ warning_string = warning_string + ' ' + msg warnings.warn( warning_string, category=DeprecationWarning, ) return func(*args, **kwargs) return new_func return wrapper
def deprecated(msg=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): warning_string = "Call to deprecated function or property `%s`." % func.__name__ warning_string = warning_string + ' ' + msg warnings.warn( warning_string, category=DeprecationWarning, ) return func(*args, **kwargs) return new_func return wrapper
[ "This", "is", "a", "decorator", "which", "can", "be", "used", "to", "mark", "functions", "as", "deprecated", ".", "It", "will", "result", "in", "a", "warning", "being", "emitted", "when", "the", "function", "is", "used", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L48-L72
[ "def", "deprecated", "(", "msg", "=", "''", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warning_string", "=", "\"Call to deprecated function or property `%s`.\"", "%", "func", ".", "__name__", "warning_string", "=", "warning_string", "+", "' '", "+", "msg", "warnings", ".", "warn", "(", "warning_string", ",", "category", "=", "DeprecationWarning", ",", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func", "return", "wrapper" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
copydoc
Decorator: Copy the docstring of `fromfunc` If the doc contains a line with the keyword `ABSTRACT`, like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed.
pypet/utils/decorators.py
def copydoc(fromfunc, sep="\n"): """Decorator: Copy the docstring of `fromfunc` If the doc contains a line with the keyword `ABSTRACT`, like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed. """ def _decorator(func): sourcedoc = fromfunc.__doc__ # Remove the ABSTRACT line: split_doc = sourcedoc.split('\n') split_doc_no_abstract = [line for line in split_doc if not 'ABSTRACT' in line] # If the length is different we have found an ABSTRACT line # Finally we want to remove the final blank line, otherwise # we would have three blank lines at the end if len(split_doc) != len(split_doc_no_abstract): sourcedoc = '\n'.join(split_doc_no_abstract[:-1]) if func.__doc__ is None: func.__doc__ = sourcedoc else: func.__doc__ = sep.join([sourcedoc, func.__doc__]) return func return _decorator
def copydoc(fromfunc, sep="\n"): """Decorator: Copy the docstring of `fromfunc` If the doc contains a line with the keyword `ABSTRACT`, like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed. """ def _decorator(func): sourcedoc = fromfunc.__doc__ # Remove the ABSTRACT line: split_doc = sourcedoc.split('\n') split_doc_no_abstract = [line for line in split_doc if not 'ABSTRACT' in line] # If the length is different we have found an ABSTRACT line # Finally we want to remove the final blank line, otherwise # we would have three blank lines at the end if len(split_doc) != len(split_doc_no_abstract): sourcedoc = '\n'.join(split_doc_no_abstract[:-1]) if func.__doc__ is None: func.__doc__ = sourcedoc else: func.__doc__ = sep.join([sourcedoc, func.__doc__]) return func return _decorator
[ "Decorator", ":", "Copy", "the", "docstring", "of", "fromfunc" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L75-L102
[ "def", "copydoc", "(", "fromfunc", ",", "sep", "=", "\"\\n\"", ")", ":", "def", "_decorator", "(", "func", ")", ":", "sourcedoc", "=", "fromfunc", ".", "__doc__", "# Remove the ABSTRACT line:", "split_doc", "=", "sourcedoc", ".", "split", "(", "'\\n'", ")", "split_doc_no_abstract", "=", "[", "line", "for", "line", "in", "split_doc", "if", "not", "'ABSTRACT'", "in", "line", "]", "# If the length is different we have found an ABSTRACT line", "# Finally we want to remove the final blank line, otherwise", "# we would have three blank lines at the end", "if", "len", "(", "split_doc", ")", "!=", "len", "(", "split_doc_no_abstract", ")", ":", "sourcedoc", "=", "'\\n'", ".", "join", "(", "split_doc_no_abstract", "[", ":", "-", "1", "]", ")", "if", "func", ".", "__doc__", "is", "None", ":", "func", ".", "__doc__", "=", "sourcedoc", "else", ":", "func", ".", "__doc__", "=", "sep", ".", "join", "(", "[", "sourcedoc", ",", "func", ".", "__doc__", "]", ")", "return", "func", "return", "_decorator" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
kwargs_mutual_exclusive
If there exist mutually exclusive parameters checks for them and maps param2 to 1.
pypet/utils/decorators.py
def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None): """ If there exist mutually exclusive parameters checks for them and maps param2 to 1.""" def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if param2_name in kwargs: if param1_name in kwargs: raise ValueError('You cannot specify `%s` and `%s` at the same time, ' 'they are mutually exclusive.' % (param1_name, param2_name)) param2 = kwargs.pop(param2_name) if map2to1 is not None: param1 = map2to1(param2) else: param1 = param2 kwargs[param1_name] = param1 return func(*args, **kwargs) return new_func return wrapper
def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None): """ If there exist mutually exclusive parameters checks for them and maps param2 to 1.""" def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if param2_name in kwargs: if param1_name in kwargs: raise ValueError('You cannot specify `%s` and `%s` at the same time, ' 'they are mutually exclusive.' % (param1_name, param2_name)) param2 = kwargs.pop(param2_name) if map2to1 is not None: param1 = map2to1(param2) else: param1 = param2 kwargs[param1_name] = param1 return func(*args, **kwargs) return new_func return wrapper
[ "If", "there", "exist", "mutually", "exclusive", "parameters", "checks", "for", "them", "and", "maps", "param2", "to", "1", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L105-L125
[ "def", "kwargs_mutual_exclusive", "(", "param1_name", ",", "param2_name", ",", "map2to1", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "param2_name", "in", "kwargs", ":", "if", "param1_name", "in", "kwargs", ":", "raise", "ValueError", "(", "'You cannot specify `%s` and `%s` at the same time, '", "'they are mutually exclusive.'", "%", "(", "param1_name", ",", "param2_name", ")", ")", "param2", "=", "kwargs", ".", "pop", "(", "param2_name", ")", "if", "map2to1", "is", "not", "None", ":", "param1", "=", "map2to1", "(", "param2", ")", "else", ":", "param1", "=", "param2", "kwargs", "[", "param1_name", "]", "=", "param1", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func", "return", "wrapper" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
kwargs_api_change
This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. Issues a warning if the old keyword argument is detected and converts call to new API. :param old_name: Old name of the keyword argument :param new_name: New name of keyword argument
pypet/utils/decorators.py
def kwargs_api_change(old_name, new_name=None): """This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. Issues a warning if the old keyword argument is detected and converts call to new API. :param old_name: Old name of the keyword argument :param new_name: New name of keyword argument """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if old_name in kwargs: if new_name is None: warning_string = 'Using deprecated keyword argument `%s` in function `%s`. ' \ 'This keyword is no longer supported, please don`t use it ' \ 'anymore.' % (old_name, func.__name__) else: warning_string = 'Using deprecated keyword argument `%s` in function `%s`, ' \ 'please use keyword `%s` instead.' % \ (old_name, func.__name__, new_name) warnings.warn(warning_string, category=DeprecationWarning) value = kwargs.pop(old_name) if new_name is not None: kwargs[new_name] = value return func(*args, **kwargs) return new_func return wrapper
def kwargs_api_change(old_name, new_name=None): """This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. Issues a warning if the old keyword argument is detected and converts call to new API. :param old_name: Old name of the keyword argument :param new_name: New name of keyword argument """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if old_name in kwargs: if new_name is None: warning_string = 'Using deprecated keyword argument `%s` in function `%s`. ' \ 'This keyword is no longer supported, please don`t use it ' \ 'anymore.' % (old_name, func.__name__) else: warning_string = 'Using deprecated keyword argument `%s` in function `%s`, ' \ 'please use keyword `%s` instead.' % \ (old_name, func.__name__, new_name) warnings.warn(warning_string, category=DeprecationWarning) value = kwargs.pop(old_name) if new_name is not None: kwargs[new_name] = value return func(*args, **kwargs) return new_func return wrapper
[ "This", "is", "a", "decorator", "which", "can", "be", "used", "if", "a", "kwarg", "has", "changed", "its", "name", "over", "versions", "to", "also", "support", "the", "old", "argument", "name", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L128-L167
[ "def", "kwargs_api_change", "(", "old_name", ",", "new_name", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "old_name", "in", "kwargs", ":", "if", "new_name", "is", "None", ":", "warning_string", "=", "'Using deprecated keyword argument `%s` in function `%s`. '", "'This keyword is no longer supported, please don`t use it '", "'anymore.'", "%", "(", "old_name", ",", "func", ".", "__name__", ")", "else", ":", "warning_string", "=", "'Using deprecated keyword argument `%s` in function `%s`, '", "'please use keyword `%s` instead.'", "%", "(", "old_name", ",", "func", ".", "__name__", ",", "new_name", ")", "warnings", ".", "warn", "(", "warning_string", ",", "category", "=", "DeprecationWarning", ")", "value", "=", "kwargs", ".", "pop", "(", "old_name", ")", "if", "new_name", "is", "not", "None", ":", "kwargs", "[", "new_name", "]", "=", "value", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func", "return", "wrapper" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
not_in_run
This is a decorator that signaling that a function is not available during a single run.
pypet/utils/decorators.py
def not_in_run(func): """This is a decorator that signaling that a function is not available during a single run. """ doc = func.__doc__ na_string = '''\nATTENTION: This function is not available during a single run!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_string]) func._not_in_run = True @functools.wraps(func) def new_func(self, *args, **kwargs): if self._is_run: raise TypeError('Function `%s` is not available during a single run.' % func.__name__) return func(self, *args, **kwargs) return new_func
def not_in_run(func): """This is a decorator that signaling that a function is not available during a single run. """ doc = func.__doc__ na_string = '''\nATTENTION: This function is not available during a single run!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_string]) func._not_in_run = True @functools.wraps(func) def new_func(self, *args, **kwargs): if self._is_run: raise TypeError('Function `%s` is not available during a single run.' % func.__name__) return func(self, *args, **kwargs) return new_func
[ "This", "is", "a", "decorator", "that", "signaling", "that", "a", "function", "is", "not", "available", "during", "a", "single", "run", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L170-L190
[ "def", "not_in_run", "(", "func", ")", ":", "doc", "=", "func", ".", "__doc__", "na_string", "=", "'''\\nATTENTION: This function is not available during a single run!\\n'''", "if", "doc", "is", "not", "None", ":", "func", ".", "__doc__", "=", "'\\n'", ".", "join", "(", "[", "doc", ",", "na_string", "]", ")", "func", ".", "_not_in_run", "=", "True", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_is_run", ":", "raise", "TypeError", "(", "'Function `%s` is not available during a single run.'", "%", "func", ".", "__name__", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
with_open_store
This is a decorator that signaling that a function is only available if the storage is open.
pypet/utils/decorators.py
def with_open_store(func): """This is a decorator that signaling that a function is only available if the storage is open. """ doc = func.__doc__ na_string = '''\nATTENTION: This function can only be used if the store is open!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_string]) func._with_open_store = True @functools.wraps(func) def new_func(self, *args, **kwargs): if not self.traj.v_storage_service.is_open: raise TypeError('Function `%s` is only available if the storage is open.' % func.__name__) return func(self, *args, **kwargs) return new_func
def with_open_store(func): """This is a decorator that signaling that a function is only available if the storage is open. """ doc = func.__doc__ na_string = '''\nATTENTION: This function can only be used if the store is open!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_string]) func._with_open_store = True @functools.wraps(func) def new_func(self, *args, **kwargs): if not self.traj.v_storage_service.is_open: raise TypeError('Function `%s` is only available if the storage is open.' % func.__name__) return func(self, *args, **kwargs) return new_func
[ "This", "is", "a", "decorator", "that", "signaling", "that", "a", "function", "is", "only", "available", "if", "the", "storage", "is", "open", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L193-L213
[ "def", "with_open_store", "(", "func", ")", ":", "doc", "=", "func", ".", "__doc__", "na_string", "=", "'''\\nATTENTION: This function can only be used if the store is open!\\n'''", "if", "doc", "is", "not", "None", ":", "func", ".", "__doc__", "=", "'\\n'", ".", "join", "(", "[", "doc", ",", "na_string", "]", ")", "func", ".", "_with_open_store", "=", "True", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "traj", ".", "v_storage_service", ".", "is_open", ":", "raise", "TypeError", "(", "'Function `%s` is only available if the storage is open.'", "%", "func", ".", "__name__", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_func" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
retry
This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger to print the caught error.
pypet/utils/decorators.py
def retry(n, errors, wait=0.0, logger_name=None): """This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger to print the caught error. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): retries = 0 while True: try: result = func(*args, **kwargs) if retries and logger_name: logger = logging.getLogger(logger_name) logger.debug('Retry of `%s` successful' % func.__name__) return result except errors: if retries >= n: if logger_name: logger = logging.getLogger(logger_name) logger.exception('I could not execute `%s` with args %s and kwargs %s, ' 'starting next try. ' % (func.__name__, str(args), str(kwargs))) raise elif logger_name: logger = logging.getLogger(logger_name) logger.debug('I could not execute `%s` with args %s and kwargs %s, ' 'starting next try. ' % (func.__name__, str(args), str(kwargs))) retries += 1 if wait: time.sleep(wait) return new_func return wrapper
def retry(n, errors, wait=0.0, logger_name=None): """This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger to print the caught error. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): retries = 0 while True: try: result = func(*args, **kwargs) if retries and logger_name: logger = logging.getLogger(logger_name) logger.debug('Retry of `%s` successful' % func.__name__) return result except errors: if retries >= n: if logger_name: logger = logging.getLogger(logger_name) logger.exception('I could not execute `%s` with args %s and kwargs %s, ' 'starting next try. ' % (func.__name__, str(args), str(kwargs))) raise elif logger_name: logger = logging.getLogger(logger_name) logger.debug('I could not execute `%s` with args %s and kwargs %s, ' 'starting next try. ' % (func.__name__, str(args), str(kwargs))) retries += 1 if wait: time.sleep(wait) return new_func return wrapper
[ "This", "is", "a", "decorator", "that", "retries", "a", "function", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L216-L260
[ "def", "retry", "(", "n", ",", "errors", ",", "wait", "=", "0.0", ",", "logger_name", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "retries", "=", "0", "while", "True", ":", "try", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "retries", "and", "logger_name", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "debug", "(", "'Retry of `%s` successful'", "%", "func", ".", "__name__", ")", "return", "result", "except", "errors", ":", "if", "retries", ">=", "n", ":", "if", "logger_name", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "exception", "(", "'I could not execute `%s` with args %s and kwargs %s, '", "'starting next try. '", "%", "(", "func", ".", "__name__", ",", "str", "(", "args", ")", ",", "str", "(", "kwargs", ")", ")", ")", "raise", "elif", "logger_name", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "debug", "(", "'I could not execute `%s` with args %s and kwargs %s, '", "'starting next try. '", "%", "(", "func", ".", "__name__", ",", "str", "(", "args", ")", ",", "str", "(", "kwargs", ")", ")", ")", "retries", "+=", "1", "if", "wait", ":", "time", ".", "sleep", "(", "wait", ")", "return", "new_func", "return", "wrapper" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
_prfx_getattr_
Replacement of __getattr__
pypet/utils/decorators.py
def _prfx_getattr_(obj, item): """Replacement of __getattr__""" if item.startswith('f_') or item.startswith('v_'): return getattr(obj, item[2:]) raise AttributeError('`%s` object has no attribute `%s`' % (obj.__class__.__name__, item))
def _prfx_getattr_(obj, item): """Replacement of __getattr__""" if item.startswith('f_') or item.startswith('v_'): return getattr(obj, item[2:]) raise AttributeError('`%s` object has no attribute `%s`' % (obj.__class__.__name__, item))
[ "Replacement", "of", "__getattr__" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L263-L267
[ "def", "_prfx_getattr_", "(", "obj", ",", "item", ")", ":", "if", "item", ".", "startswith", "(", "'f_'", ")", "or", "item", ".", "startswith", "(", "'v_'", ")", ":", "return", "getattr", "(", "obj", ",", "item", "[", "2", ":", "]", ")", "raise", "AttributeError", "(", "'`%s` object has no attribute `%s`'", "%", "(", "obj", ".", "__class__", ".", "__name__", ",", "item", ")", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
_prfx_setattr_
Replacement of __setattr__
pypet/utils/decorators.py
def _prfx_setattr_(obj, item, value): """Replacement of __setattr__""" if item.startswith('v_'): return setattr(obj, item[2:], value) else: return super(obj.__class__, obj).__setattr__(item, value)
def _prfx_setattr_(obj, item, value): """Replacement of __setattr__""" if item.startswith('v_'): return setattr(obj, item[2:], value) else: return super(obj.__class__, obj).__setattr__(item, value)
[ "Replacement", "of", "__setattr__" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L270-L275
[ "def", "_prfx_setattr_", "(", "obj", ",", "item", ",", "value", ")", ":", "if", "item", ".", "startswith", "(", "'v_'", ")", ":", "return", "setattr", "(", "obj", ",", "item", "[", "2", ":", "]", ",", "value", ")", "else", ":", "return", "super", "(", "obj", ".", "__class__", ",", "obj", ")", ".", "__setattr__", "(", "item", ",", "value", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
prefix_naming
Decorate that adds the prefix naming scheme
pypet/utils/decorators.py
def prefix_naming(cls): """Decorate that adds the prefix naming scheme""" if hasattr(cls, '__getattr__'): raise TypeError('__getattr__ already defined') cls.__getattr__ = _prfx_getattr_ cls.__setattr__ = _prfx_setattr_ return cls
def prefix_naming(cls): """Decorate that adds the prefix naming scheme""" if hasattr(cls, '__getattr__'): raise TypeError('__getattr__ already defined') cls.__getattr__ = _prfx_getattr_ cls.__setattr__ = _prfx_setattr_ return cls
[ "Decorate", "that", "adds", "the", "prefix", "naming", "scheme" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L278-L284
[ "def", "prefix_naming", "(", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'__getattr__'", ")", ":", "raise", "TypeError", "(", "'__getattr__ already defined'", ")", "cls", ".", "__getattr__", "=", "_prfx_getattr_", "cls", ".", "__setattr__", "=", "_prfx_setattr_", "return", "cls" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
add_params
Adds all necessary parameters to `traj`.
examples/example_23_brian2_network.py
def add_params(traj): """Adds all necessary parameters to `traj`.""" # We set the BrianParameter to be the standard parameter traj.v_standard_parameter=Brian2Parameter traj.v_fast_access=True # Add parameters we need for our network traj.f_add_parameter('Net.C',281*pF) traj.f_add_parameter('Net.gL',30*nS) traj.f_add_parameter('Net.EL',-70.6*mV) traj.f_add_parameter('Net.VT',-50.4*mV) traj.f_add_parameter('Net.DeltaT',2*mV) traj.f_add_parameter('Net.tauw',40*ms) traj.f_add_parameter('Net.a',4*nS) traj.f_add_parameter('Net.b',0.08*nA) traj.f_add_parameter('Net.I',.8*nA) traj.f_add_parameter('Net.Vcut','vm > 0*mV') # practical threshold condition traj.f_add_parameter('Net.N',50) eqs=''' dvm/dt=(gL*(EL-vm)+gL*DeltaT*exp((vm-VT)/DeltaT)+I-w)/C : volt dw/dt=(a*(vm-EL)-w)/tauw : amp Vr:volt ''' traj.f_add_parameter('Net.eqs', eqs) traj.f_add_parameter('reset', 'vm=Vr;w+=b')
def add_params(traj): """Adds all necessary parameters to `traj`.""" # We set the BrianParameter to be the standard parameter traj.v_standard_parameter=Brian2Parameter traj.v_fast_access=True # Add parameters we need for our network traj.f_add_parameter('Net.C',281*pF) traj.f_add_parameter('Net.gL',30*nS) traj.f_add_parameter('Net.EL',-70.6*mV) traj.f_add_parameter('Net.VT',-50.4*mV) traj.f_add_parameter('Net.DeltaT',2*mV) traj.f_add_parameter('Net.tauw',40*ms) traj.f_add_parameter('Net.a',4*nS) traj.f_add_parameter('Net.b',0.08*nA) traj.f_add_parameter('Net.I',.8*nA) traj.f_add_parameter('Net.Vcut','vm > 0*mV') # practical threshold condition traj.f_add_parameter('Net.N',50) eqs=''' dvm/dt=(gL*(EL-vm)+gL*DeltaT*exp((vm-VT)/DeltaT)+I-w)/C : volt dw/dt=(a*(vm-EL)-w)/tauw : amp Vr:volt ''' traj.f_add_parameter('Net.eqs', eqs) traj.f_add_parameter('reset', 'vm=Vr;w+=b')
[ "Adds", "all", "necessary", "parameters", "to", "traj", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_23_brian2_network.py#L14-L40
[ "def", "add_params", "(", "traj", ")", ":", "# We set the BrianParameter to be the standard parameter", "traj", ".", "v_standard_parameter", "=", "Brian2Parameter", "traj", ".", "v_fast_access", "=", "True", "# Add parameters we need for our network", "traj", ".", "f_add_parameter", "(", "'Net.C'", ",", "281", "*", "pF", ")", "traj", ".", "f_add_parameter", "(", "'Net.gL'", ",", "30", "*", "nS", ")", "traj", ".", "f_add_parameter", "(", "'Net.EL'", ",", "-", "70.6", "*", "mV", ")", "traj", ".", "f_add_parameter", "(", "'Net.VT'", ",", "-", "50.4", "*", "mV", ")", "traj", ".", "f_add_parameter", "(", "'Net.DeltaT'", ",", "2", "*", "mV", ")", "traj", ".", "f_add_parameter", "(", "'Net.tauw'", ",", "40", "*", "ms", ")", "traj", ".", "f_add_parameter", "(", "'Net.a'", ",", "4", "*", "nS", ")", "traj", ".", "f_add_parameter", "(", "'Net.b'", ",", "0.08", "*", "nA", ")", "traj", ".", "f_add_parameter", "(", "'Net.I'", ",", ".8", "*", "nA", ")", "traj", ".", "f_add_parameter", "(", "'Net.Vcut'", ",", "'vm > 0*mV'", ")", "# practical threshold condition", "traj", ".", "f_add_parameter", "(", "'Net.N'", ",", "50", ")", "eqs", "=", "'''\n dvm/dt=(gL*(EL-vm)+gL*DeltaT*exp((vm-VT)/DeltaT)+I-w)/C : volt\n dw/dt=(a*(vm-EL)-w)/tauw : amp\n Vr:volt\n '''", "traj", ".", "f_add_parameter", "(", "'Net.eqs'", ",", "eqs", ")", "traj", ".", "f_add_parameter", "(", "'reset'", ",", "'vm=Vr;w+=b'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
run_net
Creates and runs BRIAN network based on the parameters in `traj`.
examples/example_23_brian2_network.py
def run_net(traj): """Creates and runs BRIAN network based on the parameters in `traj`.""" eqs=traj.eqs # Create a namespace dictionairy namespace = traj.Net.f_to_dict(short_names=True, fast_access=True) # Create the Neuron Group neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset=traj.reset, namespace=namespace) neuron.vm=traj.EL neuron.w=traj.a*(neuron.vm-traj.EL) neuron.Vr=linspace(-48.3*mV,-47.7*mV,traj.N) # bifurcation parameter # Run the network initially for 100 milliseconds print('Initial Run') net = Network(neuron) net.run(100*ms, report='text') # we discard the first spikes # Create a Spike Monitor MSpike=SpikeMonitor(neuron) net.add(MSpike) # Create a State Monitor for the membrane voltage, record from neurons 1-3 MStateV = StateMonitor(neuron, variables=['vm'],record=[1,2,3]) net.add(MStateV) # Now record for 500 milliseconds print('Measurement run') net.run(500*ms,report='text') # Add the BRAIN monitors traj.v_standard_result = Brian2MonitorResult traj.f_add_result('SpikeMonitor',MSpike) traj.f_add_result('StateMonitorV', MStateV)
def run_net(traj): """Creates and runs BRIAN network based on the parameters in `traj`.""" eqs=traj.eqs # Create a namespace dictionairy namespace = traj.Net.f_to_dict(short_names=True, fast_access=True) # Create the Neuron Group neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset=traj.reset, namespace=namespace) neuron.vm=traj.EL neuron.w=traj.a*(neuron.vm-traj.EL) neuron.Vr=linspace(-48.3*mV,-47.7*mV,traj.N) # bifurcation parameter # Run the network initially for 100 milliseconds print('Initial Run') net = Network(neuron) net.run(100*ms, report='text') # we discard the first spikes # Create a Spike Monitor MSpike=SpikeMonitor(neuron) net.add(MSpike) # Create a State Monitor for the membrane voltage, record from neurons 1-3 MStateV = StateMonitor(neuron, variables=['vm'],record=[1,2,3]) net.add(MStateV) # Now record for 500 milliseconds print('Measurement run') net.run(500*ms,report='text') # Add the BRAIN monitors traj.v_standard_result = Brian2MonitorResult traj.f_add_result('SpikeMonitor',MSpike) traj.f_add_result('StateMonitorV', MStateV)
[ "Creates", "and", "runs", "BRIAN", "network", "based", "on", "the", "parameters", "in", "traj", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_23_brian2_network.py#L43-L76
[ "def", "run_net", "(", "traj", ")", ":", "eqs", "=", "traj", ".", "eqs", "# Create a namespace dictionairy", "namespace", "=", "traj", ".", "Net", ".", "f_to_dict", "(", "short_names", "=", "True", ",", "fast_access", "=", "True", ")", "# Create the Neuron Group", "neuron", "=", "NeuronGroup", "(", "traj", ".", "N", ",", "model", "=", "eqs", ",", "threshold", "=", "traj", ".", "Vcut", ",", "reset", "=", "traj", ".", "reset", ",", "namespace", "=", "namespace", ")", "neuron", ".", "vm", "=", "traj", ".", "EL", "neuron", ".", "w", "=", "traj", ".", "a", "*", "(", "neuron", ".", "vm", "-", "traj", ".", "EL", ")", "neuron", ".", "Vr", "=", "linspace", "(", "-", "48.3", "*", "mV", ",", "-", "47.7", "*", "mV", ",", "traj", ".", "N", ")", "# bifurcation parameter", "# Run the network initially for 100 milliseconds", "print", "(", "'Initial Run'", ")", "net", "=", "Network", "(", "neuron", ")", "net", ".", "run", "(", "100", "*", "ms", ",", "report", "=", "'text'", ")", "# we discard the first spikes", "# Create a Spike Monitor", "MSpike", "=", "SpikeMonitor", "(", "neuron", ")", "net", ".", "add", "(", "MSpike", ")", "# Create a State Monitor for the membrane voltage, record from neurons 1-3", "MStateV", "=", "StateMonitor", "(", "neuron", ",", "variables", "=", "[", "'vm'", "]", ",", "record", "=", "[", "1", ",", "2", ",", "3", "]", ")", "net", ".", "add", "(", "MStateV", ")", "# Now record for 500 milliseconds", "print", "(", "'Measurement run'", ")", "net", ".", "run", "(", "500", "*", "ms", ",", "report", "=", "'text'", ")", "# Add the BRAIN monitors", "traj", ".", "v_standard_result", "=", "Brian2MonitorResult", "traj", ".", "f_add_result", "(", "'SpikeMonitor'", ",", "MSpike", ")", "traj", ".", "f_add_result", "(", "'StateMonitorV'", ",", "MStateV", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
euler_scheme
Simulation function for Euler integration. :param traj: Container for parameters and results :param diff_func: The differential equation we want to integrate
examples/example_05_custom_parameter.py
def euler_scheme(traj, diff_func): """Simulation function for Euler integration. :param traj: Container for parameters and results :param diff_func: The differential equation we want to integrate """ steps = traj.steps initial_conditions = traj.initial_conditions dimension = len(initial_conditions) # This array will collect the results result_array = np.zeros((steps,dimension)) # Get the function parameters stored into `traj` as a dictionary # with the (short) names as keys : func_params_dict = traj.func_params.f_to_dict(short_names=True, fast_access=True) # Take initial conditions as first result result_array[0] = initial_conditions # Now we compute the Euler Scheme steps-1 times for idx in range(1,steps): result_array[idx] = diff_func(result_array[idx-1], **func_params_dict) * traj.dt + \ result_array[idx-1] # Note the **func_params_dict unzips the dictionary, it's the reverse of **kwargs in function # definitions! #Finally we want to keep the results traj.f_add_result('euler_evolution', data=result_array, comment='Our time series data!')
def euler_scheme(traj, diff_func): """Simulation function for Euler integration. :param traj: Container for parameters and results :param diff_func: The differential equation we want to integrate """ steps = traj.steps initial_conditions = traj.initial_conditions dimension = len(initial_conditions) # This array will collect the results result_array = np.zeros((steps,dimension)) # Get the function parameters stored into `traj` as a dictionary # with the (short) names as keys : func_params_dict = traj.func_params.f_to_dict(short_names=True, fast_access=True) # Take initial conditions as first result result_array[0] = initial_conditions # Now we compute the Euler Scheme steps-1 times for idx in range(1,steps): result_array[idx] = diff_func(result_array[idx-1], **func_params_dict) * traj.dt + \ result_array[idx-1] # Note the **func_params_dict unzips the dictionary, it's the reverse of **kwargs in function # definitions! #Finally we want to keep the results traj.f_add_result('euler_evolution', data=result_array, comment='Our time series data!')
[ "Simulation", "function", "for", "Euler", "integration", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_05_custom_parameter.py#L19-L52
[ "def", "euler_scheme", "(", "traj", ",", "diff_func", ")", ":", "steps", "=", "traj", ".", "steps", "initial_conditions", "=", "traj", ".", "initial_conditions", "dimension", "=", "len", "(", "initial_conditions", ")", "# This array will collect the results", "result_array", "=", "np", ".", "zeros", "(", "(", "steps", ",", "dimension", ")", ")", "# Get the function parameters stored into `traj` as a dictionary", "# with the (short) names as keys :", "func_params_dict", "=", "traj", ".", "func_params", ".", "f_to_dict", "(", "short_names", "=", "True", ",", "fast_access", "=", "True", ")", "# Take initial conditions as first result", "result_array", "[", "0", "]", "=", "initial_conditions", "# Now we compute the Euler Scheme steps-1 times", "for", "idx", "in", "range", "(", "1", ",", "steps", ")", ":", "result_array", "[", "idx", "]", "=", "diff_func", "(", "result_array", "[", "idx", "-", "1", "]", ",", "*", "*", "func_params_dict", ")", "*", "traj", ".", "dt", "+", "result_array", "[", "idx", "-", "1", "]", "# Note the **func_params_dict unzips the dictionary, it's the reverse of **kwargs in function", "# definitions!", "#Finally we want to keep the results", "traj", ".", "f_add_result", "(", "'euler_evolution'", ",", "data", "=", "result_array", ",", "comment", "=", "'Our time series data!'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
add_parameters
Adds all necessary parameters to the `traj` container
examples/example_05_custom_parameter.py
def add_parameters(traj): """Adds all necessary parameters to the `traj` container""" traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter. We will simulate # a 3-D differential equation, the Lorenz attractor. traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]), comment = 'Our initial conditions, as default we will start from' ' origin!') # We will group all parameters of the Lorenz differential equation into the group 'func_params' traj.f_add_parameter('func_params.sigma', 10.0) traj.f_add_parameter('func_params.beta', 8.0/3.0) traj.f_add_parameter('func_params.rho', 28.0) #For the fun of it we will annotate the group traj.func_params.v_annotations.info='This group contains as default the original values chosen ' \ 'by Edward Lorenz in 1963. Check it out on wikipedia ' \ '(https://en.wikipedia.org/wiki/Lorenz_attractor)!'
def add_parameters(traj): """Adds all necessary parameters to the `traj` container""" traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter. We will simulate # a 3-D differential equation, the Lorenz attractor. traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]), comment = 'Our initial conditions, as default we will start from' ' origin!') # We will group all parameters of the Lorenz differential equation into the group 'func_params' traj.f_add_parameter('func_params.sigma', 10.0) traj.f_add_parameter('func_params.beta', 8.0/3.0) traj.f_add_parameter('func_params.rho', 28.0) #For the fun of it we will annotate the group traj.func_params.v_annotations.info='This group contains as default the original values chosen ' \ 'by Edward Lorenz in 1963. Check it out on wikipedia ' \ '(https://en.wikipedia.org/wiki/Lorenz_attractor)!'
[ "Adds", "all", "necessary", "parameters", "to", "the", "traj", "container" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_05_custom_parameter.py#L103-L123
[ "def", "add_parameters", "(", "traj", ")", ":", "traj", ".", "f_add_parameter", "(", "'steps'", ",", "10000", ",", "comment", "=", "'Number of time steps to simulate'", ")", "traj", ".", "f_add_parameter", "(", "'dt'", ",", "0.01", ",", "comment", "=", "'Step size'", ")", "# Here we want to add the initial conditions as an array parameter. We will simulate", "# a 3-D differential equation, the Lorenz attractor.", "traj", ".", "f_add_parameter", "(", "ArrayParameter", ",", "'initial_conditions'", ",", "np", ".", "array", "(", "[", "0.0", ",", "0.0", ",", "0.0", "]", ")", ",", "comment", "=", "'Our initial conditions, as default we will start from'", "' origin!'", ")", "# We will group all parameters of the Lorenz differential equation into the group 'func_params'", "traj", ".", "f_add_parameter", "(", "'func_params.sigma'", ",", "10.0", ")", "traj", ".", "f_add_parameter", "(", "'func_params.beta'", ",", "8.0", "/", "3.0", ")", "traj", ".", "f_add_parameter", "(", "'func_params.rho'", ",", "28.0", ")", "#For the fun of it we will annotate the group", "traj", ".", "func_params", ".", "v_annotations", ".", "info", "=", "'This group contains as default the original values chosen '", "'by Edward Lorenz in 1963. Check it out on wikipedia '", "'(https://en.wikipedia.org/wiki/Lorenz_attractor)!'" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
diff_lorenz
The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter :return: 3d array of the Lorenz system evaluated at `value_array`
examples/example_05_custom_parameter.py
def diff_lorenz(value_array, sigma, beta, rho): """The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter :return: 3d array of the Lorenz system evaluated at `value_array` """ diff_array = np.zeros(3) diff_array[0] = sigma * (value_array[1]-value_array[0]) diff_array[1] = value_array[0] * (rho - value_array[2]) - value_array[1] diff_array[2] = value_array[0] * value_array[1] - beta * value_array[2] return diff_array
def diff_lorenz(value_array, sigma, beta, rho): """The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter :return: 3d array of the Lorenz system evaluated at `value_array` """ diff_array = np.zeros(3) diff_array[0] = sigma * (value_array[1]-value_array[0]) diff_array[1] = value_array[0] * (rho - value_array[2]) - value_array[1] diff_array[2] = value_array[0] * value_array[1] - beta * value_array[2] return diff_array
[ "The", "Lorenz", "attractor", "differential", "equation" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_05_custom_parameter.py#L128-L144
[ "def", "diff_lorenz", "(", "value_array", ",", "sigma", ",", "beta", ",", "rho", ")", ":", "diff_array", "=", "np", ".", "zeros", "(", "3", ")", "diff_array", "[", "0", "]", "=", "sigma", "*", "(", "value_array", "[", "1", "]", "-", "value_array", "[", "0", "]", ")", "diff_array", "[", "1", "]", "=", "value_array", "[", "0", "]", "*", "(", "rho", "-", "value_array", "[", "2", "]", ")", "-", "value_array", "[", "1", "]", "diff_array", "[", "2", "]", "=", "value_array", "[", "0", "]", "*", "value_array", "[", "1", "]", "-", "beta", "*", "value_array", "[", "2", "]", "return", "diff_array" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
_create_storage
Creates a service from a constructor and checks which kwargs are not used
pypet/utils/storagefactory.py
def _create_storage(storage_service, trajectory=None, **kwargs): """Creates a service from a constructor and checks which kwargs are not used""" kwargs_copy = kwargs.copy() kwargs_copy['trajectory'] = trajectory matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy) storage_service = storage_service(**matching_kwargs) unused_kwargs = set(kwargs.keys()) - set(matching_kwargs.keys()) return storage_service, unused_kwargs
def _create_storage(storage_service, trajectory=None, **kwargs): """Creates a service from a constructor and checks which kwargs are not used""" kwargs_copy = kwargs.copy() kwargs_copy['trajectory'] = trajectory matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy) storage_service = storage_service(**matching_kwargs) unused_kwargs = set(kwargs.keys()) - set(matching_kwargs.keys()) return storage_service, unused_kwargs
[ "Creates", "a", "service", "from", "a", "constructor", "and", "checks", "which", "kwargs", "are", "not", "used" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/storagefactory.py#L18-L25
[ "def", "_create_storage", "(", "storage_service", ",", "trajectory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs_copy", "=", "kwargs", ".", "copy", "(", ")", "kwargs_copy", "[", "'trajectory'", "]", "=", "trajectory", "matching_kwargs", "=", "get_matching_kwargs", "(", "storage_service", ",", "kwargs_copy", ")", "storage_service", "=", "storage_service", "(", "*", "*", "matching_kwargs", ")", "unused_kwargs", "=", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "-", "set", "(", "matching_kwargs", ".", "keys", "(", ")", ")", "return", "storage_service", ",", "unused_kwargs" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
storage_factory
Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :param kwargs: Arguments passed to the storage service :return: A storage service and a set of not used keyword arguments from kwargs
pypet/utils/storagefactory.py
def storage_factory(storage_service, trajectory=None, **kwargs): """Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :param kwargs: Arguments passed to the storage service :return: A storage service and a set of not used keyword arguments from kwargs """ if 'filename' in kwargs and storage_service is None: filename = kwargs['filename'] _, ext = os.path.splitext(filename) if ext in ('.hdf', '.h4', '.hdf4', '.he2', '.h5', '.hdf5', '.he5'): storage_service = HDF5StorageService else: raise ValueError('Extension `%s` of filename `%s` not understood.' % (ext, filename)) elif isinstance(storage_service, str): class_name = storage_service.split('.')[-1] storage_service = create_class(class_name, [storage_service, HDF5StorageService]) if inspect.isclass(storage_service): return _create_storage(storage_service, trajectory, **kwargs) else: return storage_service, set(kwargs.keys())
def storage_factory(storage_service, trajectory=None, **kwargs): """Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :param kwargs: Arguments passed to the storage service :return: A storage service and a set of not used keyword arguments from kwargs """ if 'filename' in kwargs and storage_service is None: filename = kwargs['filename'] _, ext = os.path.splitext(filename) if ext in ('.hdf', '.h4', '.hdf4', '.he2', '.h5', '.hdf5', '.he5'): storage_service = HDF5StorageService else: raise ValueError('Extension `%s` of filename `%s` not understood.' % (ext, filename)) elif isinstance(storage_service, str): class_name = storage_service.split('.')[-1] storage_service = create_class(class_name, [storage_service, HDF5StorageService]) if inspect.isclass(storage_service): return _create_storage(storage_service, trajectory, **kwargs) else: return storage_service, set(kwargs.keys())
[ "Creates", "a", "storage", "service", "to", "be", "extended", "if", "new", "storage", "services", "are", "added" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/storagefactory.py#L28-L64
[ "def", "storage_factory", "(", "storage_service", ",", "trajectory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'filename'", "in", "kwargs", "and", "storage_service", "is", "None", ":", "filename", "=", "kwargs", "[", "'filename'", "]", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "in", "(", "'.hdf'", ",", "'.h4'", ",", "'.hdf4'", ",", "'.he2'", ",", "'.h5'", ",", "'.hdf5'", ",", "'.he5'", ")", ":", "storage_service", "=", "HDF5StorageService", "else", ":", "raise", "ValueError", "(", "'Extension `%s` of filename `%s` not understood.'", "%", "(", "ext", ",", "filename", ")", ")", "elif", "isinstance", "(", "storage_service", ",", "str", ")", ":", "class_name", "=", "storage_service", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "storage_service", "=", "create_class", "(", "class_name", ",", "[", "storage_service", ",", "HDF5StorageService", "]", ")", "if", "inspect", ".", "isclass", "(", "storage_service", ")", ":", "return", "_create_storage", "(", "storage_service", ",", "trajectory", ",", "*", "*", "kwargs", ")", "else", ":", "return", "storage_service", ",", "set", "(", "kwargs", ".", "keys", "(", ")", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
multiply
Example of a sophisticated simulation that involves multiplying two values. :param traj: Trajectory containing the parameters in a particular combination, it also serves as a container for results.
examples/example_14_links.py
def multiply(traj): """Example of a sophisticated simulation that involves multiplying two values. :param traj: Trajectory containing the parameters in a particular combination, it also serves as a container for results. """ z=traj.mylink1*traj.mylink2 # And again we now can also use the different names # due to the creation of links traj.f_add_result('runs.$.z', z, comment='Result of our simulation!')
def multiply(traj): """Example of a sophisticated simulation that involves multiplying two values. :param traj: Trajectory containing the parameters in a particular combination, it also serves as a container for results. """ z=traj.mylink1*traj.mylink2 # And again we now can also use the different names # due to the creation of links traj.f_add_result('runs.$.z', z, comment='Result of our simulation!')
[ "Example", "of", "a", "sophisticated", "simulation", "that", "involves", "multiplying", "two", "values", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_14_links.py#L7-L19
[ "def", "multiply", "(", "traj", ")", ":", "z", "=", "traj", ".", "mylink1", "*", "traj", ".", "mylink2", "# And again we now can also use the different names", "# due to the creation of links", "traj", ".", "f_add_result", "(", "'runs.$.z'", ",", "z", ",", "comment", "=", "'Result of our simulation!'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
add_parameters
Adds all necessary parameters to the `traj` container. You can choose between two parameter sets. One for the Lorenz attractor and one for the Roessler attractor. The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for `traj.diff_name=='diff_roessler'`. You can use parameter presetting to switch between the two cases. :raises: A ValueError if `traj.diff_name` is none of the above
examples/example_06_parameter_presetting.py
def add_parameters(traj): """Adds all necessary parameters to the `traj` container. You can choose between two parameter sets. One for the Lorenz attractor and one for the Roessler attractor. The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for `traj.diff_name=='diff_roessler'`. You can use parameter presetting to switch between the two cases. :raises: A ValueError if `traj.diff_name` is none of the above """ traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter, since we will simulate # a 3-D differential equation, that is the Roessler attractor # (https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor) traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]), comment = 'Our initial conditions, as default we will start from' ' origin!') # Per default we choose the name `'diff_lorenz'` as in the last example traj.f_add_parameter('diff_name','diff_lorenz', comment= 'Name of our differential equation') # We want some control flow depending on which name we really choose if traj.diff_name == 'diff_lorenz': # These parameters are for the Lorenz differential equation traj.f_add_parameter('func_params.sigma', 10.0) traj.f_add_parameter('func_params.beta', 8.0/3.0) traj.f_add_parameter('func_params.rho', 28.0) elif traj.diff_name == 'diff_roessler': # If we use the Roessler system we need different parameters traj.f_add_parameter('func_params.a', 0.1) traj.f_add_parameter('func_params.c', 14.0) else: raise ValueError('I don\'t know what %s is.' % traj.diff_name)
def add_parameters(traj): """Adds all necessary parameters to the `traj` container. You can choose between two parameter sets. One for the Lorenz attractor and one for the Roessler attractor. The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for `traj.diff_name=='diff_roessler'`. You can use parameter presetting to switch between the two cases. :raises: A ValueError if `traj.diff_name` is none of the above """ traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter, since we will simulate # a 3-D differential equation, that is the Roessler attractor # (https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor) traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]), comment = 'Our initial conditions, as default we will start from' ' origin!') # Per default we choose the name `'diff_lorenz'` as in the last example traj.f_add_parameter('diff_name','diff_lorenz', comment= 'Name of our differential equation') # We want some control flow depending on which name we really choose if traj.diff_name == 'diff_lorenz': # These parameters are for the Lorenz differential equation traj.f_add_parameter('func_params.sigma', 10.0) traj.f_add_parameter('func_params.beta', 8.0/3.0) traj.f_add_parameter('func_params.rho', 28.0) elif traj.diff_name == 'diff_roessler': # If we use the Roessler system we need different parameters traj.f_add_parameter('func_params.a', 0.1) traj.f_add_parameter('func_params.c', 14.0) else: raise ValueError('I don\'t know what %s is.' % traj.diff_name)
[ "Adds", "all", "necessary", "parameters", "to", "the", "traj", "container", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_06_parameter_presetting.py#L14-L50
[ "def", "add_parameters", "(", "traj", ")", ":", "traj", ".", "f_add_parameter", "(", "'steps'", ",", "10000", ",", "comment", "=", "'Number of time steps to simulate'", ")", "traj", ".", "f_add_parameter", "(", "'dt'", ",", "0.01", ",", "comment", "=", "'Step size'", ")", "# Here we want to add the initial conditions as an array parameter, since we will simulate", "# a 3-D differential equation, that is the Roessler attractor", "# (https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor)", "traj", ".", "f_add_parameter", "(", "ArrayParameter", ",", "'initial_conditions'", ",", "np", ".", "array", "(", "[", "0.0", ",", "0.0", ",", "0.0", "]", ")", ",", "comment", "=", "'Our initial conditions, as default we will start from'", "' origin!'", ")", "# Per default we choose the name `'diff_lorenz'` as in the last example", "traj", ".", "f_add_parameter", "(", "'diff_name'", ",", "'diff_lorenz'", ",", "comment", "=", "'Name of our differential equation'", ")", "# We want some control flow depending on which name we really choose", "if", "traj", ".", "diff_name", "==", "'diff_lorenz'", ":", "# These parameters are for the Lorenz differential equation", "traj", ".", "f_add_parameter", "(", "'func_params.sigma'", ",", "10.0", ")", "traj", ".", "f_add_parameter", "(", "'func_params.beta'", ",", "8.0", "/", "3.0", ")", "traj", ".", "f_add_parameter", "(", "'func_params.rho'", ",", "28.0", ")", "elif", "traj", ".", "diff_name", "==", "'diff_roessler'", ":", "# If we use the Roessler system we need different parameters", "traj", ".", "f_add_parameter", "(", "'func_params.a'", ",", "0.1", ")", "traj", ".", "f_add_parameter", "(", "'func_params.c'", ",", "14.0", ")", "else", ":", "raise", "ValueError", "(", "'I don\\'t know what %s is.'", "%", "traj", ".", "diff_name", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
diff_roessler
The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_array`
examples/example_06_parameter_presetting.py
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_array` """ b=a diff_array = np.zeros(3) diff_array[0] = -value_array[1] - value_array[2] diff_array[1] = value_array[0] + a * value_array[1] diff_array[2] = b + value_array[2] * (value_array[0] - c) return diff_array
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_array` """ b=a diff_array = np.zeros(3) diff_array[0] = -value_array[1] - value_array[2] diff_array[1] = value_array[0] + a * value_array[1] diff_array[2] = b + value_array[2] * (value_array[0] - c) return diff_array
[ "The", "Roessler", "attractor", "differential", "equation" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_06_parameter_presetting.py#L56-L72
[ "def", "diff_roessler", "(", "value_array", ",", "a", ",", "c", ")", ":", "b", "=", "a", "diff_array", "=", "np", ".", "zeros", "(", "3", ")", "diff_array", "[", "0", "]", "=", "-", "value_array", "[", "1", "]", "-", "value_array", "[", "2", "]", "diff_array", "[", "1", "]", "=", "value_array", "[", "0", "]", "+", "a", "*", "value_array", "[", "1", "]", "diff_array", "[", "2", "]", "=", "b", "+", "value_array", "[", "2", "]", "*", "(", "value_array", "[", "0", "]", "-", "c", ")", "return", "diff_array" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
compact_hdf5_file
Can compress an HDF5 to reduce file size. The properties on how to compress the new file are taken from a given trajectory in the file. Simply calls ``ptrepack`` from the command line. (Se also https://pytables.github.io/usersguide/utilities.html#ptrepackdescr) Currently only supported under Linux, no guarantee for Windows usage. :param filename: Name of the file to compact :param name: The name of the trajectory from which the compression properties are taken :param index: Instead of a name you could also specify an index, i.e -1 for the last trajectory in the file. :param keep_backup: If a back up version of the original file should be kept. The backup file is named as the original but `_backup` is appended to the end. :return: The return/error code of ptrepack
pypet/utils/hdf5compression.py
def compact_hdf5_file(filename, name=None, index=None, keep_backup=True): """Can compress an HDF5 to reduce file size. The properties on how to compress the new file are taken from a given trajectory in the file. Simply calls ``ptrepack`` from the command line. (Se also https://pytables.github.io/usersguide/utilities.html#ptrepackdescr) Currently only supported under Linux, no guarantee for Windows usage. :param filename: Name of the file to compact :param name: The name of the trajectory from which the compression properties are taken :param index: Instead of a name you could also specify an index, i.e -1 for the last trajectory in the file. :param keep_backup: If a back up version of the original file should be kept. The backup file is named as the original but `_backup` is appended to the end. :return: The return/error code of ptrepack """ if name is None and index is None: index = -1 tmp_traj = load_trajectory(name, index, as_new=False, load_all=pypetconstants.LOAD_NOTHING, force=True, filename=filename) service = tmp_traj.v_storage_service complevel = service.complevel complib = service.complib shuffle = service.shuffle fletcher32 = service.fletcher32 name_wo_ext, ext = os.path.splitext(filename) tmp_filename = name_wo_ext + '_tmp' + ext abs_filename = os.path.abspath(filename) abs_tmp_filename = os.path.abspath(tmp_filename) command = ['ptrepack', '-v', '--complib', complib, '--complevel', str(complevel), '--shuffle', str(int(shuffle)), '--fletcher32', str(int(fletcher32)), abs_filename, abs_tmp_filename] str_command = ' '.join(command) print('Executing command `%s`' % str_command) retcode = subprocess.call(command) if retcode != 0: print('#### ERROR: Compacting `%s` failed with errorcode %s! ####' % (filename, str(retcode))) else: print('#### Compacting successful ####') print('Renaming files') if keep_backup: backup_file_name = name_wo_ext + '_backup' + ext os.rename(filename, backup_file_name) else: os.remove(filename) os.rename(tmp_filename, filename) print('### Compacting and Renaming finished ####') return retcode
def compact_hdf5_file(filename, name=None, index=None, keep_backup=True): """Can compress an HDF5 to reduce file size. The properties on how to compress the new file are taken from a given trajectory in the file. Simply calls ``ptrepack`` from the command line. (Se also https://pytables.github.io/usersguide/utilities.html#ptrepackdescr) Currently only supported under Linux, no guarantee for Windows usage. :param filename: Name of the file to compact :param name: The name of the trajectory from which the compression properties are taken :param index: Instead of a name you could also specify an index, i.e -1 for the last trajectory in the file. :param keep_backup: If a back up version of the original file should be kept. The backup file is named as the original but `_backup` is appended to the end. :return: The return/error code of ptrepack """ if name is None and index is None: index = -1 tmp_traj = load_trajectory(name, index, as_new=False, load_all=pypetconstants.LOAD_NOTHING, force=True, filename=filename) service = tmp_traj.v_storage_service complevel = service.complevel complib = service.complib shuffle = service.shuffle fletcher32 = service.fletcher32 name_wo_ext, ext = os.path.splitext(filename) tmp_filename = name_wo_ext + '_tmp' + ext abs_filename = os.path.abspath(filename) abs_tmp_filename = os.path.abspath(tmp_filename) command = ['ptrepack', '-v', '--complib', complib, '--complevel', str(complevel), '--shuffle', str(int(shuffle)), '--fletcher32', str(int(fletcher32)), abs_filename, abs_tmp_filename] str_command = ' '.join(command) print('Executing command `%s`' % str_command) retcode = subprocess.call(command) if retcode != 0: print('#### ERROR: Compacting `%s` failed with errorcode %s! ####' % (filename, str(retcode))) else: print('#### Compacting successful ####') print('Renaming files') if keep_backup: backup_file_name = name_wo_ext + '_backup' + ext os.rename(filename, backup_file_name) else: os.remove(filename) os.rename(tmp_filename, filename) print('### Compacting and Renaming finished ####') return retcode
[ "Can", "compress", "an", "HDF5", "to", "reduce", "file", "size", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/hdf5compression.py#L12-L86
[ "def", "compact_hdf5_file", "(", "filename", ",", "name", "=", "None", ",", "index", "=", "None", ",", "keep_backup", "=", "True", ")", ":", "if", "name", "is", "None", "and", "index", "is", "None", ":", "index", "=", "-", "1", "tmp_traj", "=", "load_trajectory", "(", "name", ",", "index", ",", "as_new", "=", "False", ",", "load_all", "=", "pypetconstants", ".", "LOAD_NOTHING", ",", "force", "=", "True", ",", "filename", "=", "filename", ")", "service", "=", "tmp_traj", ".", "v_storage_service", "complevel", "=", "service", ".", "complevel", "complib", "=", "service", ".", "complib", "shuffle", "=", "service", ".", "shuffle", "fletcher32", "=", "service", ".", "fletcher32", "name_wo_ext", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "tmp_filename", "=", "name_wo_ext", "+", "'_tmp'", "+", "ext", "abs_filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "abs_tmp_filename", "=", "os", ".", "path", ".", "abspath", "(", "tmp_filename", ")", "command", "=", "[", "'ptrepack'", ",", "'-v'", ",", "'--complib'", ",", "complib", ",", "'--complevel'", ",", "str", "(", "complevel", ")", ",", "'--shuffle'", ",", "str", "(", "int", "(", "shuffle", ")", ")", ",", "'--fletcher32'", ",", "str", "(", "int", "(", "fletcher32", ")", ")", ",", "abs_filename", ",", "abs_tmp_filename", "]", "str_command", "=", "' '", ".", "join", "(", "command", ")", "print", "(", "'Executing command `%s`'", "%", "str_command", ")", "retcode", "=", "subprocess", ".", "call", "(", "command", ")", "if", "retcode", "!=", "0", ":", "print", "(", "'#### ERROR: Compacting `%s` failed with errorcode %s! ####'", "%", "(", "filename", ",", "str", "(", "retcode", ")", ")", ")", "else", ":", "print", "(", "'#### Compacting successful ####'", ")", "print", "(", "'Renaming files'", ")", "if", "keep_backup", ":", "backup_file_name", "=", "name_wo_ext", "+", "'_backup'", "+", "ext", "os", ".", "rename", "(", "filename", ",", "backup_file_name", ")", "else", ":", "os", ".", "remove", "(", "filename", ")", "os", ".", "rename", "(", "tmp_filename", ",", "filename", ")", "print", "(", "'### Compacting and Renaming finished ####'", ")", "return", "retcode" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
_explored_parameters_in_group
Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False`
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if param in group_node: explored = True break return explored
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if param in group_node: explored = True break return explored
[ "Checks", "if", "one", "the", "parameters", "in", "group_node", "is", "explored", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L16-L30
[ "def", "_explored_parameters_in_group", "(", "traj", ",", "group_node", ")", ":", "explored", "=", "False", "for", "param", "in", "traj", ".", "f_get_explored_parameters", "(", ")", ":", "if", "param", "in", "group_node", ":", "explored", "=", "True", "break", "return", "explored" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNeuronGroup.add_parameters
Adds all neuron group parameters to `traj`.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) scale = traj.simulation.scale traj.v_standard_parameter = Brian2Parameter model_eqs = '''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1 mu : 1 I_syn = - I_syn_i + I_syn_e : Hz ''' conn_eqs = '''I_syn_PRE = x_PRE/(tau2_PRE-tau1_PRE) : Hz dx_PRE/dt = -(normalization_PRE*y_PRE+x_PRE)*invtau1_PRE : 1 dy_PRE/dt = -y_PRE*invtau2_PRE : 1 ''' traj.f_add_parameter('model.eqs', model_eqs, comment='The differential equation for the neuron model') traj.f_add_parameter('model.synaptic.eqs', conn_eqs, comment='The differential equation for the synapses. ' 'PRE will be replaced by `i` or `e` depending ' 'on the source population') traj.f_add_parameter('model.synaptic.tau1', 1*ms, comment = 'The decay time') traj.f_add_parameter('model.synaptic.tau2_e', 3*ms, comment = 'The rise time, excitatory') traj.f_add_parameter('model.synaptic.tau2_i', 2*ms, comment = 'The rise time, inhibitory') traj.f_add_parameter('model.V_th', 'V >= 1.0', comment = "Threshold value") traj.f_add_parameter('model.reset_func', 'V=0.0', comment = "String representation of reset function") traj.f_add_parameter('model.refractory', 5*ms, comment = "Absolute refractory period") traj.f_add_parameter('model.N_e', int(2000*scale), comment = "Amount of excitatory neurons") traj.f_add_parameter('model.N_i', int(500*scale), comment = "Amount of inhibitory neurons") traj.f_add_parameter('model.tau_e', 15*ms, comment = "Membrane time constant, excitatory") traj.f_add_parameter('model.tau_i', 10*ms, comment = "Membrane time constant, inhibitory") traj.f_add_parameter('model.mu_e_min', 1.1, comment = "Lower bound for bias, excitatory") traj.f_add_parameter('model.mu_e_max', 1.2, comment = "Upper bound for bias, excitatory") traj.f_add_parameter('model.mu_i_min', 1.0, comment = "Lower bound for bias, inhibitory") traj.f_add_parameter('model.mu_i_max', 1.05, comment = "Upper bound for bias, inhibitory")
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) scale = traj.simulation.scale traj.v_standard_parameter = Brian2Parameter model_eqs = '''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1 mu : 1 I_syn = - I_syn_i + I_syn_e : Hz ''' conn_eqs = '''I_syn_PRE = x_PRE/(tau2_PRE-tau1_PRE) : Hz dx_PRE/dt = -(normalization_PRE*y_PRE+x_PRE)*invtau1_PRE : 1 dy_PRE/dt = -y_PRE*invtau2_PRE : 1 ''' traj.f_add_parameter('model.eqs', model_eqs, comment='The differential equation for the neuron model') traj.f_add_parameter('model.synaptic.eqs', conn_eqs, comment='The differential equation for the synapses. ' 'PRE will be replaced by `i` or `e` depending ' 'on the source population') traj.f_add_parameter('model.synaptic.tau1', 1*ms, comment = 'The decay time') traj.f_add_parameter('model.synaptic.tau2_e', 3*ms, comment = 'The rise time, excitatory') traj.f_add_parameter('model.synaptic.tau2_i', 2*ms, comment = 'The rise time, inhibitory') traj.f_add_parameter('model.V_th', 'V >= 1.0', comment = "Threshold value") traj.f_add_parameter('model.reset_func', 'V=0.0', comment = "String representation of reset function") traj.f_add_parameter('model.refractory', 5*ms, comment = "Absolute refractory period") traj.f_add_parameter('model.N_e', int(2000*scale), comment = "Amount of excitatory neurons") traj.f_add_parameter('model.N_i', int(500*scale), comment = "Amount of inhibitory neurons") traj.f_add_parameter('model.tau_e', 15*ms, comment = "Membrane time constant, excitatory") traj.f_add_parameter('model.tau_i', 10*ms, comment = "Membrane time constant, inhibitory") traj.f_add_parameter('model.mu_e_min', 1.1, comment = "Lower bound for bias, excitatory") traj.f_add_parameter('model.mu_e_max', 1.2, comment = "Upper bound for bias, excitatory") traj.f_add_parameter('model.mu_i_min', 1.0, comment = "Lower bound for bias, inhibitory") traj.f_add_parameter('model.mu_i_max', 1.05, comment = "Upper bound for bias, inhibitory")
[ "Adds", "all", "neuron", "group", "parameters", "to", "traj", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L40-L86
[ "def", "add_parameters", "(", "traj", ")", ":", "assert", "(", "isinstance", "(", "traj", ",", "Trajectory", ")", ")", "scale", "=", "traj", ".", "simulation", ".", "scale", "traj", ".", "v_standard_parameter", "=", "Brian2Parameter", "model_eqs", "=", "'''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1\n mu : 1\n I_syn = - I_syn_i + I_syn_e : Hz\n '''", "conn_eqs", "=", "'''I_syn_PRE = x_PRE/(tau2_PRE-tau1_PRE) : Hz\n dx_PRE/dt = -(normalization_PRE*y_PRE+x_PRE)*invtau1_PRE : 1\n dy_PRE/dt = -y_PRE*invtau2_PRE : 1\n '''", "traj", ".", "f_add_parameter", "(", "'model.eqs'", ",", "model_eqs", ",", "comment", "=", "'The differential equation for the neuron model'", ")", "traj", ".", "f_add_parameter", "(", "'model.synaptic.eqs'", ",", "conn_eqs", ",", "comment", "=", "'The differential equation for the synapses. '", "'PRE will be replaced by `i` or `e` depending '", "'on the source population'", ")", "traj", ".", "f_add_parameter", "(", "'model.synaptic.tau1'", ",", "1", "*", "ms", ",", "comment", "=", "'The decay time'", ")", "traj", ".", "f_add_parameter", "(", "'model.synaptic.tau2_e'", ",", "3", "*", "ms", ",", "comment", "=", "'The rise time, excitatory'", ")", "traj", ".", "f_add_parameter", "(", "'model.synaptic.tau2_i'", ",", "2", "*", "ms", ",", "comment", "=", "'The rise time, inhibitory'", ")", "traj", ".", "f_add_parameter", "(", "'model.V_th'", ",", "'V >= 1.0'", ",", "comment", "=", "\"Threshold value\"", ")", "traj", ".", "f_add_parameter", "(", "'model.reset_func'", ",", "'V=0.0'", ",", "comment", "=", "\"String representation of reset function\"", ")", "traj", ".", "f_add_parameter", "(", "'model.refractory'", ",", "5", "*", "ms", ",", "comment", "=", "\"Absolute refractory period\"", ")", "traj", ".", "f_add_parameter", "(", "'model.N_e'", ",", "int", "(", "2000", "*", "scale", ")", ",", "comment", "=", "\"Amount of excitatory neurons\"", ")", "traj", ".", "f_add_parameter", "(", "'model.N_i'", ",", "int", "(", "500", "*", "scale", ")", ",", "comment", "=", "\"Amount of inhibitory neurons\"", ")", "traj", ".", "f_add_parameter", "(", "'model.tau_e'", ",", "15", "*", "ms", ",", "comment", "=", "\"Membrane time constant, excitatory\"", ")", "traj", ".", "f_add_parameter", "(", "'model.tau_i'", ",", "10", "*", "ms", ",", "comment", "=", "\"Membrane time constant, inhibitory\"", ")", "traj", ".", "f_add_parameter", "(", "'model.mu_e_min'", ",", "1.1", ",", "comment", "=", "\"Lower bound for bias, excitatory\"", ")", "traj", ".", "f_add_parameter", "(", "'model.mu_e_max'", ",", "1.2", ",", "comment", "=", "\"Upper bound for bias, excitatory\"", ")", "traj", ".", "f_add_parameter", "(", "'model.mu_i_min'", ",", "1.0", ",", "comment", "=", "\"Lower bound for bias, inhibitory\"", ")", "traj", ".", "f_add_parameter", "(", "'model.mu_i_max'", ",", "1.05", ",", "comment", "=", "\"Upper bound for bias, inhibitory\"", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNeuronGroup._build_model_eqs
Computes model equations for the excitatory and inhibitory population. Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs` and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending on the type of population. :return: Dictionary with 'i' equation object for inhibitory neurons and 'e' for excitatory
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _build_model_eqs(traj): """Computes model equations for the excitatory and inhibitory population. Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs` and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending on the type of population. :return: Dictionary with 'i' equation object for inhibitory neurons and 'e' for excitatory """ model_eqs = traj.model.eqs post_eqs={} for name_post in ['i','e']: variables_dict ={} new_model_eqs=model_eqs.replace('POST', name_post) for name_pre in ['i', 'e']: conn_eqs = traj.model.synaptic.eqs new_conn_eqs = conn_eqs.replace('PRE', name_pre) new_model_eqs += new_conn_eqs tau1 = traj.model.synaptic['tau1'] tau2 = traj.model.synaptic['tau2_'+name_pre] normalization = (tau1-tau2) / tau2 invtau1=1.0/tau1 invtau2 = 1.0/tau2 variables_dict['invtau1_'+name_pre] = invtau1 variables_dict['invtau2_'+name_pre] = invtau2 variables_dict['normalization_'+name_pre] = normalization variables_dict['tau1_'+name_pre] = tau1 variables_dict['tau2_'+name_pre] = tau2 variables_dict['tau_'+name_post] = traj.model['tau_'+name_post] post_eqs[name_post] = Equations(new_model_eqs, **variables_dict) return post_eqs
def _build_model_eqs(traj): """Computes model equations for the excitatory and inhibitory population. Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs` and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending on the type of population. :return: Dictionary with 'i' equation object for inhibitory neurons and 'e' for excitatory """ model_eqs = traj.model.eqs post_eqs={} for name_post in ['i','e']: variables_dict ={} new_model_eqs=model_eqs.replace('POST', name_post) for name_pre in ['i', 'e']: conn_eqs = traj.model.synaptic.eqs new_conn_eqs = conn_eqs.replace('PRE', name_pre) new_model_eqs += new_conn_eqs tau1 = traj.model.synaptic['tau1'] tau2 = traj.model.synaptic['tau2_'+name_pre] normalization = (tau1-tau2) / tau2 invtau1=1.0/tau1 invtau2 = 1.0/tau2 variables_dict['invtau1_'+name_pre] = invtau1 variables_dict['invtau2_'+name_pre] = invtau2 variables_dict['normalization_'+name_pre] = normalization variables_dict['tau1_'+name_pre] = tau1 variables_dict['tau2_'+name_pre] = tau2 variables_dict['tau_'+name_post] = traj.model['tau_'+name_post] post_eqs[name_post] = Equations(new_model_eqs, **variables_dict) return post_eqs
[ "Computes", "model", "equations", "for", "the", "excitatory", "and", "inhibitory", "population", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L90-L127
[ "def", "_build_model_eqs", "(", "traj", ")", ":", "model_eqs", "=", "traj", ".", "model", ".", "eqs", "post_eqs", "=", "{", "}", "for", "name_post", "in", "[", "'i'", ",", "'e'", "]", ":", "variables_dict", "=", "{", "}", "new_model_eqs", "=", "model_eqs", ".", "replace", "(", "'POST'", ",", "name_post", ")", "for", "name_pre", "in", "[", "'i'", ",", "'e'", "]", ":", "conn_eqs", "=", "traj", ".", "model", ".", "synaptic", ".", "eqs", "new_conn_eqs", "=", "conn_eqs", ".", "replace", "(", "'PRE'", ",", "name_pre", ")", "new_model_eqs", "+=", "new_conn_eqs", "tau1", "=", "traj", ".", "model", ".", "synaptic", "[", "'tau1'", "]", "tau2", "=", "traj", ".", "model", ".", "synaptic", "[", "'tau2_'", "+", "name_pre", "]", "normalization", "=", "(", "tau1", "-", "tau2", ")", "/", "tau2", "invtau1", "=", "1.0", "/", "tau1", "invtau2", "=", "1.0", "/", "tau2", "variables_dict", "[", "'invtau1_'", "+", "name_pre", "]", "=", "invtau1", "variables_dict", "[", "'invtau2_'", "+", "name_pre", "]", "=", "invtau2", "variables_dict", "[", "'normalization_'", "+", "name_pre", "]", "=", "normalization", "variables_dict", "[", "'tau1_'", "+", "name_pre", "]", "=", "tau1", "variables_dict", "[", "'tau2_'", "+", "name_pre", "]", "=", "tau2", "variables_dict", "[", "'tau_'", "+", "name_post", "]", "=", "traj", ".", "model", "[", "'tau_'", "+", "name_post", "]", "post_eqs", "[", "name_post", "]", "=", "Equations", "(", "new_model_eqs", ",", "*", "*", "variables_dict", ")", "return", "post_eqs" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNeuronGroup.pre_build
Pre-builds the neuron groups. Pre-build is only performed if none of the relevant parameters is explored. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group
examples/example_24_large_scale_brian2_simulation/clusternet.py
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the neuron groups. Pre-build is only performed if none of the relevant parameters is explored. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.model) if self._pre_build: self._build_model(traj, brian_list, network_dict)
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the neuron groups. Pre-build is only performed if none of the relevant parameters is explored. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.model) if self._pre_build: self._build_model(traj, brian_list, network_dict)
[ "Pre", "-", "builds", "the", "neuron", "groups", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L129-L161
[ "def", "pre_build", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "self", ".", "_pre_build", "=", "not", "_explored_parameters_in_group", "(", "traj", ",", "traj", ".", "parameters", ".", "model", ")", "if", "self", ".", "_pre_build", ":", "self", ".", "_build_model", "(", "traj", ",", "brian_list", ",", "network_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNeuronGroup.build
Builds the neuron groups. Build is only performed if neuron group was not pre-build before. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group
examples/example_24_large_scale_brian2_simulation/clusternet.py
def build(self, traj, brian_list, network_dict): """Builds the neuron groups. Build is only performed if neuron group was not pre-build before. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group """ if not hasattr(self, '_pre_build') or not self._pre_build: self._build_model(traj, brian_list, network_dict)
def build(self, traj, brian_list, network_dict): """Builds the neuron groups. Build is only performed if neuron group was not pre-build before. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Inhibitory neuron group Excitatory neuron group :param network_dict: Dictionary of elements shared among the components Adds: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group """ if not hasattr(self, '_pre_build') or not self._pre_build: self._build_model(traj, brian_list, network_dict)
[ "Builds", "the", "neuron", "groups", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L164-L194
[ "def", "build", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_pre_build'", ")", "or", "not", "self", ".", "_pre_build", ":", "self", ".", "_build_model", "(", "traj", ",", "brian_list", ",", "network_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNeuronGroup._build_model
Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _build_model(self, traj, brian_list, network_dict): """Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`. """ model = traj.parameters.model # Create the equations for both models eqs_dict = self._build_model_eqs(traj) # Create inhibitory neurons eqs_i = eqs_dict['i'] neurons_i = NeuronGroup(N=model.N_i, model = eqs_i, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, method='Euler') # Create excitatory neurons eqs_e = eqs_dict['e'] neurons_e = NeuronGroup(N=model.N_e, model = eqs_e, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, method='Euler') # Set the bias terms neurons_e.mu =rand(model.N_e) * (model.mu_e_max - model.mu_e_min) + model.mu_e_min neurons_i.mu =rand(model.N_i) * (model.mu_i_max - model.mu_i_min) + model.mu_i_min # Set initial membrane potentials neurons_e.V = rand(model.N_e) neurons_i.V = rand(model.N_i) # Add both groups to the `brian_list` and the `network_dict` brian_list.append(neurons_i) brian_list.append(neurons_e) network_dict['neurons_e']=neurons_e network_dict['neurons_i']=neurons_i
def _build_model(self, traj, brian_list, network_dict): """Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`. """ model = traj.parameters.model # Create the equations for both models eqs_dict = self._build_model_eqs(traj) # Create inhibitory neurons eqs_i = eqs_dict['i'] neurons_i = NeuronGroup(N=model.N_i, model = eqs_i, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, method='Euler') # Create excitatory neurons eqs_e = eqs_dict['e'] neurons_e = NeuronGroup(N=model.N_e, model = eqs_e, threshold=model.V_th, reset=model.reset_func, refractory=model.refractory, method='Euler') # Set the bias terms neurons_e.mu =rand(model.N_e) * (model.mu_e_max - model.mu_e_min) + model.mu_e_min neurons_i.mu =rand(model.N_i) * (model.mu_i_max - model.mu_i_min) + model.mu_i_min # Set initial membrane potentials neurons_e.V = rand(model.N_e) neurons_i.V = rand(model.N_i) # Add both groups to the `brian_list` and the `network_dict` brian_list.append(neurons_i) brian_list.append(neurons_e) network_dict['neurons_e']=neurons_e network_dict['neurons_i']=neurons_i
[ "Builds", "the", "neuron", "groups", "from", "traj", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L197-L240
[ "def", "_build_model", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "model", "=", "traj", ".", "parameters", ".", "model", "# Create the equations for both models", "eqs_dict", "=", "self", ".", "_build_model_eqs", "(", "traj", ")", "# Create inhibitory neurons", "eqs_i", "=", "eqs_dict", "[", "'i'", "]", "neurons_i", "=", "NeuronGroup", "(", "N", "=", "model", ".", "N_i", ",", "model", "=", "eqs_i", ",", "threshold", "=", "model", ".", "V_th", ",", "reset", "=", "model", ".", "reset_func", ",", "refractory", "=", "model", ".", "refractory", ",", "method", "=", "'Euler'", ")", "# Create excitatory neurons", "eqs_e", "=", "eqs_dict", "[", "'e'", "]", "neurons_e", "=", "NeuronGroup", "(", "N", "=", "model", ".", "N_e", ",", "model", "=", "eqs_e", ",", "threshold", "=", "model", ".", "V_th", ",", "reset", "=", "model", ".", "reset_func", ",", "refractory", "=", "model", ".", "refractory", ",", "method", "=", "'Euler'", ")", "# Set the bias terms", "neurons_e", ".", "mu", "=", "rand", "(", "model", ".", "N_e", ")", "*", "(", "model", ".", "mu_e_max", "-", "model", ".", "mu_e_min", ")", "+", "model", ".", "mu_e_min", "neurons_i", ".", "mu", "=", "rand", "(", "model", ".", "N_i", ")", "*", "(", "model", ".", "mu_i_max", "-", "model", ".", "mu_i_min", ")", "+", "model", ".", "mu_i_min", "# Set initial membrane potentials", "neurons_e", ".", "V", "=", "rand", "(", "model", ".", "N_e", ")", "neurons_i", ".", "V", "=", "rand", "(", "model", ".", "N_i", ")", "# Add both groups to the `brian_list` and the `network_dict`", "brian_list", ".", "append", "(", "neurons_i", ")", "brian_list", ".", "append", "(", "neurons_e", ")", "network_dict", "[", "'neurons_e'", "]", "=", "neurons_e", "network_dict", "[", "'neurons_i'", "]", "=", "neurons_i" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNConnections.add_parameters
Adds all neuron group parameters to `traj`.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) traj.v_standard_parameter = Brian2Parameter scale = traj.simulation.scale traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering') traj.f_add_parameter('connections.clustersize_e', 100, comment='Size of a cluster') traj.f_add_parameter('connections.strength_factor', 2.5, comment='Factor for scaling cluster weights') traj.f_add_parameter('connections.p_ii', 0.25, comment='Connection probability from inhibitory to inhibitory' ) traj.f_add_parameter('connections.p_ei', 0.25, comment='Connection probability from inhibitory to excitatory' ) traj.f_add_parameter('connections.p_ie', 0.25, comment='Connection probability from excitatory to inhibitory' ) traj.f_add_parameter('connections.p_ee', 0.1, comment='Connection probability from excitatory to excitatory' ) traj.f_add_parameter('connections.J_ii', 0.027/np.sqrt(scale), comment='Connection strength from inhibitory to inhibitory') traj.f_add_parameter('connections.J_ei', 0.032/np.sqrt(scale), comment='Connection strength from inhibitory to excitatroy') traj.f_add_parameter('connections.J_ie', 0.009/np.sqrt(scale), comment='Connection strength from excitatory to inhibitory') traj.f_add_parameter('connections.J_ee', 0.012/np.sqrt(scale), comment='Connection strength from excitatory to excitatory')
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) traj.v_standard_parameter = Brian2Parameter scale = traj.simulation.scale traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering') traj.f_add_parameter('connections.clustersize_e', 100, comment='Size of a cluster') traj.f_add_parameter('connections.strength_factor', 2.5, comment='Factor for scaling cluster weights') traj.f_add_parameter('connections.p_ii', 0.25, comment='Connection probability from inhibitory to inhibitory' ) traj.f_add_parameter('connections.p_ei', 0.25, comment='Connection probability from inhibitory to excitatory' ) traj.f_add_parameter('connections.p_ie', 0.25, comment='Connection probability from excitatory to inhibitory' ) traj.f_add_parameter('connections.p_ee', 0.1, comment='Connection probability from excitatory to excitatory' ) traj.f_add_parameter('connections.J_ii', 0.027/np.sqrt(scale), comment='Connection strength from inhibitory to inhibitory') traj.f_add_parameter('connections.J_ei', 0.032/np.sqrt(scale), comment='Connection strength from inhibitory to excitatroy') traj.f_add_parameter('connections.J_ie', 0.009/np.sqrt(scale), comment='Connection strength from excitatory to inhibitory') traj.f_add_parameter('connections.J_ee', 0.012/np.sqrt(scale), comment='Connection strength from excitatory to excitatory')
[ "Adds", "all", "neuron", "group", "parameters", "to", "traj", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L255-L284
[ "def", "add_parameters", "(", "traj", ")", ":", "assert", "(", "isinstance", "(", "traj", ",", "Trajectory", ")", ")", "traj", ".", "v_standard_parameter", "=", "Brian2Parameter", "scale", "=", "traj", ".", "simulation", ".", "scale", "traj", ".", "f_add_parameter", "(", "'connections.R_ee'", ",", "1.0", ",", "comment", "=", "'Scaling factor for clustering'", ")", "traj", ".", "f_add_parameter", "(", "'connections.clustersize_e'", ",", "100", ",", "comment", "=", "'Size of a cluster'", ")", "traj", ".", "f_add_parameter", "(", "'connections.strength_factor'", ",", "2.5", ",", "comment", "=", "'Factor for scaling cluster weights'", ")", "traj", ".", "f_add_parameter", "(", "'connections.p_ii'", ",", "0.25", ",", "comment", "=", "'Connection probability from inhibitory to inhibitory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.p_ei'", ",", "0.25", ",", "comment", "=", "'Connection probability from inhibitory to excitatory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.p_ie'", ",", "0.25", ",", "comment", "=", "'Connection probability from excitatory to inhibitory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.p_ee'", ",", "0.1", ",", "comment", "=", "'Connection probability from excitatory to excitatory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.J_ii'", ",", "0.027", "/", "np", ".", "sqrt", "(", "scale", ")", ",", "comment", "=", "'Connection strength from inhibitory to inhibitory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.J_ei'", ",", "0.032", "/", "np", ".", "sqrt", "(", "scale", ")", ",", "comment", "=", "'Connection strength from inhibitory to excitatroy'", ")", "traj", ".", "f_add_parameter", "(", "'connections.J_ie'", ",", "0.009", "/", "np", ".", "sqrt", "(", "scale", ")", ",", "comment", "=", "'Connection strength from excitatory to inhibitory'", ")", "traj", ".", "f_add_parameter", "(", "'connections.J_ee'", ",", "0.012", "/", "np", ".", "sqrt", "(", "scale", ")", ",", "comment", "=", "'Connection strength from excitatory to excitatory'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNConnections.pre_build
Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering
examples/example_24_large_scale_brian2_simulation/clusternet.py
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.connections) self._pre_build = (self._pre_build and 'neurons_i' in network_dict and 'neurons_e' in network_dict) if self._pre_build: self._build_connections(traj, brian_list, network_dict)
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ self._pre_build = not _explored_parameters_in_group(traj, traj.parameters.connections) self._pre_build = (self._pre_build and 'neurons_i' in network_dict and 'neurons_e' in network_dict) if self._pre_build: self._build_connections(traj, brian_list, network_dict)
[ "Pre", "-", "builds", "the", "connections", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L287-L325
[ "def", "pre_build", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "self", ".", "_pre_build", "=", "not", "_explored_parameters_in_group", "(", "traj", ",", "traj", ".", "parameters", ".", "connections", ")", "self", ".", "_pre_build", "=", "(", "self", ".", "_pre_build", "and", "'neurons_i'", "in", "network_dict", "and", "'neurons_e'", "in", "network_dict", ")", "if", "self", ".", "_pre_build", ":", "self", ".", "_build_connections", "(", "traj", ",", "brian_list", ",", "network_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNConnections.build
Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering
examples/example_24_large_scale_brian2_simulation/clusternet.py
def build(self, traj, brian_list, network_dict): """Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ if not hasattr(self, '_pre_build') or not self._pre_build: self._build_connections(traj, brian_list, network_dict)
def build(self, traj, brian_list, network_dict): """Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds: Connections, amount depends on clustering :param network_dict: Dictionary of elements shared among the components Expects: 'neurons_i': Inhibitory neuron group 'neurons_e': Excitatory neuron group Adds: Connections, amount depends on clustering """ if not hasattr(self, '_pre_build') or not self._pre_build: self._build_connections(traj, brian_list, network_dict)
[ "Builds", "the", "connections", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L328-L360
[ "def", "build", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_pre_build'", ")", "or", "not", "self", ".", "_pre_build", ":", "self", ".", "_build_connections", "(", "traj", ",", "brian_list", ",", "network_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNConnections._build_connections
Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _build_connections(self, traj, brian_list, network_dict): """Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`. """ connections = traj.connections neurons_i = network_dict['neurons_i'] neurons_e = network_dict['neurons_e'] print('Connecting ii') self.conn_ii = Synapses(neurons_i,neurons_i, on_pre='y_i += %f' % connections.J_ii) self.conn_ii.connect('i != j', p=connections.p_ii) print('Connecting ei') self.conn_ei = Synapses(neurons_i,neurons_e, on_pre='y_i += %f' % connections.J_ei) self.conn_ei.connect('i != j', p=connections.p_ei) print('Connecting ie') self.conn_ie = Synapses(neurons_e,neurons_i, on_pre='y_e += %f' % connections.J_ie) self.conn_ie.connect('i != j', p=connections.p_ie) conns_list = [self.conn_ii, self.conn_ei, self.conn_ie] if connections.R_ee > 1.0: # If we come here we want to create clusters cluster_list=[] cluster_conns_list=[] model=traj.model # Compute the number of clusters clusters = int(model.N_e/connections.clustersize_e) traj.f_add_derived_parameter('connections.clusters', clusters, comment='Number of clusters') # Compute outgoing connection probability p_out = (connections.p_ee*model.N_e) / \ (connections.R_ee*connections.clustersize_e+model.N_e- connections.clustersize_e) # Compute within cluster connection probability p_in = p_out * connections.R_ee # We keep these derived parameters traj.f_add_derived_parameter('connections.p_ee_in', p_in , comment='Connection prob within cluster') traj.f_add_derived_parameter('connections.p_ee_out', p_out , comment='Connection prob to outside of cluster') low_index = 0 high_index = connections.clustersize_e # Iterate through cluster and connect within clusters and to the rest of the neurons for irun in range(clusters): cluster = neurons_e[low_index:high_index] # Connections within cluster print('Connecting ee cluster #%d of %d' % (irun, clusters)) conn = Synapses(cluster,cluster, on_pre='y_e += %f' % (connections.J_ee*connections.strength_factor)) conn.connect('i != j', p=p_in) cluster_conns_list.append(conn) # Connections reaching out from cluster # A cluster consists of `clustersize_e` neurons with consecutive indices. # So usually the outside world consists of two groups, neurons with lower # indices than the cluster indices, and neurons with higher indices. # Only the clusters at the index boundaries project to neurons with only either # lower or higher indices if low_index > 0: rest_low = neurons_e[0:low_index] print('Connecting cluster with other neurons of lower index') low_conn = Synapses(cluster,rest_low, on_pre='y_e += %f' % connections.J_ee) low_conn.connect('i != j', p=p_out) cluster_conns_list.append(low_conn) if high_index < model.N_e: rest_high = neurons_e[high_index:model.N_e] print('Connecting cluster with other neurons of higher index') high_conn = Synapses(cluster,rest_high, on_pre='y_e += %f' % connections.J_ee) high_conn.connect('i != j', p=p_out) cluster_conns_list.append(high_conn) low_index=high_index high_index+=connections.clustersize_e self.cluster_conns=cluster_conns_list conns_list+=cluster_conns_list else: # Here we don't cluster and connection probabilities are homogeneous print('Connectiong ee') self.conn_ee = Synapses(neurons_e,neurons_e, on_pre='y_e += %f' % connections.J_ee) self.conn_ee.connect('i != j', p=connections.p_ee) conns_list.append(self.conn_ee) # Add the connections to the `brian_list` and the network dict brian_list.extend(conns_list) network_dict['connections'] = conns_list
def _build_connections(self, traj, brian_list, network_dict): """Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`. """ connections = traj.connections neurons_i = network_dict['neurons_i'] neurons_e = network_dict['neurons_e'] print('Connecting ii') self.conn_ii = Synapses(neurons_i,neurons_i, on_pre='y_i += %f' % connections.J_ii) self.conn_ii.connect('i != j', p=connections.p_ii) print('Connecting ei') self.conn_ei = Synapses(neurons_i,neurons_e, on_pre='y_i += %f' % connections.J_ei) self.conn_ei.connect('i != j', p=connections.p_ei) print('Connecting ie') self.conn_ie = Synapses(neurons_e,neurons_i, on_pre='y_e += %f' % connections.J_ie) self.conn_ie.connect('i != j', p=connections.p_ie) conns_list = [self.conn_ii, self.conn_ei, self.conn_ie] if connections.R_ee > 1.0: # If we come here we want to create clusters cluster_list=[] cluster_conns_list=[] model=traj.model # Compute the number of clusters clusters = int(model.N_e/connections.clustersize_e) traj.f_add_derived_parameter('connections.clusters', clusters, comment='Number of clusters') # Compute outgoing connection probability p_out = (connections.p_ee*model.N_e) / \ (connections.R_ee*connections.clustersize_e+model.N_e- connections.clustersize_e) # Compute within cluster connection probability p_in = p_out * connections.R_ee # We keep these derived parameters traj.f_add_derived_parameter('connections.p_ee_in', p_in , comment='Connection prob within cluster') traj.f_add_derived_parameter('connections.p_ee_out', p_out , comment='Connection prob to outside of cluster') low_index = 0 high_index = connections.clustersize_e # Iterate through cluster and connect within clusters and to the rest of the neurons for irun in range(clusters): cluster = neurons_e[low_index:high_index] # Connections within cluster print('Connecting ee cluster #%d of %d' % (irun, clusters)) conn = Synapses(cluster,cluster, on_pre='y_e += %f' % (connections.J_ee*connections.strength_factor)) conn.connect('i != j', p=p_in) cluster_conns_list.append(conn) # Connections reaching out from cluster # A cluster consists of `clustersize_e` neurons with consecutive indices. # So usually the outside world consists of two groups, neurons with lower # indices than the cluster indices, and neurons with higher indices. # Only the clusters at the index boundaries project to neurons with only either # lower or higher indices if low_index > 0: rest_low = neurons_e[0:low_index] print('Connecting cluster with other neurons of lower index') low_conn = Synapses(cluster,rest_low, on_pre='y_e += %f' % connections.J_ee) low_conn.connect('i != j', p=p_out) cluster_conns_list.append(low_conn) if high_index < model.N_e: rest_high = neurons_e[high_index:model.N_e] print('Connecting cluster with other neurons of higher index') high_conn = Synapses(cluster,rest_high, on_pre='y_e += %f' % connections.J_ee) high_conn.connect('i != j', p=p_out) cluster_conns_list.append(high_conn) low_index=high_index high_index+=connections.clustersize_e self.cluster_conns=cluster_conns_list conns_list+=cluster_conns_list else: # Here we don't cluster and connection probabilities are homogeneous print('Connectiong ee') self.conn_ee = Synapses(neurons_e,neurons_e, on_pre='y_e += %f' % connections.J_ee) self.conn_ee.connect('i != j', p=connections.p_ee) conns_list.append(self.conn_ee) # Add the connections to the `brian_list` and the network dict brian_list.extend(conns_list) network_dict['connections'] = conns_list
[ "Connects", "neuron", "groups", "neurons_i", "and", "neurons_e", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L363-L473
[ "def", "_build_connections", "(", "self", ",", "traj", ",", "brian_list", ",", "network_dict", ")", ":", "connections", "=", "traj", ".", "connections", "neurons_i", "=", "network_dict", "[", "'neurons_i'", "]", "neurons_e", "=", "network_dict", "[", "'neurons_e'", "]", "print", "(", "'Connecting ii'", ")", "self", ".", "conn_ii", "=", "Synapses", "(", "neurons_i", ",", "neurons_i", ",", "on_pre", "=", "'y_i += %f'", "%", "connections", ".", "J_ii", ")", "self", ".", "conn_ii", ".", "connect", "(", "'i != j'", ",", "p", "=", "connections", ".", "p_ii", ")", "print", "(", "'Connecting ei'", ")", "self", ".", "conn_ei", "=", "Synapses", "(", "neurons_i", ",", "neurons_e", ",", "on_pre", "=", "'y_i += %f'", "%", "connections", ".", "J_ei", ")", "self", ".", "conn_ei", ".", "connect", "(", "'i != j'", ",", "p", "=", "connections", ".", "p_ei", ")", "print", "(", "'Connecting ie'", ")", "self", ".", "conn_ie", "=", "Synapses", "(", "neurons_e", ",", "neurons_i", ",", "on_pre", "=", "'y_e += %f'", "%", "connections", ".", "J_ie", ")", "self", ".", "conn_ie", ".", "connect", "(", "'i != j'", ",", "p", "=", "connections", ".", "p_ie", ")", "conns_list", "=", "[", "self", ".", "conn_ii", ",", "self", ".", "conn_ei", ",", "self", ".", "conn_ie", "]", "if", "connections", ".", "R_ee", ">", "1.0", ":", "# If we come here we want to create clusters", "cluster_list", "=", "[", "]", "cluster_conns_list", "=", "[", "]", "model", "=", "traj", ".", "model", "# Compute the number of clusters", "clusters", "=", "int", "(", "model", ".", "N_e", "/", "connections", ".", "clustersize_e", ")", "traj", ".", "f_add_derived_parameter", "(", "'connections.clusters'", ",", "clusters", ",", "comment", "=", "'Number of clusters'", ")", "# Compute outgoing connection probability", "p_out", "=", "(", "connections", ".", "p_ee", "*", "model", ".", "N_e", ")", "/", "(", "connections", ".", "R_ee", "*", "connections", ".", "clustersize_e", "+", "model", ".", "N_e", "-", "connections", ".", "clustersize_e", ")", "# Compute within cluster connection probability", "p_in", "=", "p_out", "*", "connections", ".", "R_ee", "# We keep these derived parameters", "traj", ".", "f_add_derived_parameter", "(", "'connections.p_ee_in'", ",", "p_in", ",", "comment", "=", "'Connection prob within cluster'", ")", "traj", ".", "f_add_derived_parameter", "(", "'connections.p_ee_out'", ",", "p_out", ",", "comment", "=", "'Connection prob to outside of cluster'", ")", "low_index", "=", "0", "high_index", "=", "connections", ".", "clustersize_e", "# Iterate through cluster and connect within clusters and to the rest of the neurons", "for", "irun", "in", "range", "(", "clusters", ")", ":", "cluster", "=", "neurons_e", "[", "low_index", ":", "high_index", "]", "# Connections within cluster", "print", "(", "'Connecting ee cluster #%d of %d'", "%", "(", "irun", ",", "clusters", ")", ")", "conn", "=", "Synapses", "(", "cluster", ",", "cluster", ",", "on_pre", "=", "'y_e += %f'", "%", "(", "connections", ".", "J_ee", "*", "connections", ".", "strength_factor", ")", ")", "conn", ".", "connect", "(", "'i != j'", ",", "p", "=", "p_in", ")", "cluster_conns_list", ".", "append", "(", "conn", ")", "# Connections reaching out from cluster", "# A cluster consists of `clustersize_e` neurons with consecutive indices.", "# So usually the outside world consists of two groups, neurons with lower", "# indices than the cluster indices, and neurons with higher indices.", "# Only the clusters at the index boundaries project to neurons with only either", "# lower or higher indices", "if", "low_index", ">", "0", ":", "rest_low", "=", "neurons_e", "[", "0", ":", "low_index", "]", "print", "(", "'Connecting cluster with other neurons of lower index'", ")", "low_conn", "=", "Synapses", "(", "cluster", ",", "rest_low", ",", "on_pre", "=", "'y_e += %f'", "%", "connections", ".", "J_ee", ")", "low_conn", ".", "connect", "(", "'i != j'", ",", "p", "=", "p_out", ")", "cluster_conns_list", ".", "append", "(", "low_conn", ")", "if", "high_index", "<", "model", ".", "N_e", ":", "rest_high", "=", "neurons_e", "[", "high_index", ":", "model", ".", "N_e", "]", "print", "(", "'Connecting cluster with other neurons of higher index'", ")", "high_conn", "=", "Synapses", "(", "cluster", ",", "rest_high", ",", "on_pre", "=", "'y_e += %f'", "%", "connections", ".", "J_ee", ")", "high_conn", ".", "connect", "(", "'i != j'", ",", "p", "=", "p_out", ")", "cluster_conns_list", ".", "append", "(", "high_conn", ")", "low_index", "=", "high_index", "high_index", "+=", "connections", ".", "clustersize_e", "self", ".", "cluster_conns", "=", "cluster_conns_list", "conns_list", "+=", "cluster_conns_list", "else", ":", "# Here we don't cluster and connection probabilities are homogeneous", "print", "(", "'Connectiong ee'", ")", "self", ".", "conn_ee", "=", "Synapses", "(", "neurons_e", ",", "neurons_e", ",", "on_pre", "=", "'y_e += %f'", "%", "connections", ".", "J_ee", ")", "self", ".", "conn_ee", ".", "connect", "(", "'i != j'", ",", "p", "=", "connections", ".", "p_ee", ")", "conns_list", ".", "append", "(", "self", ".", "conn_ee", ")", "# Add the connections to the `brian_list` and the network dict", "brian_list", ".", "extend", "(", "conns_list", ")", "network_dict", "[", "'connections'", "]", "=", "conns_list" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNNetworkRunner.add_parameters
Adds all necessary parameters to `traj` container.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def add_parameters(self, traj): """Adds all necessary parameters to `traj` container.""" par= traj.f_add_parameter(Brian2Parameter,'simulation.durations.initial_run', 500*ms, comment='Initialisation run for more realistic ' 'measurement conditions.') par.v_annotations.order=0 par=traj.f_add_parameter(Brian2Parameter,'simulation.durations.measurement_run', 1500*ms, comment='Measurement run that is considered for ' 'statistical evaluation') par.v_annotations.order=1
def add_parameters(self, traj): """Adds all necessary parameters to `traj` container.""" par= traj.f_add_parameter(Brian2Parameter,'simulation.durations.initial_run', 500*ms, comment='Initialisation run for more realistic ' 'measurement conditions.') par.v_annotations.order=0 par=traj.f_add_parameter(Brian2Parameter,'simulation.durations.measurement_run', 1500*ms, comment='Measurement run that is considered for ' 'statistical evaluation') par.v_annotations.order=1
[ "Adds", "all", "necessary", "parameters", "to", "traj", "container", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L485-L495
[ "def", "add_parameters", "(", "self", ",", "traj", ")", ":", "par", "=", "traj", ".", "f_add_parameter", "(", "Brian2Parameter", ",", "'simulation.durations.initial_run'", ",", "500", "*", "ms", ",", "comment", "=", "'Initialisation run for more realistic '", "'measurement conditions.'", ")", "par", ".", "v_annotations", ".", "order", "=", "0", "par", "=", "traj", ".", "f_add_parameter", "(", "Brian2Parameter", ",", "'simulation.durations.measurement_run'", ",", "1500", "*", "ms", ",", "comment", "=", "'Measurement run that is considered for '", "'statistical evaluation'", ")", "par", ".", "v_annotations", ".", "order", "=", "1" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNFanoFactorComputer._compute_fano_factor
Computes Fano Factor for one neuron. :param spike_res: Result containing the spiketimes of all neurons :param neuron_id: Index of neuron for which FF is computed :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Fano Factor (float) or returns 0 if mean firing activity is 0.
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _compute_fano_factor(spike_res, neuron_id, time_window, start_time, end_time): """Computes Fano Factor for one neuron. :param spike_res: Result containing the spiketimes of all neurons :param neuron_id: Index of neuron for which FF is computed :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Fano Factor (float) or returns 0 if mean firing activity is 0. """ assert(end_time >= start_time+time_window) # Number of time bins bins = (end_time-start_time)/time_window bins = int(np.floor(bins)) # Arrays for binning of spike counts binned_spikes = np.zeros(bins) # DataFrame only containing spikes of the particular neuron spike_array_neuron = spike_res.t[spike_res.i==neuron_id] for bin in range(bins): # We iterate over the bins to calculate the spike counts lower_time = start_time+time_window*bin upper_time = start_time+time_window*(bin+1) # Filter the spikes spike_array_interval = spike_array_neuron[spike_array_neuron >= lower_time] spike_array_interval = spike_array_interval[spike_array_interval < upper_time] # Add count to bins spikes = len(spike_array_interval) binned_spikes[bin]=spikes var = np.var(binned_spikes) avg = np.mean(binned_spikes) if avg > 0: return var/float(avg) else: return 0
def _compute_fano_factor(spike_res, neuron_id, time_window, start_time, end_time): """Computes Fano Factor for one neuron. :param spike_res: Result containing the spiketimes of all neurons :param neuron_id: Index of neuron for which FF is computed :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Fano Factor (float) or returns 0 if mean firing activity is 0. """ assert(end_time >= start_time+time_window) # Number of time bins bins = (end_time-start_time)/time_window bins = int(np.floor(bins)) # Arrays for binning of spike counts binned_spikes = np.zeros(bins) # DataFrame only containing spikes of the particular neuron spike_array_neuron = spike_res.t[spike_res.i==neuron_id] for bin in range(bins): # We iterate over the bins to calculate the spike counts lower_time = start_time+time_window*bin upper_time = start_time+time_window*(bin+1) # Filter the spikes spike_array_interval = spike_array_neuron[spike_array_neuron >= lower_time] spike_array_interval = spike_array_interval[spike_array_interval < upper_time] # Add count to bins spikes = len(spike_array_interval) binned_spikes[bin]=spikes var = np.var(binned_spikes) avg = np.mean(binned_spikes) if avg > 0: return var/float(avg) else: return 0
[ "Computes", "Fano", "Factor", "for", "one", "neuron", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L508-L569
[ "def", "_compute_fano_factor", "(", "spike_res", ",", "neuron_id", ",", "time_window", ",", "start_time", ",", "end_time", ")", ":", "assert", "(", "end_time", ">=", "start_time", "+", "time_window", ")", "# Number of time bins", "bins", "=", "(", "end_time", "-", "start_time", ")", "/", "time_window", "bins", "=", "int", "(", "np", ".", "floor", "(", "bins", ")", ")", "# Arrays for binning of spike counts", "binned_spikes", "=", "np", ".", "zeros", "(", "bins", ")", "# DataFrame only containing spikes of the particular neuron", "spike_array_neuron", "=", "spike_res", ".", "t", "[", "spike_res", ".", "i", "==", "neuron_id", "]", "for", "bin", "in", "range", "(", "bins", ")", ":", "# We iterate over the bins to calculate the spike counts", "lower_time", "=", "start_time", "+", "time_window", "*", "bin", "upper_time", "=", "start_time", "+", "time_window", "*", "(", "bin", "+", "1", ")", "# Filter the spikes", "spike_array_interval", "=", "spike_array_neuron", "[", "spike_array_neuron", ">=", "lower_time", "]", "spike_array_interval", "=", "spike_array_interval", "[", "spike_array_interval", "<", "upper_time", "]", "# Add count to bins", "spikes", "=", "len", "(", "spike_array_interval", ")", "binned_spikes", "[", "bin", "]", "=", "spikes", "var", "=", "np", ".", "var", "(", "binned_spikes", ")", "avg", "=", "np", ".", "mean", "(", "binned_spikes", ")", "if", "avg", ">", "0", ":", "return", "var", "/", "float", "(", "avg", ")", "else", ":", "return", "0" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNFanoFactorComputer._compute_mean_fano_factor
Computes average Fano Factor over many neurons. :param neuron_ids: List of neuron indices to average over :param spike_res: Result containing all the spikes :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Average fano factor
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _compute_mean_fano_factor( neuron_ids, spike_res, time_window, start_time, end_time): """Computes average Fano Factor over many neurons. :param neuron_ids: List of neuron indices to average over :param spike_res: Result containing all the spikes :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Average fano factor """ ffs = np.zeros(len(neuron_ids)) for idx, neuron_id in enumerate(neuron_ids): ff=CNFanoFactorComputer._compute_fano_factor( spike_res, neuron_id, time_window, start_time, end_time) ffs[idx]=ff mean_ff = np.mean(ffs) return mean_ff
def _compute_mean_fano_factor( neuron_ids, spike_res, time_window, start_time, end_time): """Computes average Fano Factor over many neurons. :param neuron_ids: List of neuron indices to average over :param spike_res: Result containing all the spikes :param time_window: Length of the consecutive time windows to compute the FF :param start_time: Start time of measurement to consider :param end_time: End time of measurement to consider :return: Average fano factor """ ffs = np.zeros(len(neuron_ids)) for idx, neuron_id in enumerate(neuron_ids): ff=CNFanoFactorComputer._compute_fano_factor( spike_res, neuron_id, time_window, start_time, end_time) ffs[idx]=ff mean_ff = np.mean(ffs) return mean_ff
[ "Computes", "average", "Fano", "Factor", "over", "many", "neurons", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L572-L608
[ "def", "_compute_mean_fano_factor", "(", "neuron_ids", ",", "spike_res", ",", "time_window", ",", "start_time", ",", "end_time", ")", ":", "ffs", "=", "np", ".", "zeros", "(", "len", "(", "neuron_ids", ")", ")", "for", "idx", ",", "neuron_id", "in", "enumerate", "(", "neuron_ids", ")", ":", "ff", "=", "CNFanoFactorComputer", ".", "_compute_fano_factor", "(", "spike_res", ",", "neuron_id", ",", "time_window", ",", "start_time", ",", "end_time", ")", "ffs", "[", "idx", "]", "=", "ff", "mean_ff", "=", "np", ".", "mean", "(", "ffs", ")", "return", "mean_ff" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNFanoFactorComputer.analyse
Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: `results.statistics.mean_fano_factor`: Average Fano Factor :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: Upcoming subruns, analysis is only performed if subruns is empty, aka the final subrun has finished. :param network_dict: Dictionary of items shared among componetns
examples/example_24_large_scale_brian2_simulation/clusternet.py
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: `results.statistics.mean_fano_factor`: Average Fano Factor :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: Upcoming subruns, analysis is only performed if subruns is empty, aka the final subrun has finished. :param network_dict: Dictionary of items shared among componetns """ #Check if we finished all subruns if len(subrun_list)==0: spikes_e = traj.results.monitors.spikes_e time_window = traj.parameters.analysis.statistics.time_window start_time = traj.parameters.simulation.durations.initial_run end_time = start_time+traj.parameters.simulation.durations.measurement_run neuron_ids = traj.parameters.analysis.statistics.neuron_ids mean_ff = self._compute_mean_fano_factor( neuron_ids, spikes_e, time_window, start_time, end_time) traj.f_add_result('statistics.mean_fano_factor', mean_ff, comment='Average Fano ' 'Factor over all ' 'exc neurons') print('R_ee: %f, Mean FF: %f' % (traj.R_ee, mean_ff))
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: `results.statistics.mean_fano_factor`: Average Fano Factor :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: Upcoming subruns, analysis is only performed if subruns is empty, aka the final subrun has finished. :param network_dict: Dictionary of items shared among componetns """ #Check if we finished all subruns if len(subrun_list)==0: spikes_e = traj.results.monitors.spikes_e time_window = traj.parameters.analysis.statistics.time_window start_time = traj.parameters.simulation.durations.initial_run end_time = start_time+traj.parameters.simulation.durations.measurement_run neuron_ids = traj.parameters.analysis.statistics.neuron_ids mean_ff = self._compute_mean_fano_factor( neuron_ids, spikes_e, time_window, start_time, end_time) traj.f_add_result('statistics.mean_fano_factor', mean_ff, comment='Average Fano ' 'Factor over all ' 'exc neurons') print('R_ee: %f, Mean FF: %f' % (traj.R_ee, mean_ff))
[ "Calculates", "average", "Fano", "Factor", "of", "a", "network", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L610-L659
[ "def", "analyse", "(", "self", ",", "traj", ",", "network", ",", "current_subrun", ",", "subrun_list", ",", "network_dict", ")", ":", "#Check if we finished all subruns", "if", "len", "(", "subrun_list", ")", "==", "0", ":", "spikes_e", "=", "traj", ".", "results", ".", "monitors", ".", "spikes_e", "time_window", "=", "traj", ".", "parameters", ".", "analysis", ".", "statistics", ".", "time_window", "start_time", "=", "traj", ".", "parameters", ".", "simulation", ".", "durations", ".", "initial_run", "end_time", "=", "start_time", "+", "traj", ".", "parameters", ".", "simulation", ".", "durations", ".", "measurement_run", "neuron_ids", "=", "traj", ".", "parameters", ".", "analysis", ".", "statistics", ".", "neuron_ids", "mean_ff", "=", "self", ".", "_compute_mean_fano_factor", "(", "neuron_ids", ",", "spikes_e", ",", "time_window", ",", "start_time", ",", "end_time", ")", "traj", ".", "f_add_result", "(", "'statistics.mean_fano_factor'", ",", "mean_ff", ",", "comment", "=", "'Average Fano '", "'Factor over all '", "'exc neurons'", ")", "print", "(", "'R_ee: %f, Mean FF: %f'", "%", "(", "traj", ".", "R_ee", ",", "mean_ff", ")", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis.add_to_network
Adds monitors to the network if the measurement run is carried out. :param traj: Trajectory container :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subrun_list :param network_dict: Dictionary of items shared among the components Expects: 'neurons_e': Excitatory neuron group Adds: 'monitors': List of monitors 0. SpikeMonitor of excitatory neurons 1. StateMonitor of membrane potential of some excitatory neurons (specified in `neuron_records`) 2. StateMonitor of excitatory synaptic currents of some excitatory neurons 3. State monitor of inhibitory currents of some excitatory neurons
examples/example_24_large_scale_brian2_simulation/clusternet.py
def add_to_network(self, traj, network, current_subrun, subrun_list, network_dict): """Adds monitors to the network if the measurement run is carried out. :param traj: Trajectory container :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subrun_list :param network_dict: Dictionary of items shared among the components Expects: 'neurons_e': Excitatory neuron group Adds: 'monitors': List of monitors 0. SpikeMonitor of excitatory neurons 1. StateMonitor of membrane potential of some excitatory neurons (specified in `neuron_records`) 2. StateMonitor of excitatory synaptic currents of some excitatory neurons 3. State monitor of inhibitory currents of some excitatory neurons """ if current_subrun.v_annotations.order == 1: self._add_monitors(traj, network, network_dict)
def add_to_network(self, traj, network, current_subrun, subrun_list, network_dict): """Adds monitors to the network if the measurement run is carried out. :param traj: Trajectory container :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subrun_list :param network_dict: Dictionary of items shared among the components Expects: 'neurons_e': Excitatory neuron group Adds: 'monitors': List of monitors 0. SpikeMonitor of excitatory neurons 1. StateMonitor of membrane potential of some excitatory neurons (specified in `neuron_records`) 2. StateMonitor of excitatory synaptic currents of some excitatory neurons 3. State monitor of inhibitory currents of some excitatory neurons """ if current_subrun.v_annotations.order == 1: self._add_monitors(traj, network, network_dict)
[ "Adds", "monitors", "to", "the", "network", "if", "the", "measurement", "run", "is", "carried", "out", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L675-L709
[ "def", "add_to_network", "(", "self", ",", "traj", ",", "network", ",", "current_subrun", ",", "subrun_list", ",", "network_dict", ")", ":", "if", "current_subrun", ".", "v_annotations", ".", "order", "==", "1", ":", "self", ".", "_add_monitors", "(", "traj", ",", "network", ",", "network_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis._add_monitors
Adds monitors to the network
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _add_monitors(self, traj, network, network_dict): """Adds monitors to the network""" neurons_e = network_dict['neurons_e'] monitor_list = [] # Spiketimes self.spike_monitor = SpikeMonitor(neurons_e) monitor_list.append(self.spike_monitor) # Membrane Potential self.V_monitor = StateMonitor(neurons_e,'V', record=list(traj.neuron_records)) monitor_list.append(self.V_monitor) # Exc. syn .Current self.I_syn_e_monitor = StateMonitor(neurons_e, 'I_syn_e', record=list(traj.neuron_records)) monitor_list.append(self.I_syn_e_monitor) # Inh. syn. Current self.I_syn_i_monitor = StateMonitor(neurons_e, 'I_syn_i', record=list(traj.neuron_records)) monitor_list.append(self.I_syn_i_monitor) # Add monitors to network and dictionary network.add(*monitor_list) network_dict['monitors'] = monitor_list
def _add_monitors(self, traj, network, network_dict): """Adds monitors to the network""" neurons_e = network_dict['neurons_e'] monitor_list = [] # Spiketimes self.spike_monitor = SpikeMonitor(neurons_e) monitor_list.append(self.spike_monitor) # Membrane Potential self.V_monitor = StateMonitor(neurons_e,'V', record=list(traj.neuron_records)) monitor_list.append(self.V_monitor) # Exc. syn .Current self.I_syn_e_monitor = StateMonitor(neurons_e, 'I_syn_e', record=list(traj.neuron_records)) monitor_list.append(self.I_syn_e_monitor) # Inh. syn. Current self.I_syn_i_monitor = StateMonitor(neurons_e, 'I_syn_i', record=list(traj.neuron_records)) monitor_list.append(self.I_syn_i_monitor) # Add monitors to network and dictionary network.add(*monitor_list) network_dict['monitors'] = monitor_list
[ "Adds", "monitors", "to", "the", "network" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L711-L740
[ "def", "_add_monitors", "(", "self", ",", "traj", ",", "network", ",", "network_dict", ")", ":", "neurons_e", "=", "network_dict", "[", "'neurons_e'", "]", "monitor_list", "=", "[", "]", "# Spiketimes", "self", ".", "spike_monitor", "=", "SpikeMonitor", "(", "neurons_e", ")", "monitor_list", ".", "append", "(", "self", ".", "spike_monitor", ")", "# Membrane Potential", "self", ".", "V_monitor", "=", "StateMonitor", "(", "neurons_e", ",", "'V'", ",", "record", "=", "list", "(", "traj", ".", "neuron_records", ")", ")", "monitor_list", ".", "append", "(", "self", ".", "V_monitor", ")", "# Exc. syn .Current", "self", ".", "I_syn_e_monitor", "=", "StateMonitor", "(", "neurons_e", ",", "'I_syn_e'", ",", "record", "=", "list", "(", "traj", ".", "neuron_records", ")", ")", "monitor_list", ".", "append", "(", "self", ".", "I_syn_e_monitor", ")", "# Inh. syn. Current", "self", ".", "I_syn_i_monitor", "=", "StateMonitor", "(", "neurons_e", ",", "'I_syn_i'", ",", "record", "=", "list", "(", "traj", ".", "neuron_records", ")", ")", "monitor_list", ".", "append", "(", "self", ".", "I_syn_i_monitor", ")", "# Add monitors to network and dictionary", "network", ".", "add", "(", "*", "monitor_list", ")", "network_dict", "[", "'monitors'", "]", "=", "monitor_list" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis._make_folder
Makes a subfolder for plots. :return: Path name to print folder
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _make_folder(self, traj): """Makes a subfolder for plots. :return: Path name to print folder """ print_folder = os.path.join(traj.analysis.plot_folder, traj.v_name, traj.v_crun) print_folder = os.path.abspath(print_folder) if not os.path.isdir(print_folder): os.makedirs(print_folder) return print_folder
def _make_folder(self, traj): """Makes a subfolder for plots. :return: Path name to print folder """ print_folder = os.path.join(traj.analysis.plot_folder, traj.v_name, traj.v_crun) print_folder = os.path.abspath(print_folder) if not os.path.isdir(print_folder): os.makedirs(print_folder) return print_folder
[ "Makes", "a", "subfolder", "for", "plots", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L742-L754
[ "def", "_make_folder", "(", "self", ",", "traj", ")", ":", "print_folder", "=", "os", ".", "path", ".", "join", "(", "traj", ".", "analysis", ".", "plot_folder", ",", "traj", ".", "v_name", ",", "traj", ".", "v_crun", ")", "print_folder", "=", "os", ".", "path", ".", "abspath", "(", "print_folder", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "print_folder", ")", ":", "os", ".", "makedirs", "(", "print_folder", ")", "return", "print_folder" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis._plot_result
Plots a state variable graph for several neurons into one figure
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _plot_result(self, traj, result_name): """Plots a state variable graph for several neurons into one figure""" result = traj.f_get(result_name) varname = result.record_variables[0] values = result[varname] times = result.t record = result.record for idx, celia_neuron in enumerate(record): plt.subplot(len(record), 1, idx+1) plt.plot(times, values[idx,:]) if idx==0: plt.title('%s' % varname) if idx==1: plt.ylabel('%s' % ( varname)) if idx == len(record)-1: plt.xlabel('t')
def _plot_result(self, traj, result_name): """Plots a state variable graph for several neurons into one figure""" result = traj.f_get(result_name) varname = result.record_variables[0] values = result[varname] times = result.t record = result.record for idx, celia_neuron in enumerate(record): plt.subplot(len(record), 1, idx+1) plt.plot(times, values[idx,:]) if idx==0: plt.title('%s' % varname) if idx==1: plt.ylabel('%s' % ( varname)) if idx == len(record)-1: plt.xlabel('t')
[ "Plots", "a", "state", "variable", "graph", "for", "several", "neurons", "into", "one", "figure" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L756-L773
[ "def", "_plot_result", "(", "self", ",", "traj", ",", "result_name", ")", ":", "result", "=", "traj", ".", "f_get", "(", "result_name", ")", "varname", "=", "result", ".", "record_variables", "[", "0", "]", "values", "=", "result", "[", "varname", "]", "times", "=", "result", ".", "t", "record", "=", "result", ".", "record", "for", "idx", ",", "celia_neuron", "in", "enumerate", "(", "record", ")", ":", "plt", ".", "subplot", "(", "len", "(", "record", ")", ",", "1", ",", "idx", "+", "1", ")", "plt", ".", "plot", "(", "times", ",", "values", "[", "idx", ",", ":", "]", ")", "if", "idx", "==", "0", ":", "plt", ".", "title", "(", "'%s'", "%", "varname", ")", "if", "idx", "==", "1", ":", "plt", ".", "ylabel", "(", "'%s'", "%", "(", "varname", ")", ")", "if", "idx", "==", "len", "(", "record", ")", "-", "1", ":", "plt", ".", "xlabel", "(", "'t'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis._print_graphs
Makes some plots and stores them into subfolders
examples/example_24_large_scale_brian2_simulation/clusternet.py
def _print_graphs(self, traj): """Makes some plots and stores them into subfolders""" print_folder = self._make_folder(traj) # If we use BRIAN's own raster_plot functionality we # need to sue the SpikeMonitor directly plt.figure() plt.scatter(self.spike_monitor.t, self.spike_monitor.i, s=1) plt.xlabel('t') plt.ylabel('Exc. Neurons') plt.title('Spike Raster Plot') filename=os.path.join(print_folder,'spike.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() fig=plt.figure() self._plot_result(traj, 'monitors.V') filename=os.path.join(print_folder,'V.png') print('Current plot: %s ' % filename) fig.savefig(filename) plt.close() plt.figure() self._plot_result(traj, 'monitors.I_syn_e') filename=os.path.join(print_folder,'I_syn_e.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() plt.figure() self._plot_result(traj, 'monitors.I_syn_i') filename=os.path.join(print_folder,'I_syn_i.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() if not traj.analysis.show_plots: plt.close('all') else: plt.show()
def _print_graphs(self, traj): """Makes some plots and stores them into subfolders""" print_folder = self._make_folder(traj) # If we use BRIAN's own raster_plot functionality we # need to sue the SpikeMonitor directly plt.figure() plt.scatter(self.spike_monitor.t, self.spike_monitor.i, s=1) plt.xlabel('t') plt.ylabel('Exc. Neurons') plt.title('Spike Raster Plot') filename=os.path.join(print_folder,'spike.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() fig=plt.figure() self._plot_result(traj, 'monitors.V') filename=os.path.join(print_folder,'V.png') print('Current plot: %s ' % filename) fig.savefig(filename) plt.close() plt.figure() self._plot_result(traj, 'monitors.I_syn_e') filename=os.path.join(print_folder,'I_syn_e.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() plt.figure() self._plot_result(traj, 'monitors.I_syn_i') filename=os.path.join(print_folder,'I_syn_i.png') print('Current plot: %s ' % filename) plt.savefig(filename) plt.close() if not traj.analysis.show_plots: plt.close('all') else: plt.show()
[ "Makes", "some", "plots", "and", "stores", "them", "into", "subfolders" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L775-L817
[ "def", "_print_graphs", "(", "self", ",", "traj", ")", ":", "print_folder", "=", "self", ".", "_make_folder", "(", "traj", ")", "# If we use BRIAN's own raster_plot functionality we", "# need to sue the SpikeMonitor directly", "plt", ".", "figure", "(", ")", "plt", ".", "scatter", "(", "self", ".", "spike_monitor", ".", "t", ",", "self", ".", "spike_monitor", ".", "i", ",", "s", "=", "1", ")", "plt", ".", "xlabel", "(", "'t'", ")", "plt", ".", "ylabel", "(", "'Exc. Neurons'", ")", "plt", ".", "title", "(", "'Spike Raster Plot'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "print_folder", ",", "'spike.png'", ")", "print", "(", "'Current plot: %s '", "%", "filename", ")", "plt", ".", "savefig", "(", "filename", ")", "plt", ".", "close", "(", ")", "fig", "=", "plt", ".", "figure", "(", ")", "self", ".", "_plot_result", "(", "traj", ",", "'monitors.V'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "print_folder", ",", "'V.png'", ")", "print", "(", "'Current plot: %s '", "%", "filename", ")", "fig", ".", "savefig", "(", "filename", ")", "plt", ".", "close", "(", ")", "plt", ".", "figure", "(", ")", "self", ".", "_plot_result", "(", "traj", ",", "'monitors.I_syn_e'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "print_folder", ",", "'I_syn_e.png'", ")", "print", "(", "'Current plot: %s '", "%", "filename", ")", "plt", ".", "savefig", "(", "filename", ")", "plt", ".", "close", "(", ")", "plt", ".", "figure", "(", ")", "self", ".", "_plot_result", "(", "traj", ",", "'monitors.I_syn_i'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "print_folder", ",", "'I_syn_i.png'", ")", "print", "(", "'Current plot: %s '", "%", "filename", ")", "plt", ".", "savefig", "(", "filename", ")", "plt", ".", "close", "(", ")", "if", "not", "traj", ".", "analysis", ".", "show_plots", ":", "plt", ".", "close", "(", "'all'", ")", "else", ":", "plt", ".", "show", "(", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
CNMonitorAnalysis.analyse
Extracts monitor data and plots. Data extraction is done if all subruns have been completed, i.e. `len(subrun_list)==0` First, extracts results from the monitors and stores them into `traj`. Next, uses the extracted data for plots. :param traj: Trajectory container Adds: Data from monitors :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subruns :param network_dict: Dictionary of items shared among all components
examples/example_24_large_scale_brian2_simulation/clusternet.py
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Extracts monitor data and plots. Data extraction is done if all subruns have been completed, i.e. `len(subrun_list)==0` First, extracts results from the monitors and stores them into `traj`. Next, uses the extracted data for plots. :param traj: Trajectory container Adds: Data from monitors :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subruns :param network_dict: Dictionary of items shared among all components """ if len(subrun_list)==0: traj.f_add_result(Brian2MonitorResult, 'monitors.spikes_e', self.spike_monitor, comment = 'The spiketimes of the excitatory population') traj.f_add_result(Brian2MonitorResult, 'monitors.V', self.V_monitor, comment = 'Membrane voltage of four neurons from 2 clusters') traj.f_add_result(Brian2MonitorResult, 'monitors.I_syn_e', self.I_syn_e_monitor, comment = 'I_syn_e of four neurons from 2 clusters') traj.f_add_result(Brian2MonitorResult, 'monitors.I_syn_i', self.I_syn_i_monitor, comment = 'I_syn_i of four neurons from 2 clusters') print('Plotting') if traj.parameters.analysis.make_plots: self._print_graphs(traj)
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Extracts monitor data and plots. Data extraction is done if all subruns have been completed, i.e. `len(subrun_list)==0` First, extracts results from the monitors and stores them into `traj`. Next, uses the extracted data for plots. :param traj: Trajectory container Adds: Data from monitors :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_list: List of coming subruns :param network_dict: Dictionary of items shared among all components """ if len(subrun_list)==0: traj.f_add_result(Brian2MonitorResult, 'monitors.spikes_e', self.spike_monitor, comment = 'The spiketimes of the excitatory population') traj.f_add_result(Brian2MonitorResult, 'monitors.V', self.V_monitor, comment = 'Membrane voltage of four neurons from 2 clusters') traj.f_add_result(Brian2MonitorResult, 'monitors.I_syn_e', self.I_syn_e_monitor, comment = 'I_syn_e of four neurons from 2 clusters') traj.f_add_result(Brian2MonitorResult, 'monitors.I_syn_i', self.I_syn_i_monitor, comment = 'I_syn_i of four neurons from 2 clusters') print('Plotting') if traj.parameters.analysis.make_plots: self._print_graphs(traj)
[ "Extracts", "monitor", "data", "and", "plots", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L820-L864
[ "def", "analyse", "(", "self", ",", "traj", ",", "network", ",", "current_subrun", ",", "subrun_list", ",", "network_dict", ")", ":", "if", "len", "(", "subrun_list", ")", "==", "0", ":", "traj", ".", "f_add_result", "(", "Brian2MonitorResult", ",", "'monitors.spikes_e'", ",", "self", ".", "spike_monitor", ",", "comment", "=", "'The spiketimes of the excitatory population'", ")", "traj", ".", "f_add_result", "(", "Brian2MonitorResult", ",", "'monitors.V'", ",", "self", ".", "V_monitor", ",", "comment", "=", "'Membrane voltage of four neurons from 2 clusters'", ")", "traj", ".", "f_add_result", "(", "Brian2MonitorResult", ",", "'monitors.I_syn_e'", ",", "self", ".", "I_syn_e_monitor", ",", "comment", "=", "'I_syn_e of four neurons from 2 clusters'", ")", "traj", ".", "f_add_result", "(", "Brian2MonitorResult", ",", "'monitors.I_syn_i'", ",", "self", ".", "I_syn_i_monitor", ",", "comment", "=", "'I_syn_i of four neurons from 2 clusters'", ")", "print", "(", "'Plotting'", ")", "if", "traj", ".", "parameters", ".", "analysis", ".", "make_plots", ":", "self", ".", "_print_graphs", "(", "traj", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
get_batch
Function that parses the batch id from the command line arguments
examples/example_22_saga_python/the_task.py
def get_batch(): """Function that parses the batch id from the command line arguments""" optlist, args = getopt.getopt(sys.argv[1:], '', longopts='batch=') batch = 0 for o, a in optlist: if o == '--batch': batch = int(a) print('Found batch %d' % batch) return batch
def get_batch(): """Function that parses the batch id from the command line arguments""" optlist, args = getopt.getopt(sys.argv[1:], '', longopts='batch=') batch = 0 for o, a in optlist: if o == '--batch': batch = int(a) print('Found batch %d' % batch) return batch
[ "Function", "that", "parses", "the", "batch", "id", "from", "the", "command", "line", "arguments" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_22_saga_python/the_task.py#L98-L107
[ "def", "get_batch", "(", ")", ":", "optlist", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "''", ",", "longopts", "=", "'batch='", ")", "batch", "=", "0", "for", "o", ",", "a", "in", "optlist", ":", "if", "o", "==", "'--batch'", ":", "batch", "=", "int", "(", "a", ")", "print", "(", "'Found batch %d'", "%", "batch", ")", "return", "batch" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
explore_batch
Chooses exploration according to `batch`
examples/example_22_saga_python/the_task.py
def explore_batch(traj, batch): """Chooses exploration according to `batch`""" explore_dict = {} explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist() # for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0], # for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0] # and so on traj.f_explore(explore_dict)
def explore_batch(traj, batch): """Chooses exploration according to `batch`""" explore_dict = {} explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist() # for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0], # for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0] # and so on traj.f_explore(explore_dict)
[ "Chooses", "exploration", "according", "to", "batch" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_22_saga_python/the_task.py#L110-L117
[ "def", "explore_batch", "(", "traj", ",", "batch", ")", ":", "explore_dict", "=", "{", "}", "explore_dict", "[", "'sigma'", "]", "=", "np", ".", "arange", "(", "10.0", "*", "batch", ",", "10.0", "*", "(", "batch", "+", "1", ")", ",", "1.0", ")", ".", "tolist", "(", ")", "# for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0],", "# for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0]", "# and so on", "traj", ".", "f_explore", "(", "explore_dict", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NNTreeNode.vars
Alternative naming, you can use `node.vars.name` instead of `node.v_name`
pypet/naturalnaming.py
def vars(self): """Alternative naming, you can use `node.vars.name` instead of `node.v_name`""" if self._vars is None: self._vars = NNTreeNodeVars(self) return self._vars
def vars(self): """Alternative naming, you can use `node.vars.name` instead of `node.v_name`""" if self._vars is None: self._vars = NNTreeNodeVars(self) return self._vars
[ "Alternative", "naming", "you", "can", "use", "node", ".", "vars", ".", "name", "instead", "of", "node", ".", "v_name" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L203-L207
[ "def", "vars", "(", "self", ")", ":", "if", "self", ".", "_vars", "is", "None", ":", "self", ".", "_vars", "=", "NNTreeNodeVars", "(", "self", ")", "return", "self", ".", "_vars" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NNTreeNode.func
Alternative naming, you can use `node.func.name` instead of `node.f_func`
pypet/naturalnaming.py
def func(self): """Alternative naming, you can use `node.func.name` instead of `node.f_func`""" if self._func is None: self._func = NNTreeNodeFunc(self) return self._func
def func(self): """Alternative naming, you can use `node.func.name` instead of `node.f_func`""" if self._func is None: self._func = NNTreeNodeFunc(self) return self._func
[ "Alternative", "naming", "you", "can", "use", "node", ".", "func", ".", "name", "instead", "of", "node", ".", "f_func" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L210-L214
[ "def", "func", "(", "self", ")", ":", "if", "self", ".", "_func", "is", "None", ":", "self", ".", "_func", "=", "NNTreeNodeFunc", "(", "self", ")", "return", "self", ".", "_func" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NNTreeNode._rename
Renames the tree node
pypet/naturalnaming.py
def _rename(self, full_name): """Renames the tree node""" self._full_name = full_name if full_name: self._name = full_name.rsplit('.', 1)[-1]
def _rename(self, full_name): """Renames the tree node""" self._full_name = full_name if full_name: self._name = full_name.rsplit('.', 1)[-1]
[ "Renames", "the", "tree", "node" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L294-L298
[ "def", "_rename", "(", "self", ",", "full_name", ")", ":", "self", ".", "_full_name", "=", "full_name", "if", "full_name", ":", "self", ".", "_name", "=", "full_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "-", "1", "]" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NNTreeNode._set_details
Sets some details for internal handling.
pypet/naturalnaming.py
def _set_details(self, depth, branch, run_branch): """Sets some details for internal handling.""" self._depth = depth self._branch = branch self._run_branch = run_branch
def _set_details(self, depth, branch, run_branch): """Sets some details for internal handling.""" self._depth = depth self._branch = branch self._run_branch = run_branch
[ "Sets", "some", "details", "for", "internal", "handling", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L300-L304
[ "def", "_set_details", "(", "self", ",", "depth", ",", "branch", ",", "run_branch", ")", ":", "self", ".", "_depth", "=", "depth", "self", ".", "_branch", "=", "branch", "self", ".", "_run_branch", "=", "run_branch" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._map_type_to_dict
Maps a an instance type representation string (e.g. 'RESULT') to the corresponding dictionary in root.
pypet/naturalnaming.py
def _map_type_to_dict(self, type_name): """ Maps a an instance type representation string (e.g. 'RESULT') to the corresponding dictionary in root. """ root = self._root_instance if type_name == RESULT: return root._results elif type_name == PARAMETER: return root._parameters elif type_name == DERIVED_PARAMETER: return root._derived_parameters elif type_name == CONFIG: return root._config elif type_name == LEAF: return root._other_leaves else: raise RuntimeError('You shall not pass!')
def _map_type_to_dict(self, type_name): """ Maps a an instance type representation string (e.g. 'RESULT') to the corresponding dictionary in root. """ root = self._root_instance if type_name == RESULT: return root._results elif type_name == PARAMETER: return root._parameters elif type_name == DERIVED_PARAMETER: return root._derived_parameters elif type_name == CONFIG: return root._config elif type_name == LEAF: return root._other_leaves else: raise RuntimeError('You shall not pass!')
[ "Maps", "a", "an", "instance", "type", "representation", "string", "(", "e", ".", "g", ".", "RESULT", ")", "to", "the", "corresponding", "dictionary", "in", "root", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L507-L525
[ "def", "_map_type_to_dict", "(", "self", ",", "type_name", ")", ":", "root", "=", "self", ".", "_root_instance", "if", "type_name", "==", "RESULT", ":", "return", "root", ".", "_results", "elif", "type_name", "==", "PARAMETER", ":", "return", "root", ".", "_parameters", "elif", "type_name", "==", "DERIVED_PARAMETER", ":", "return", "root", ".", "_derived_parameters", "elif", "type_name", "==", "CONFIG", ":", "return", "root", ".", "_config", "elif", "type_name", "==", "LEAF", ":", "return", "root", ".", "_other_leaves", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._fetch_from_string
Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param name: String name of item to store, load or remove. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs)
pypet/naturalnaming.py
def _fetch_from_string(self, store_load, name, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param name: String name of item to store, load or remove. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ if not isinstance(name, str): raise TypeError('No string!') node = self._root_instance.f_get(name) return self._fetch_from_node(store_load, node, args, kwargs)
def _fetch_from_string(self, store_load, name, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param name: String name of item to store, load or remove. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ if not isinstance(name, str): raise TypeError('No string!') node = self._root_instance.f_get(name) return self._fetch_from_node(store_load, node, args, kwargs)
[ "Method", "used", "by", "f_store", "/", "load", "/", "remove_items", "to", "find", "a", "corresponding", "item", "in", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L527-L552
[ "def", "_fetch_from_string", "(", "self", ",", "store_load", ",", "name", ",", "args", ",", "kwargs", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "'No string!'", ")", "node", "=", "self", ".", "_root_instance", ".", "f_get", "(", "name", ")", "return", "self", ".", "_fetch_from_node", "(", "store_load", ",", "node", ",", "args", ",", "kwargs", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._fetch_from_node
Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove :param node: A group, parameter or result instance. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs)
pypet/naturalnaming.py
def _fetch_from_node(self, store_load, node, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove :param node: A group, parameter or result instance. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ msg = self._node_to_msg(store_load, node) return msg, node, args, kwargs
def _fetch_from_node(self, store_load, node, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove :param node: A group, parameter or result instance. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ msg = self._node_to_msg(store_load, node) return msg, node, args, kwargs
[ "Method", "used", "by", "f_store", "/", "load", "/", "remove_items", "to", "find", "a", "corresponding", "item", "in", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L554-L570
[ "def", "_fetch_from_node", "(", "self", ",", "store_load", ",", "node", ",", "args", ",", "kwargs", ")", ":", "msg", "=", "self", ".", "_node_to_msg", "(", "store_load", ",", "node", ")", "return", "msg", ",", "node", ",", "args", ",", "kwargs" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._fetch_from_tuple
Method used by f_store/load/remove_items to find a corresponding item in the tree. The input to the method should already be in the correct format, this method only checks for sanity. :param store_load: String constant specifying if we want to store, load or remove :param store_tuple: Tuple already in correct format (msg, item, args, kwargs). If args and kwargs are not given, they are taken from the supplied parameters :param args: Additional arguments passed to the storage service if len(store_tuple)<3 :param kwargs: Additional keyword arguments passed to the storage service if ``len(store_tuple)<4`` :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs)
pypet/naturalnaming.py
def _fetch_from_tuple(self, store_load, store_tuple, args, kwargs): """ Method used by f_store/load/remove_items to find a corresponding item in the tree. The input to the method should already be in the correct format, this method only checks for sanity. :param store_load: String constant specifying if we want to store, load or remove :param store_tuple: Tuple already in correct format (msg, item, args, kwargs). If args and kwargs are not given, they are taken from the supplied parameters :param args: Additional arguments passed to the storage service if len(store_tuple)<3 :param kwargs: Additional keyword arguments passed to the storage service if ``len(store_tuple)<4`` :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ node = store_tuple[1] msg = store_tuple[0] if len(store_tuple) > 2: args = store_tuple[2] if len(store_tuple) > 3: kwargs = store_tuple[3] if len(store_tuple) > 4: raise ValueError('Your argument tuple %s has to many entries, please call ' 'store with [(msg,item,args,kwargs),...]' % str(store_tuple)) # #dummy test _ = self._fetch_from_node(store_load, node, args, kwargs) return msg, node, args, kwargs
def _fetch_from_tuple(self, store_load, store_tuple, args, kwargs): """ Method used by f_store/load/remove_items to find a corresponding item in the tree. The input to the method should already be in the correct format, this method only checks for sanity. :param store_load: String constant specifying if we want to store, load or remove :param store_tuple: Tuple already in correct format (msg, item, args, kwargs). If args and kwargs are not given, they are taken from the supplied parameters :param args: Additional arguments passed to the storage service if len(store_tuple)<3 :param kwargs: Additional keyword arguments passed to the storage service if ``len(store_tuple)<4`` :return: A formatted request that can be handled by the storage service, aka a tuple: (msg, item_to_store_load_or_remove, args, kwargs) """ node = store_tuple[1] msg = store_tuple[0] if len(store_tuple) > 2: args = store_tuple[2] if len(store_tuple) > 3: kwargs = store_tuple[3] if len(store_tuple) > 4: raise ValueError('Your argument tuple %s has to many entries, please call ' 'store with [(msg,item,args,kwargs),...]' % str(store_tuple)) # #dummy test _ = self._fetch_from_node(store_load, node, args, kwargs) return msg, node, args, kwargs
[ "Method", "used", "by", "f_store", "/", "load", "/", "remove_items", "to", "find", "a", "corresponding", "item", "in", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L572-L613
[ "def", "_fetch_from_tuple", "(", "self", ",", "store_load", ",", "store_tuple", ",", "args", ",", "kwargs", ")", ":", "node", "=", "store_tuple", "[", "1", "]", "msg", "=", "store_tuple", "[", "0", "]", "if", "len", "(", "store_tuple", ")", ">", "2", ":", "args", "=", "store_tuple", "[", "2", "]", "if", "len", "(", "store_tuple", ")", ">", "3", ":", "kwargs", "=", "store_tuple", "[", "3", "]", "if", "len", "(", "store_tuple", ")", ">", "4", ":", "raise", "ValueError", "(", "'Your argument tuple %s has to many entries, please call '", "'store with [(msg,item,args,kwargs),...]'", "%", "str", "(", "store_tuple", ")", ")", "# #dummy test", "_", "=", "self", ".", "_fetch_from_node", "(", "store_load", ",", "node", ",", "args", ",", "kwargs", ")", "return", "msg", ",", "node", ",", "args", ",", "kwargs" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._node_to_msg
Maps a given node and a store_load constant to the message that is understood by the storage service.
pypet/naturalnaming.py
def _node_to_msg(store_load, node): """Maps a given node and a store_load constant to the message that is understood by the storage service. """ if node.v_is_leaf: if store_load == STORE: return pypetconstants.LEAF elif store_load == LOAD: return pypetconstants.LEAF elif store_load == REMOVE: return pypetconstants.DELETE else: if store_load == STORE: return pypetconstants.GROUP elif store_load == LOAD: return pypetconstants.GROUP elif store_load == REMOVE: return pypetconstants.DELETE
def _node_to_msg(store_load, node): """Maps a given node and a store_load constant to the message that is understood by the storage service. """ if node.v_is_leaf: if store_load == STORE: return pypetconstants.LEAF elif store_load == LOAD: return pypetconstants.LEAF elif store_load == REMOVE: return pypetconstants.DELETE else: if store_load == STORE: return pypetconstants.GROUP elif store_load == LOAD: return pypetconstants.GROUP elif store_load == REMOVE: return pypetconstants.DELETE
[ "Maps", "a", "given", "node", "and", "a", "store_load", "constant", "to", "the", "message", "that", "is", "understood", "by", "the", "storage", "service", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L616-L634
[ "def", "_node_to_msg", "(", "store_load", ",", "node", ")", ":", "if", "node", ".", "v_is_leaf", ":", "if", "store_load", "==", "STORE", ":", "return", "pypetconstants", ".", "LEAF", "elif", "store_load", "==", "LOAD", ":", "return", "pypetconstants", ".", "LEAF", "elif", "store_load", "==", "REMOVE", ":", "return", "pypetconstants", ".", "DELETE", "else", ":", "if", "store_load", "==", "STORE", ":", "return", "pypetconstants", ".", "GROUP", "elif", "store_load", "==", "LOAD", ":", "return", "pypetconstants", ".", "GROUP", "elif", "store_load", "==", "REMOVE", ":", "return", "pypetconstants", ".", "DELETE" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._fetch_items
Method used by f_store/load/remove_items to find corresponding items in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param iterable: Iterable over items to look for in the tree. Can be strings specifying names, can be the item instances themselves or already correctly formatted tuples. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service. Two optional keyword arguments are popped and used by this method. only_empties: Can be in kwargs if only empty parameters and results should be considered. non_empties: Can be in kwargs if only non-empty parameters and results should be considered. :return: A list containing formatted tuples. These tuples can be handled by the storage service, they have the following format: (msg, item_to_store_load_or_remove, args, kwargs)
pypet/naturalnaming.py
def _fetch_items(self, store_load, iterable, args, kwargs): """ Method used by f_store/load/remove_items to find corresponding items in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param iterable: Iterable over items to look for in the tree. Can be strings specifying names, can be the item instances themselves or already correctly formatted tuples. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service. Two optional keyword arguments are popped and used by this method. only_empties: Can be in kwargs if only empty parameters and results should be considered. non_empties: Can be in kwargs if only non-empty parameters and results should be considered. :return: A list containing formatted tuples. These tuples can be handled by the storage service, they have the following format: (msg, item_to_store_load_or_remove, args, kwargs) """ only_empties = kwargs.pop('only_empties', False) non_empties = kwargs.pop('non_empties', False) item_list = [] # Iterate through the iterable and apply the appropriate fetching method via try and error. for iter_item in iterable: try: item_tuple = self._fetch_from_string(store_load, iter_item, args, kwargs) except TypeError: try: item_tuple = self._fetch_from_node(store_load, iter_item, args, kwargs) except AttributeError: item_tuple = self._fetch_from_tuple(store_load, iter_item, args, kwargs) item = item_tuple[1] msg = item_tuple[0] if item.v_is_leaf: if only_empties and not item.f_is_empty(): continue if non_empties and item.f_is_empty(): continue # # Explored Parameters cannot be deleted, this would break the underlying hdf5 file # # structure # if (msg == pypetconstants.DELETE and # item.v_full_name in self._root_instance._explored_parameters and # len(self._root_instance._explored_parameters) == 1): # raise TypeError('You cannot the last explored parameter of a trajectory stored ' # 'into an hdf5 file.') item_list.append(item_tuple) return item_list
def _fetch_items(self, store_load, iterable, args, kwargs): """ Method used by f_store/load/remove_items to find corresponding items in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the top of this module. :param iterable: Iterable over items to look for in the tree. Can be strings specifying names, can be the item instances themselves or already correctly formatted tuples. :param args: Additional arguments passed to the storage service :param kwargs: Additional keyword arguments passed to the storage service. Two optional keyword arguments are popped and used by this method. only_empties: Can be in kwargs if only empty parameters and results should be considered. non_empties: Can be in kwargs if only non-empty parameters and results should be considered. :return: A list containing formatted tuples. These tuples can be handled by the storage service, they have the following format: (msg, item_to_store_load_or_remove, args, kwargs) """ only_empties = kwargs.pop('only_empties', False) non_empties = kwargs.pop('non_empties', False) item_list = [] # Iterate through the iterable and apply the appropriate fetching method via try and error. for iter_item in iterable: try: item_tuple = self._fetch_from_string(store_load, iter_item, args, kwargs) except TypeError: try: item_tuple = self._fetch_from_node(store_load, iter_item, args, kwargs) except AttributeError: item_tuple = self._fetch_from_tuple(store_load, iter_item, args, kwargs) item = item_tuple[1] msg = item_tuple[0] if item.v_is_leaf: if only_empties and not item.f_is_empty(): continue if non_empties and item.f_is_empty(): continue # # Explored Parameters cannot be deleted, this would break the underlying hdf5 file # # structure # if (msg == pypetconstants.DELETE and # item.v_full_name in self._root_instance._explored_parameters and # len(self._root_instance._explored_parameters) == 1): # raise TypeError('You cannot the last explored parameter of a trajectory stored ' # 'into an hdf5 file.') item_list.append(item_tuple) return item_list
[ "Method", "used", "by", "f_store", "/", "load", "/", "remove_items", "to", "find", "corresponding", "items", "in", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L636-L708
[ "def", "_fetch_items", "(", "self", ",", "store_load", ",", "iterable", ",", "args", ",", "kwargs", ")", ":", "only_empties", "=", "kwargs", ".", "pop", "(", "'only_empties'", ",", "False", ")", "non_empties", "=", "kwargs", ".", "pop", "(", "'non_empties'", ",", "False", ")", "item_list", "=", "[", "]", "# Iterate through the iterable and apply the appropriate fetching method via try and error.", "for", "iter_item", "in", "iterable", ":", "try", ":", "item_tuple", "=", "self", ".", "_fetch_from_string", "(", "store_load", ",", "iter_item", ",", "args", ",", "kwargs", ")", "except", "TypeError", ":", "try", ":", "item_tuple", "=", "self", ".", "_fetch_from_node", "(", "store_load", ",", "iter_item", ",", "args", ",", "kwargs", ")", "except", "AttributeError", ":", "item_tuple", "=", "self", ".", "_fetch_from_tuple", "(", "store_load", ",", "iter_item", ",", "args", ",", "kwargs", ")", "item", "=", "item_tuple", "[", "1", "]", "msg", "=", "item_tuple", "[", "0", "]", "if", "item", ".", "v_is_leaf", ":", "if", "only_empties", "and", "not", "item", ".", "f_is_empty", "(", ")", ":", "continue", "if", "non_empties", "and", "item", ".", "f_is_empty", "(", ")", ":", "continue", "# # Explored Parameters cannot be deleted, this would break the underlying hdf5 file", "# # structure", "# if (msg == pypetconstants.DELETE and", "# item.v_full_name in self._root_instance._explored_parameters and", "# len(self._root_instance._explored_parameters) == 1):", "# raise TypeError('You cannot the last explored parameter of a trajectory stored '", "# 'into an hdf5 file.')", "item_list", ".", "append", "(", "item_tuple", ")", "return", "item_list" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._remove_subtree
Removes a subtree from the trajectory tree. Does not delete stuff from disk only from RAM. :param start_node: The parent node from where to start :param name: Name of child which will be deleted and recursively all nodes below the child :param predicate: Predicate that can be used to compute for individual nodes if they should be removed ``True`` or kept ``False``.
pypet/naturalnaming.py
def _remove_subtree(self, start_node, name, predicate=None): """Removes a subtree from the trajectory tree. Does not delete stuff from disk only from RAM. :param start_node: The parent node from where to start :param name: Name of child which will be deleted and recursively all nodes below the child :param predicate: Predicate that can be used to compute for individual nodes if they should be removed ``True`` or kept ``False``. """ def _delete_from_children(node, child_name): del node._children[child_name] if child_name in node._groups: del node._groups[child_name] elif child_name in node._leaves: del node._leaves[child_name] else: raise RuntimeError('You shall not pass!') def _remove_subtree_inner(node, predicate): if not predicate(node): return False elif node.v_is_group: for name_ in itools.chain(list(node._leaves.keys()), list(node._groups.keys())): child_ = node._children[name_] child_deleted = _remove_subtree_inner(child_, predicate) if child_deleted: _delete_from_children(node, name_) del child_ for link_ in list(node._links.keys()): node.f_remove_link(link_) if len(node._children) == 0: self._delete_node(node) return True else: return False else: self._delete_node(node) return True if name in start_node._links: start_node.f_remove_link(name) else: child = start_node._children[name] if predicate is None: predicate = lambda x: True if _remove_subtree_inner(child, predicate): _delete_from_children(start_node, name) del child return True else: return False
def _remove_subtree(self, start_node, name, predicate=None): """Removes a subtree from the trajectory tree. Does not delete stuff from disk only from RAM. :param start_node: The parent node from where to start :param name: Name of child which will be deleted and recursively all nodes below the child :param predicate: Predicate that can be used to compute for individual nodes if they should be removed ``True`` or kept ``False``. """ def _delete_from_children(node, child_name): del node._children[child_name] if child_name in node._groups: del node._groups[child_name] elif child_name in node._leaves: del node._leaves[child_name] else: raise RuntimeError('You shall not pass!') def _remove_subtree_inner(node, predicate): if not predicate(node): return False elif node.v_is_group: for name_ in itools.chain(list(node._leaves.keys()), list(node._groups.keys())): child_ = node._children[name_] child_deleted = _remove_subtree_inner(child_, predicate) if child_deleted: _delete_from_children(node, name_) del child_ for link_ in list(node._links.keys()): node.f_remove_link(link_) if len(node._children) == 0: self._delete_node(node) return True else: return False else: self._delete_node(node) return True if name in start_node._links: start_node.f_remove_link(name) else: child = start_node._children[name] if predicate is None: predicate = lambda x: True if _remove_subtree_inner(child, predicate): _delete_from_children(start_node, name) del child return True else: return False
[ "Removes", "a", "subtree", "from", "the", "trajectory", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L710-L769
[ "def", "_remove_subtree", "(", "self", ",", "start_node", ",", "name", ",", "predicate", "=", "None", ")", ":", "def", "_delete_from_children", "(", "node", ",", "child_name", ")", ":", "del", "node", ".", "_children", "[", "child_name", "]", "if", "child_name", "in", "node", ".", "_groups", ":", "del", "node", ".", "_groups", "[", "child_name", "]", "elif", "child_name", "in", "node", ".", "_leaves", ":", "del", "node", ".", "_leaves", "[", "child_name", "]", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")", "def", "_remove_subtree_inner", "(", "node", ",", "predicate", ")", ":", "if", "not", "predicate", "(", "node", ")", ":", "return", "False", "elif", "node", ".", "v_is_group", ":", "for", "name_", "in", "itools", ".", "chain", "(", "list", "(", "node", ".", "_leaves", ".", "keys", "(", ")", ")", ",", "list", "(", "node", ".", "_groups", ".", "keys", "(", ")", ")", ")", ":", "child_", "=", "node", ".", "_children", "[", "name_", "]", "child_deleted", "=", "_remove_subtree_inner", "(", "child_", ",", "predicate", ")", "if", "child_deleted", ":", "_delete_from_children", "(", "node", ",", "name_", ")", "del", "child_", "for", "link_", "in", "list", "(", "node", ".", "_links", ".", "keys", "(", ")", ")", ":", "node", ".", "f_remove_link", "(", "link_", ")", "if", "len", "(", "node", ".", "_children", ")", "==", "0", ":", "self", ".", "_delete_node", "(", "node", ")", "return", "True", "else", ":", "return", "False", "else", ":", "self", ".", "_delete_node", "(", "node", ")", "return", "True", "if", "name", "in", "start_node", ".", "_links", ":", "start_node", ".", "f_remove_link", "(", "name", ")", "else", ":", "child", "=", "start_node", ".", "_children", "[", "name", "]", "if", "predicate", "is", "None", ":", "predicate", "=", "lambda", "x", ":", "True", "if", "_remove_subtree_inner", "(", "child", ",", "predicate", ")", ":", "_delete_from_children", "(", "start_node", ",", "name", ")", "del", "child", "return", "True", "else", ":", "return", "False" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._delete_node
Deletes a single node from the tree. Removes all references to the node. Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups hanging directly below root cannot be deleted. Also the root node itself cannot be deleted. (This would cause a tremendous wave of uncontrollable self destruction, which would finally lead to the Apocalypse!)
pypet/naturalnaming.py
def _delete_node(self, node): """Deletes a single node from the tree. Removes all references to the node. Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups hanging directly below root cannot be deleted. Also the root node itself cannot be deleted. (This would cause a tremendous wave of uncontrollable self destruction, which would finally lead to the Apocalypse!) """ full_name = node.v_full_name root = self._root_instance if full_name == '': # You cannot delete root return if node.v_is_leaf: if full_name in root._parameters: del root._parameters[full_name] elif full_name in root._config: del root._config[full_name] elif full_name in root._derived_parameters: del root._derived_parameters[full_name] elif full_name in root._results: del root._results[full_name] elif full_name in root._other_leaves: del root._other_leaves[full_name] if full_name in root._explored_parameters: if root._stored: # We always keep the explored parameters in case the trajectory was stored root._explored_parameters[full_name] = None else: del root._explored_parameters[full_name] if len(root._explored_parameters) == 0: root.f_shrink() del self._flat_leaf_storage_dict[full_name] else: del root._all_groups[full_name] if full_name in root._run_parent_groups: del root._run_parent_groups[full_name] # Delete all links to the node if full_name in root._linked_by: linking = root._linked_by[full_name] for linking_name in list(linking.keys()): linking_group, link_set = linking[linking_name] for link in list(link_set): linking_group.f_remove_link(link) if (node.v_location, node.v_name) in self._root_instance._new_nodes: del self._root_instance._new_nodes[(node.v_location, node.v_name)] # Finally remove all references in the dictionaries for fast search self._remove_from_nodes_and_leaves(node) # Remove circular references node._vars = None node._func = None
def _delete_node(self, node): """Deletes a single node from the tree. Removes all references to the node. Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups hanging directly below root cannot be deleted. Also the root node itself cannot be deleted. (This would cause a tremendous wave of uncontrollable self destruction, which would finally lead to the Apocalypse!) """ full_name = node.v_full_name root = self._root_instance if full_name == '': # You cannot delete root return if node.v_is_leaf: if full_name in root._parameters: del root._parameters[full_name] elif full_name in root._config: del root._config[full_name] elif full_name in root._derived_parameters: del root._derived_parameters[full_name] elif full_name in root._results: del root._results[full_name] elif full_name in root._other_leaves: del root._other_leaves[full_name] if full_name in root._explored_parameters: if root._stored: # We always keep the explored parameters in case the trajectory was stored root._explored_parameters[full_name] = None else: del root._explored_parameters[full_name] if len(root._explored_parameters) == 0: root.f_shrink() del self._flat_leaf_storage_dict[full_name] else: del root._all_groups[full_name] if full_name in root._run_parent_groups: del root._run_parent_groups[full_name] # Delete all links to the node if full_name in root._linked_by: linking = root._linked_by[full_name] for linking_name in list(linking.keys()): linking_group, link_set = linking[linking_name] for link in list(link_set): linking_group.f_remove_link(link) if (node.v_location, node.v_name) in self._root_instance._new_nodes: del self._root_instance._new_nodes[(node.v_location, node.v_name)] # Finally remove all references in the dictionaries for fast search self._remove_from_nodes_and_leaves(node) # Remove circular references node._vars = None node._func = None
[ "Deletes", "a", "single", "node", "from", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L771-L838
[ "def", "_delete_node", "(", "self", ",", "node", ")", ":", "full_name", "=", "node", ".", "v_full_name", "root", "=", "self", ".", "_root_instance", "if", "full_name", "==", "''", ":", "# You cannot delete root", "return", "if", "node", ".", "v_is_leaf", ":", "if", "full_name", "in", "root", ".", "_parameters", ":", "del", "root", ".", "_parameters", "[", "full_name", "]", "elif", "full_name", "in", "root", ".", "_config", ":", "del", "root", ".", "_config", "[", "full_name", "]", "elif", "full_name", "in", "root", ".", "_derived_parameters", ":", "del", "root", ".", "_derived_parameters", "[", "full_name", "]", "elif", "full_name", "in", "root", ".", "_results", ":", "del", "root", ".", "_results", "[", "full_name", "]", "elif", "full_name", "in", "root", ".", "_other_leaves", ":", "del", "root", ".", "_other_leaves", "[", "full_name", "]", "if", "full_name", "in", "root", ".", "_explored_parameters", ":", "if", "root", ".", "_stored", ":", "# We always keep the explored parameters in case the trajectory was stored", "root", ".", "_explored_parameters", "[", "full_name", "]", "=", "None", "else", ":", "del", "root", ".", "_explored_parameters", "[", "full_name", "]", "if", "len", "(", "root", ".", "_explored_parameters", ")", "==", "0", ":", "root", ".", "f_shrink", "(", ")", "del", "self", ".", "_flat_leaf_storage_dict", "[", "full_name", "]", "else", ":", "del", "root", ".", "_all_groups", "[", "full_name", "]", "if", "full_name", "in", "root", ".", "_run_parent_groups", ":", "del", "root", ".", "_run_parent_groups", "[", "full_name", "]", "# Delete all links to the node", "if", "full_name", "in", "root", ".", "_linked_by", ":", "linking", "=", "root", ".", "_linked_by", "[", "full_name", "]", "for", "linking_name", "in", "list", "(", "linking", ".", "keys", "(", ")", ")", ":", "linking_group", ",", "link_set", "=", "linking", "[", "linking_name", "]", "for", "link", "in", "list", "(", "link_set", ")", ":", "linking_group", ".", "f_remove_link", "(", "link", ")", "if", "(", "node", ".", "v_location", ",", "node", ".", "v_name", ")", "in", "self", ".", "_root_instance", ".", "_new_nodes", ":", "del", "self", ".", "_root_instance", ".", "_new_nodes", "[", "(", "node", ".", "v_location", ",", "node", ".", "v_name", ")", "]", "# Finally remove all references in the dictionaries for fast search", "self", ".", "_remove_from_nodes_and_leaves", "(", "node", ")", "# Remove circular references", "node", ".", "_vars", "=", "None", "node", ".", "_func", "=", "None" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._remove_node_or_leaf
Removes a single node from the tree. Only from RAM not from hdf5 file! :param instance: The node to be deleted :param recursive: If group nodes with children should be deleted
pypet/naturalnaming.py
def _remove_node_or_leaf(self, instance, recursive=False): """Removes a single node from the tree. Only from RAM not from hdf5 file! :param instance: The node to be deleted :param recursive: If group nodes with children should be deleted """ full_name = instance.v_full_name split_name = deque(full_name.split('.')) self._remove_along_branch(self._root_instance, split_name, recursive)
def _remove_node_or_leaf(self, instance, recursive=False): """Removes a single node from the tree. Only from RAM not from hdf5 file! :param instance: The node to be deleted :param recursive: If group nodes with children should be deleted """ full_name = instance.v_full_name split_name = deque(full_name.split('.')) self._remove_along_branch(self._root_instance, split_name, recursive)
[ "Removes", "a", "single", "node", "from", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L856-L868
[ "def", "_remove_node_or_leaf", "(", "self", ",", "instance", ",", "recursive", "=", "False", ")", ":", "full_name", "=", "instance", ".", "v_full_name", "split_name", "=", "deque", "(", "full_name", ".", "split", "(", "'.'", ")", ")", "self", ".", "_remove_along_branch", "(", "self", ".", "_root_instance", ",", "split_name", ",", "recursive", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._remove_along_branch
Removes a given node from the tree. Starts from a given node and walks recursively down the tree to the location of the node we want to remove. We need to walk from a start node in case we want to check on the way back whether we got empty group nodes due to deletion. :param actual_node: Current node :param split_name: DEQUE of names to get the next nodes. :param recursive: To also delete all children of a group node :return: True if node was deleted, otherwise False
pypet/naturalnaming.py
def _remove_along_branch(self, actual_node, split_name, recursive=False): """Removes a given node from the tree. Starts from a given node and walks recursively down the tree to the location of the node we want to remove. We need to walk from a start node in case we want to check on the way back whether we got empty group nodes due to deletion. :param actual_node: Current node :param split_name: DEQUE of names to get the next nodes. :param recursive: To also delete all children of a group node :return: True if node was deleted, otherwise False """ # If the names list is empty, we have reached the node we want to delete. if len(split_name) == 0: if actual_node.v_is_group and actual_node.f_has_children(): if recursive: for child in list(actual_node._children.keys()): actual_node.f_remove_child(child, recursive=True) else: raise TypeError('Cannot remove group `%s` it contains children. Please ' 'remove with `recursive=True`.' % actual_node.v_full_name) self._delete_node(actual_node) return True # Otherwise get the next node by using the first name in the list name = split_name.popleft() if name in actual_node._links: if len(split_name)>0: raise RuntimeError('You cannot remove nodes while hopping over links!') actual_node.f_remove_link(name) else: child = actual_node._children[name] if self._remove_along_branch(child, split_name, recursive=recursive): del actual_node._children[name] if name in actual_node._groups: del actual_node._groups[name] elif name in actual_node._leaves: del actual_node._leaves[name] else: raise RuntimeError('You shall not pass!') del child return False
def _remove_along_branch(self, actual_node, split_name, recursive=False): """Removes a given node from the tree. Starts from a given node and walks recursively down the tree to the location of the node we want to remove. We need to walk from a start node in case we want to check on the way back whether we got empty group nodes due to deletion. :param actual_node: Current node :param split_name: DEQUE of names to get the next nodes. :param recursive: To also delete all children of a group node :return: True if node was deleted, otherwise False """ # If the names list is empty, we have reached the node we want to delete. if len(split_name) == 0: if actual_node.v_is_group and actual_node.f_has_children(): if recursive: for child in list(actual_node._children.keys()): actual_node.f_remove_child(child, recursive=True) else: raise TypeError('Cannot remove group `%s` it contains children. Please ' 'remove with `recursive=True`.' % actual_node.v_full_name) self._delete_node(actual_node) return True # Otherwise get the next node by using the first name in the list name = split_name.popleft() if name in actual_node._links: if len(split_name)>0: raise RuntimeError('You cannot remove nodes while hopping over links!') actual_node.f_remove_link(name) else: child = actual_node._children[name] if self._remove_along_branch(child, split_name, recursive=recursive): del actual_node._children[name] if name in actual_node._groups: del actual_node._groups[name] elif name in actual_node._leaves: del actual_node._leaves[name] else: raise RuntimeError('You shall not pass!') del child return False
[ "Removes", "a", "given", "node", "from", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L870-L924
[ "def", "_remove_along_branch", "(", "self", ",", "actual_node", ",", "split_name", ",", "recursive", "=", "False", ")", ":", "# If the names list is empty, we have reached the node we want to delete.", "if", "len", "(", "split_name", ")", "==", "0", ":", "if", "actual_node", ".", "v_is_group", "and", "actual_node", ".", "f_has_children", "(", ")", ":", "if", "recursive", ":", "for", "child", "in", "list", "(", "actual_node", ".", "_children", ".", "keys", "(", ")", ")", ":", "actual_node", ".", "f_remove_child", "(", "child", ",", "recursive", "=", "True", ")", "else", ":", "raise", "TypeError", "(", "'Cannot remove group `%s` it contains children. Please '", "'remove with `recursive=True`.'", "%", "actual_node", ".", "v_full_name", ")", "self", ".", "_delete_node", "(", "actual_node", ")", "return", "True", "# Otherwise get the next node by using the first name in the list", "name", "=", "split_name", ".", "popleft", "(", ")", "if", "name", "in", "actual_node", ".", "_links", ":", "if", "len", "(", "split_name", ")", ">", "0", ":", "raise", "RuntimeError", "(", "'You cannot remove nodes while hopping over links!'", ")", "actual_node", ".", "f_remove_link", "(", "name", ")", "else", ":", "child", "=", "actual_node", ".", "_children", "[", "name", "]", "if", "self", ".", "_remove_along_branch", "(", "child", ",", "split_name", ",", "recursive", "=", "recursive", ")", ":", "del", "actual_node", ".", "_children", "[", "name", "]", "if", "name", "in", "actual_node", ".", "_groups", ":", "del", "actual_node", ".", "_groups", "[", "name", "]", "elif", "name", "in", "actual_node", ".", "_leaves", ":", "del", "actual_node", ".", "_leaves", "[", "name", "]", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")", "del", "child", "return", "False" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._translate_shortcut
Maps a given shortcut to corresponding name * 'run_X' or 'r_X' to 'run_XXXXXXXXX' * 'crun' to the current run name in case of a single run instance if trajectory is used via `v_crun` * 'par' 'parameters' * 'dpar' to 'derived_parameters' * 'res' to 'results' * 'conf' to 'config' :return: True or False and the mapped name.
pypet/naturalnaming.py
def _translate_shortcut(self, name): """Maps a given shortcut to corresponding name * 'run_X' or 'r_X' to 'run_XXXXXXXXX' * 'crun' to the current run name in case of a single run instance if trajectory is used via `v_crun` * 'par' 'parameters' * 'dpar' to 'derived_parameters' * 'res' to 'results' * 'conf' to 'config' :return: True or False and the mapped name. """ if isinstance(name, int): return True, self._root_instance.f_wildcard('$', name) if name.startswith('run_') or name.startswith('r_'): split_name = name.split('_') if len(split_name) == 2: index = split_name[1] if index.isdigit(): return True, self._root_instance.f_wildcard('$', int(index)) elif index == 'A': return True, self._root_instance.f_wildcard('$', -1) if name.startswith('runtoset_') or name.startswith('rts_'): split_name = name.split('_') if len(split_name) == 2: index = split_name[1] if index.isdigit(): return True, self._root_instance.f_wildcard('$set', int(index)) elif index == 'A': return True, self._root_instance.f_wildcard('$set', -1) if name in SHORTCUT_SET: if name == 'par': return True, 'parameters' elif name == 'dpar': return True, 'derived_parameters' elif name == 'res': return True, 'results' elif name == 'conf': return True, 'config' else: raise RuntimeError('You shall not pass!') return False, name
def _translate_shortcut(self, name): """Maps a given shortcut to corresponding name * 'run_X' or 'r_X' to 'run_XXXXXXXXX' * 'crun' to the current run name in case of a single run instance if trajectory is used via `v_crun` * 'par' 'parameters' * 'dpar' to 'derived_parameters' * 'res' to 'results' * 'conf' to 'config' :return: True or False and the mapped name. """ if isinstance(name, int): return True, self._root_instance.f_wildcard('$', name) if name.startswith('run_') or name.startswith('r_'): split_name = name.split('_') if len(split_name) == 2: index = split_name[1] if index.isdigit(): return True, self._root_instance.f_wildcard('$', int(index)) elif index == 'A': return True, self._root_instance.f_wildcard('$', -1) if name.startswith('runtoset_') or name.startswith('rts_'): split_name = name.split('_') if len(split_name) == 2: index = split_name[1] if index.isdigit(): return True, self._root_instance.f_wildcard('$set', int(index)) elif index == 'A': return True, self._root_instance.f_wildcard('$set', -1) if name in SHORTCUT_SET: if name == 'par': return True, 'parameters' elif name == 'dpar': return True, 'derived_parameters' elif name == 'res': return True, 'results' elif name == 'conf': return True, 'config' else: raise RuntimeError('You shall not pass!') return False, name
[ "Maps", "a", "given", "shortcut", "to", "corresponding", "name" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L926-L979
[ "def", "_translate_shortcut", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "name", ",", "int", ")", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "'$'", ",", "name", ")", "if", "name", ".", "startswith", "(", "'run_'", ")", "or", "name", ".", "startswith", "(", "'r_'", ")", ":", "split_name", "=", "name", ".", "split", "(", "'_'", ")", "if", "len", "(", "split_name", ")", "==", "2", ":", "index", "=", "split_name", "[", "1", "]", "if", "index", ".", "isdigit", "(", ")", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "'$'", ",", "int", "(", "index", ")", ")", "elif", "index", "==", "'A'", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "'$'", ",", "-", "1", ")", "if", "name", ".", "startswith", "(", "'runtoset_'", ")", "or", "name", ".", "startswith", "(", "'rts_'", ")", ":", "split_name", "=", "name", ".", "split", "(", "'_'", ")", "if", "len", "(", "split_name", ")", "==", "2", ":", "index", "=", "split_name", "[", "1", "]", "if", "index", ".", "isdigit", "(", ")", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "'$set'", ",", "int", "(", "index", ")", ")", "elif", "index", "==", "'A'", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "'$set'", ",", "-", "1", ")", "if", "name", "in", "SHORTCUT_SET", ":", "if", "name", "==", "'par'", ":", "return", "True", ",", "'parameters'", "elif", "name", "==", "'dpar'", ":", "return", "True", ",", "'derived_parameters'", "elif", "name", "==", "'res'", ":", "return", "True", ",", "'results'", "elif", "name", "==", "'conf'", ":", "return", "True", ",", "'config'", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")", "return", "False", ",", "name" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._add_prefix
Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. For example, this could be 'parameters' for parameters or 'results.run_00000004' for results added to the fifth single run. :param split_names: List of names of the new node (e.g. ``['mynewgroupA', 'mynewgroupB', 'myresult']``). :param start_node: Parent node under which the new node should be added. :param group_type_name: Type name of subbranch the item belongs to (e.g. 'PARAMETER_GROUP', 'RESULT_GROUP' etc). :return: The name with the added prefix.
pypet/naturalnaming.py
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. For example, this could be 'parameters' for parameters or 'results.run_00000004' for results added to the fifth single run. :param split_names: List of names of the new node (e.g. ``['mynewgroupA', 'mynewgroupB', 'myresult']``). :param start_node: Parent node under which the new node should be added. :param group_type_name: Type name of subbranch the item belongs to (e.g. 'PARAMETER_GROUP', 'RESULT_GROUP' etc). :return: The name with the added prefix. """ root = self._root_instance # If the start node of our insertion is root or one below root # we might need to add prefixes. # In case of derived parameters and results we also need to add prefixes containing the # subbranch and the current run in case of a single run. # For instance, a prefix could be 'results.runs.run_00000007'. prepend = [] if start_node.v_depth < 3 and not group_type_name == GROUP: if start_node.v_depth == 0: if group_type_name == DERIVED_PARAMETER_GROUP: if split_names[0] == 'derived_parameters': return split_names else: prepend += ['derived_parameters'] elif group_type_name == RESULT_GROUP: if split_names[0] == 'results': return split_names else: prepend += ['results'] elif group_type_name == CONFIG_GROUP: if split_names[0] == 'config': return split_names else: prepend += ['config'] elif group_type_name == PARAMETER_GROUP: if split_names[0] == 'parameters': return split_names[0] else: prepend += ['parameters'] else: raise RuntimeError('Why are you here?') # Check if we have to add a prefix containing the current run if root._is_run and root._auto_run_prepend: dummy = root.f_wildcard('$', -1) crun = root.f_wildcard('$') if any(name in root._run_information for name in split_names): pass elif any(name == dummy for name in split_names): pass elif (group_type_name == RESULT_GROUP or group_type_name == DERIVED_PARAMETER_GROUP): if start_node.v_depth == 0: prepend += ['runs', crun] elif start_node.v_depth == 1: if len(split_names) == 1 and split_names[0] == 'runs': return split_names else: prepend += ['runs', crun] elif start_node.v_depth == 2 and start_node.v_name == 'runs': prepend += [crun] if prepend: split_names = prepend + split_names return split_names
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. For example, this could be 'parameters' for parameters or 'results.run_00000004' for results added to the fifth single run. :param split_names: List of names of the new node (e.g. ``['mynewgroupA', 'mynewgroupB', 'myresult']``). :param start_node: Parent node under which the new node should be added. :param group_type_name: Type name of subbranch the item belongs to (e.g. 'PARAMETER_GROUP', 'RESULT_GROUP' etc). :return: The name with the added prefix. """ root = self._root_instance # If the start node of our insertion is root or one below root # we might need to add prefixes. # In case of derived parameters and results we also need to add prefixes containing the # subbranch and the current run in case of a single run. # For instance, a prefix could be 'results.runs.run_00000007'. prepend = [] if start_node.v_depth < 3 and not group_type_name == GROUP: if start_node.v_depth == 0: if group_type_name == DERIVED_PARAMETER_GROUP: if split_names[0] == 'derived_parameters': return split_names else: prepend += ['derived_parameters'] elif group_type_name == RESULT_GROUP: if split_names[0] == 'results': return split_names else: prepend += ['results'] elif group_type_name == CONFIG_GROUP: if split_names[0] == 'config': return split_names else: prepend += ['config'] elif group_type_name == PARAMETER_GROUP: if split_names[0] == 'parameters': return split_names[0] else: prepend += ['parameters'] else: raise RuntimeError('Why are you here?') # Check if we have to add a prefix containing the current run if root._is_run and root._auto_run_prepend: dummy = root.f_wildcard('$', -1) crun = root.f_wildcard('$') if any(name in root._run_information for name in split_names): pass elif any(name == dummy for name in split_names): pass elif (group_type_name == RESULT_GROUP or group_type_name == DERIVED_PARAMETER_GROUP): if start_node.v_depth == 0: prepend += ['runs', crun] elif start_node.v_depth == 1: if len(split_names) == 1 and split_names[0] == 'runs': return split_names else: prepend += ['runs', crun] elif start_node.v_depth == 2 and start_node.v_name == 'runs': prepend += [crun] if prepend: split_names = prepend + split_names return split_names
[ "Adds", "the", "correct", "sub", "branch", "prefix", "to", "a", "given", "name", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L981-L1071
[ "def", "_add_prefix", "(", "self", ",", "split_names", ",", "start_node", ",", "group_type_name", ")", ":", "root", "=", "self", ".", "_root_instance", "# If the start node of our insertion is root or one below root", "# we might need to add prefixes.", "# In case of derived parameters and results we also need to add prefixes containing the", "# subbranch and the current run in case of a single run.", "# For instance, a prefix could be 'results.runs.run_00000007'.", "prepend", "=", "[", "]", "if", "start_node", ".", "v_depth", "<", "3", "and", "not", "group_type_name", "==", "GROUP", ":", "if", "start_node", ".", "v_depth", "==", "0", ":", "if", "group_type_name", "==", "DERIVED_PARAMETER_GROUP", ":", "if", "split_names", "[", "0", "]", "==", "'derived_parameters'", ":", "return", "split_names", "else", ":", "prepend", "+=", "[", "'derived_parameters'", "]", "elif", "group_type_name", "==", "RESULT_GROUP", ":", "if", "split_names", "[", "0", "]", "==", "'results'", ":", "return", "split_names", "else", ":", "prepend", "+=", "[", "'results'", "]", "elif", "group_type_name", "==", "CONFIG_GROUP", ":", "if", "split_names", "[", "0", "]", "==", "'config'", ":", "return", "split_names", "else", ":", "prepend", "+=", "[", "'config'", "]", "elif", "group_type_name", "==", "PARAMETER_GROUP", ":", "if", "split_names", "[", "0", "]", "==", "'parameters'", ":", "return", "split_names", "[", "0", "]", "else", ":", "prepend", "+=", "[", "'parameters'", "]", "else", ":", "raise", "RuntimeError", "(", "'Why are you here?'", ")", "# Check if we have to add a prefix containing the current run", "if", "root", ".", "_is_run", "and", "root", ".", "_auto_run_prepend", ":", "dummy", "=", "root", ".", "f_wildcard", "(", "'$'", ",", "-", "1", ")", "crun", "=", "root", ".", "f_wildcard", "(", "'$'", ")", "if", "any", "(", "name", "in", "root", ".", "_run_information", "for", "name", "in", "split_names", ")", ":", "pass", "elif", "any", "(", "name", "==", "dummy", "for", "name", "in", "split_names", ")", ":", "pass", "elif", "(", "group_type_name", "==", "RESULT_GROUP", "or", "group_type_name", "==", "DERIVED_PARAMETER_GROUP", ")", ":", "if", "start_node", ".", "v_depth", "==", "0", ":", "prepend", "+=", "[", "'runs'", ",", "crun", "]", "elif", "start_node", ".", "v_depth", "==", "1", ":", "if", "len", "(", "split_names", ")", "==", "1", "and", "split_names", "[", "0", "]", "==", "'runs'", ":", "return", "split_names", "else", ":", "prepend", "+=", "[", "'runs'", ",", "crun", "]", "elif", "start_node", ".", "v_depth", "==", "2", "and", "start_node", ".", "v_name", "==", "'runs'", ":", "prepend", "+=", "[", "crun", "]", "if", "prepend", ":", "split_names", "=", "prepend", "+", "split_names", "return", "split_names" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._determine_types
Determines types for generic additions
pypet/naturalnaming.py
def _determine_types(start_node, first_name, add_leaf, add_link): """Determines types for generic additions""" if start_node.v_is_root: where = first_name else: where = start_node._branch if where in SUBTREE_MAPPING: type_tuple = SUBTREE_MAPPING[where] else: type_tuple = (GROUP, LEAF) if add_link: return type_tuple[0], LINK if add_leaf: return type_tuple else: return type_tuple[0], type_tuple[0]
def _determine_types(start_node, first_name, add_leaf, add_link): """Determines types for generic additions""" if start_node.v_is_root: where = first_name else: where = start_node._branch if where in SUBTREE_MAPPING: type_tuple = SUBTREE_MAPPING[where] else: type_tuple = (GROUP, LEAF) if add_link: return type_tuple[0], LINK if add_leaf: return type_tuple else: return type_tuple[0], type_tuple[0]
[ "Determines", "types", "for", "generic", "additions" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1074-L1091
[ "def", "_determine_types", "(", "start_node", ",", "first_name", ",", "add_leaf", ",", "add_link", ")", ":", "if", "start_node", ".", "v_is_root", ":", "where", "=", "first_name", "else", ":", "where", "=", "start_node", ".", "_branch", "if", "where", "in", "SUBTREE_MAPPING", ":", "type_tuple", "=", "SUBTREE_MAPPING", "[", "where", "]", "else", ":", "type_tuple", "=", "(", "GROUP", ",", "LEAF", ")", "if", "add_link", ":", "return", "type_tuple", "[", "0", "]", ",", "LINK", "if", "add_leaf", ":", "return", "type_tuple", "else", ":", "return", "type_tuple", "[", "0", "]", ",", "type_tuple", "[", "0", "]" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._add_generic
Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initiated from :param type_name: The type of the new instance. Whether it is a parameter, parameter group, config, config group, etc. See the name of the corresponding constants at the top of this python module. :param group_type_name: Type of the subbranch. i.e. whether the item is added to the 'parameters', 'results' etc. These subbranch types are named as the group names (e.g. 'PARAMETER_GROUP') in order to have less constants. For all constants used see beginning of this python module. :param args: Arguments specifying how the item is added. If len(args)==1 and the argument is the a given instance of a result or parameter, this one is added to the tree. Otherwise it is checked if the first argument is a class specifying how to construct a new item and the second argument is the name of the new class. If the first argument is not a class but a string, the string is assumed to be the name of the new instance. Additional args are later on used for the construction of the instance. :param kwargs: Additional keyword arguments that might be handed over to the instance constructor. :param add_prefix: If a prefix group, i.e. `results`, `config`, etc. should be added :param check_naming: If it should be checked for correct namings, can be set to ``False`` if data is loaded and we know that all names are correct. :return: The new added instance
pypet/naturalnaming.py
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): """Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initiated from :param type_name: The type of the new instance. Whether it is a parameter, parameter group, config, config group, etc. See the name of the corresponding constants at the top of this python module. :param group_type_name: Type of the subbranch. i.e. whether the item is added to the 'parameters', 'results' etc. These subbranch types are named as the group names (e.g. 'PARAMETER_GROUP') in order to have less constants. For all constants used see beginning of this python module. :param args: Arguments specifying how the item is added. If len(args)==1 and the argument is the a given instance of a result or parameter, this one is added to the tree. Otherwise it is checked if the first argument is a class specifying how to construct a new item and the second argument is the name of the new class. If the first argument is not a class but a string, the string is assumed to be the name of the new instance. Additional args are later on used for the construction of the instance. :param kwargs: Additional keyword arguments that might be handed over to the instance constructor. :param add_prefix: If a prefix group, i.e. `results`, `config`, etc. should be added :param check_naming: If it should be checked for correct namings, can be set to ``False`` if data is loaded and we know that all names are correct. :return: The new added instance """ args = list(args) create_new = True name = '' instance = None constructor = None add_link = type_name == LINK # First check if the item is already a given instance or we want to add a link if add_link: name = args[0] instance = args[1] create_new = False elif len(args) == 1 and len(kwargs) == 0: item = args[0] try: name = item.v_full_name instance = item create_new = False except AttributeError: pass # If the item is not an instance yet, check if args[0] is a class and args[1] is # a string describing the new name of the instance. # If args[0] is not a class it is assumed to be the name of the new instance. if create_new: if len(args) > 0 and inspect.isclass(args[0]): constructor = args.pop(0) if len(args) > 0 and isinstance(args[0], str): name = args.pop(0) elif 'name' in kwargs: name = kwargs.pop('name') elif 'full_name' in kwargs: name = kwargs.pop('full_name') else: raise ValueError('Could not determine a name of the new item you want to add. ' 'Either pass the name as positional argument or as a keyword ' 'argument `name`.') split_names = name.split('.') if check_naming: for idx, name in enumerate(split_names): translated_shortcut, name = self._translate_shortcut(name) replaced, name = self._replace_wildcards(name) if translated_shortcut or replaced: split_names[idx] = name # First check if the naming of the new item is appropriate faulty_names = self._check_names(split_names, start_node) if faulty_names: full_name = '.'.join(split_names) raise ValueError( 'Your Parameter/Result/Node `%s` contains the following not admissible names: ' '%s please choose other names.' % (full_name, faulty_names)) if add_link: if instance is None: raise ValueError('You must provide an instance to link to!') if instance.v_is_root: raise ValueError('You cannot create a link to the root node') if start_node.v_is_root and name in SUBTREE_MAPPING: raise ValueError('`%s` is a reserved name for a group under root.' % name) if not self._root_instance.f_contains(instance, with_links=False, shortcuts=False): raise ValueError('You can only link to items within the trajectory tree!') # Check if the name fulfils the prefix conditions, if not change the name accordingly. if add_prefix: split_names = self._add_prefix(split_names, start_node, group_type_name) if group_type_name == GROUP: add_leaf = type_name != group_type_name and not add_link # If this is equal we add a group node group_type_name, type_name = self._determine_types(start_node, split_names[0], add_leaf, add_link) # Check if we are allowed to add the data if self._root_instance._is_run and type_name in SENSITIVE_TYPES: raise TypeError('You are not allowed to add config or parameter data or groups ' 'during a single run.') return self._add_to_tree(start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs)
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): """Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initiated from :param type_name: The type of the new instance. Whether it is a parameter, parameter group, config, config group, etc. See the name of the corresponding constants at the top of this python module. :param group_type_name: Type of the subbranch. i.e. whether the item is added to the 'parameters', 'results' etc. These subbranch types are named as the group names (e.g. 'PARAMETER_GROUP') in order to have less constants. For all constants used see beginning of this python module. :param args: Arguments specifying how the item is added. If len(args)==1 and the argument is the a given instance of a result or parameter, this one is added to the tree. Otherwise it is checked if the first argument is a class specifying how to construct a new item and the second argument is the name of the new class. If the first argument is not a class but a string, the string is assumed to be the name of the new instance. Additional args are later on used for the construction of the instance. :param kwargs: Additional keyword arguments that might be handed over to the instance constructor. :param add_prefix: If a prefix group, i.e. `results`, `config`, etc. should be added :param check_naming: If it should be checked for correct namings, can be set to ``False`` if data is loaded and we know that all names are correct. :return: The new added instance """ args = list(args) create_new = True name = '' instance = None constructor = None add_link = type_name == LINK # First check if the item is already a given instance or we want to add a link if add_link: name = args[0] instance = args[1] create_new = False elif len(args) == 1 and len(kwargs) == 0: item = args[0] try: name = item.v_full_name instance = item create_new = False except AttributeError: pass # If the item is not an instance yet, check if args[0] is a class and args[1] is # a string describing the new name of the instance. # If args[0] is not a class it is assumed to be the name of the new instance. if create_new: if len(args) > 0 and inspect.isclass(args[0]): constructor = args.pop(0) if len(args) > 0 and isinstance(args[0], str): name = args.pop(0) elif 'name' in kwargs: name = kwargs.pop('name') elif 'full_name' in kwargs: name = kwargs.pop('full_name') else: raise ValueError('Could not determine a name of the new item you want to add. ' 'Either pass the name as positional argument or as a keyword ' 'argument `name`.') split_names = name.split('.') if check_naming: for idx, name in enumerate(split_names): translated_shortcut, name = self._translate_shortcut(name) replaced, name = self._replace_wildcards(name) if translated_shortcut or replaced: split_names[idx] = name # First check if the naming of the new item is appropriate faulty_names = self._check_names(split_names, start_node) if faulty_names: full_name = '.'.join(split_names) raise ValueError( 'Your Parameter/Result/Node `%s` contains the following not admissible names: ' '%s please choose other names.' % (full_name, faulty_names)) if add_link: if instance is None: raise ValueError('You must provide an instance to link to!') if instance.v_is_root: raise ValueError('You cannot create a link to the root node') if start_node.v_is_root and name in SUBTREE_MAPPING: raise ValueError('`%s` is a reserved name for a group under root.' % name) if not self._root_instance.f_contains(instance, with_links=False, shortcuts=False): raise ValueError('You can only link to items within the trajectory tree!') # Check if the name fulfils the prefix conditions, if not change the name accordingly. if add_prefix: split_names = self._add_prefix(split_names, start_node, group_type_name) if group_type_name == GROUP: add_leaf = type_name != group_type_name and not add_link # If this is equal we add a group node group_type_name, type_name = self._determine_types(start_node, split_names[0], add_leaf, add_link) # Check if we are allowed to add the data if self._root_instance._is_run and type_name in SENSITIVE_TYPES: raise TypeError('You are not allowed to add config or parameter data or groups ' 'during a single run.') return self._add_to_tree(start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs)
[ "Adds", "a", "given", "item", "to", "the", "tree", "irrespective", "of", "the", "subtree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1093-L1230
[ "def", "_add_generic", "(", "self", ",", "start_node", ",", "type_name", ",", "group_type_name", ",", "args", ",", "kwargs", ",", "add_prefix", "=", "True", ",", "check_naming", "=", "True", ")", ":", "args", "=", "list", "(", "args", ")", "create_new", "=", "True", "name", "=", "''", "instance", "=", "None", "constructor", "=", "None", "add_link", "=", "type_name", "==", "LINK", "# First check if the item is already a given instance or we want to add a link", "if", "add_link", ":", "name", "=", "args", "[", "0", "]", "instance", "=", "args", "[", "1", "]", "create_new", "=", "False", "elif", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", ":", "item", "=", "args", "[", "0", "]", "try", ":", "name", "=", "item", ".", "v_full_name", "instance", "=", "item", "create_new", "=", "False", "except", "AttributeError", ":", "pass", "# If the item is not an instance yet, check if args[0] is a class and args[1] is", "# a string describing the new name of the instance.", "# If args[0] is not a class it is assumed to be the name of the new instance.", "if", "create_new", ":", "if", "len", "(", "args", ")", ">", "0", "and", "inspect", ".", "isclass", "(", "args", "[", "0", "]", ")", ":", "constructor", "=", "args", ".", "pop", "(", "0", ")", "if", "len", "(", "args", ")", ">", "0", "and", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", ":", "name", "=", "args", ".", "pop", "(", "0", ")", "elif", "'name'", "in", "kwargs", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "elif", "'full_name'", "in", "kwargs", ":", "name", "=", "kwargs", ".", "pop", "(", "'full_name'", ")", "else", ":", "raise", "ValueError", "(", "'Could not determine a name of the new item you want to add. '", "'Either pass the name as positional argument or as a keyword '", "'argument `name`.'", ")", "split_names", "=", "name", ".", "split", "(", "'.'", ")", "if", "check_naming", ":", "for", "idx", ",", "name", "in", "enumerate", "(", "split_names", ")", ":", "translated_shortcut", ",", "name", "=", "self", ".", "_translate_shortcut", "(", "name", ")", "replaced", ",", "name", "=", "self", ".", "_replace_wildcards", "(", "name", ")", "if", "translated_shortcut", "or", "replaced", ":", "split_names", "[", "idx", "]", "=", "name", "# First check if the naming of the new item is appropriate", "faulty_names", "=", "self", ".", "_check_names", "(", "split_names", ",", "start_node", ")", "if", "faulty_names", ":", "full_name", "=", "'.'", ".", "join", "(", "split_names", ")", "raise", "ValueError", "(", "'Your Parameter/Result/Node `%s` contains the following not admissible names: '", "'%s please choose other names.'", "%", "(", "full_name", ",", "faulty_names", ")", ")", "if", "add_link", ":", "if", "instance", "is", "None", ":", "raise", "ValueError", "(", "'You must provide an instance to link to!'", ")", "if", "instance", ".", "v_is_root", ":", "raise", "ValueError", "(", "'You cannot create a link to the root node'", ")", "if", "start_node", ".", "v_is_root", "and", "name", "in", "SUBTREE_MAPPING", ":", "raise", "ValueError", "(", "'`%s` is a reserved name for a group under root.'", "%", "name", ")", "if", "not", "self", ".", "_root_instance", ".", "f_contains", "(", "instance", ",", "with_links", "=", "False", ",", "shortcuts", "=", "False", ")", ":", "raise", "ValueError", "(", "'You can only link to items within the trajectory tree!'", ")", "# Check if the name fulfils the prefix conditions, if not change the name accordingly.", "if", "add_prefix", ":", "split_names", "=", "self", ".", "_add_prefix", "(", "split_names", ",", "start_node", ",", "group_type_name", ")", "if", "group_type_name", "==", "GROUP", ":", "add_leaf", "=", "type_name", "!=", "group_type_name", "and", "not", "add_link", "# If this is equal we add a group node", "group_type_name", ",", "type_name", "=", "self", ".", "_determine_types", "(", "start_node", ",", "split_names", "[", "0", "]", ",", "add_leaf", ",", "add_link", ")", "# Check if we are allowed to add the data", "if", "self", ".", "_root_instance", ".", "_is_run", "and", "type_name", "in", "SENSITIVE_TYPES", ":", "raise", "TypeError", "(", "'You are not allowed to add config or parameter data or groups '", "'during a single run.'", ")", "return", "self", ".", "_add_to_tree", "(", "start_node", ",", "split_names", ",", "type_name", ",", "group_type_name", ",", "instance", ",", "constructor", ",", "args", ",", "kwargs", ")" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._replace_wildcards
Replaces the $ wildcards and returns True/False in case it was replaced
pypet/naturalnaming.py
def _replace_wildcards(self, name, run_idx=None): """Replaces the $ wildcards and returns True/False in case it was replaced""" if self._root_instance.f_is_wildcard(name): return True, self._root_instance.f_wildcard(name, run_idx) else: return False, name
def _replace_wildcards(self, name, run_idx=None): """Replaces the $ wildcards and returns True/False in case it was replaced""" if self._root_instance.f_is_wildcard(name): return True, self._root_instance.f_wildcard(name, run_idx) else: return False, name
[ "Replaces", "the", "$", "wildcards", "and", "returns", "True", "/", "False", "in", "case", "it", "was", "replaced" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1232-L1237
[ "def", "_replace_wildcards", "(", "self", ",", "name", ",", "run_idx", "=", "None", ")", ":", "if", "self", ".", "_root_instance", ".", "f_is_wildcard", "(", "name", ")", ":", "return", "True", ",", "self", ".", "_root_instance", ".", "f_wildcard", "(", "name", ",", "run_idx", ")", "else", ":", "return", "False", ",", "name" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._add_to_tree
Adds a new item to the tree. The item can be an already given instance or it is created new. :param start_node: Parental node the adding of the item was initiated from. :param split_names: List of names of the new item :param type_name: Type of item 'RESULT', 'RESULT_GROUP', 'PARAMETER', etc. See name of constants at beginning of the python module. :param group_type_name: Name of the subbranch the item is added to 'RESULT_GROUP', 'PARAMETER_GROUP' etc. See name of constants at beginning of this python module. :param instance: Here an already given instance can be passed. If instance should be created new pass None. :param constructor: If instance should be created new pass a constructor class. If None is passed the standard constructor for the instance is chosen. :param args: Additional arguments passed to instance construction :param kwargs: Additional keyword arguments passed to instance construction :return: The new added instance :raises: ValueError if naming of the new item is invalid
pypet/naturalnaming.py
def _add_to_tree(self, start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs): """Adds a new item to the tree. The item can be an already given instance or it is created new. :param start_node: Parental node the adding of the item was initiated from. :param split_names: List of names of the new item :param type_name: Type of item 'RESULT', 'RESULT_GROUP', 'PARAMETER', etc. See name of constants at beginning of the python module. :param group_type_name: Name of the subbranch the item is added to 'RESULT_GROUP', 'PARAMETER_GROUP' etc. See name of constants at beginning of this python module. :param instance: Here an already given instance can be passed. If instance should be created new pass None. :param constructor: If instance should be created new pass a constructor class. If None is passed the standard constructor for the instance is chosen. :param args: Additional arguments passed to instance construction :param kwargs: Additional keyword arguments passed to instance construction :return: The new added instance :raises: ValueError if naming of the new item is invalid """ # Then walk iteratively from the start node as specified by the new name and create # new empty groups on the fly try: act_node = start_node last_idx = len(split_names) - 1 add_link = type_name == LINK link_added = False # last_name = start_node.v_crun for idx, name in enumerate(split_names): if name not in act_node._children: if idx == last_idx: if add_link: new_node = self._create_link(act_node, name, instance) link_added = True elif group_type_name != type_name: # We are at the end of the chain and we add a leaf node new_node = self._create_any_param_or_result(act_node, name, type_name, instance, constructor, args, kwargs) self._flat_leaf_storage_dict[new_node.v_full_name] = new_node else: # We add a group as desired new_node = self._create_any_group(act_node, name, group_type_name, instance, constructor, args, kwargs) else: # We add a group on the fly new_node = self._create_any_group(act_node, name, group_type_name) if name in self._root_instance._run_information: self._root_instance._run_parent_groups[act_node.v_full_name] = act_node if self._root_instance._is_run: if link_added: self._root_instance._new_links[(act_node.v_full_name, name)] = \ (act_node, new_node) else: self._root_instance._new_nodes[(act_node.v_full_name, name)] = \ (act_node, new_node) else: if name in act_node._links: raise AttributeError('You cannot hop over links when adding ' 'data to the tree. ' 'There is a link called `%s` under `%s`.' % (name, act_node.v_full_name)) if idx == last_idx: if self._root_instance._no_clobber: self._logger.warning('You already have a group/instance/link `%s` ' 'under `%s`. ' 'However, you set `v_no_clobber=True`, ' 'so I will ignore your addition of ' 'data.' % (name, act_node.v_full_name)) else: raise AttributeError('You already have a group/instance/link `%s` ' 'under `%s`' % (name, act_node.v_full_name)) act_node = act_node._children[name] return act_node except: self._logger.error('Failed adding `%s` under `%s`.' % (name, start_node.v_full_name)) raise
def _add_to_tree(self, start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs): """Adds a new item to the tree. The item can be an already given instance or it is created new. :param start_node: Parental node the adding of the item was initiated from. :param split_names: List of names of the new item :param type_name: Type of item 'RESULT', 'RESULT_GROUP', 'PARAMETER', etc. See name of constants at beginning of the python module. :param group_type_name: Name of the subbranch the item is added to 'RESULT_GROUP', 'PARAMETER_GROUP' etc. See name of constants at beginning of this python module. :param instance: Here an already given instance can be passed. If instance should be created new pass None. :param constructor: If instance should be created new pass a constructor class. If None is passed the standard constructor for the instance is chosen. :param args: Additional arguments passed to instance construction :param kwargs: Additional keyword arguments passed to instance construction :return: The new added instance :raises: ValueError if naming of the new item is invalid """ # Then walk iteratively from the start node as specified by the new name and create # new empty groups on the fly try: act_node = start_node last_idx = len(split_names) - 1 add_link = type_name == LINK link_added = False # last_name = start_node.v_crun for idx, name in enumerate(split_names): if name not in act_node._children: if idx == last_idx: if add_link: new_node = self._create_link(act_node, name, instance) link_added = True elif group_type_name != type_name: # We are at the end of the chain and we add a leaf node new_node = self._create_any_param_or_result(act_node, name, type_name, instance, constructor, args, kwargs) self._flat_leaf_storage_dict[new_node.v_full_name] = new_node else: # We add a group as desired new_node = self._create_any_group(act_node, name, group_type_name, instance, constructor, args, kwargs) else: # We add a group on the fly new_node = self._create_any_group(act_node, name, group_type_name) if name in self._root_instance._run_information: self._root_instance._run_parent_groups[act_node.v_full_name] = act_node if self._root_instance._is_run: if link_added: self._root_instance._new_links[(act_node.v_full_name, name)] = \ (act_node, new_node) else: self._root_instance._new_nodes[(act_node.v_full_name, name)] = \ (act_node, new_node) else: if name in act_node._links: raise AttributeError('You cannot hop over links when adding ' 'data to the tree. ' 'There is a link called `%s` under `%s`.' % (name, act_node.v_full_name)) if idx == last_idx: if self._root_instance._no_clobber: self._logger.warning('You already have a group/instance/link `%s` ' 'under `%s`. ' 'However, you set `v_no_clobber=True`, ' 'so I will ignore your addition of ' 'data.' % (name, act_node.v_full_name)) else: raise AttributeError('You already have a group/instance/link `%s` ' 'under `%s`' % (name, act_node.v_full_name)) act_node = act_node._children[name] return act_node except: self._logger.error('Failed adding `%s` under `%s`.' % (name, start_node.v_full_name)) raise
[ "Adds", "a", "new", "item", "to", "the", "tree", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1261-L1377
[ "def", "_add_to_tree", "(", "self", ",", "start_node", ",", "split_names", ",", "type_name", ",", "group_type_name", ",", "instance", ",", "constructor", ",", "args", ",", "kwargs", ")", ":", "# Then walk iteratively from the start node as specified by the new name and create", "# new empty groups on the fly", "try", ":", "act_node", "=", "start_node", "last_idx", "=", "len", "(", "split_names", ")", "-", "1", "add_link", "=", "type_name", "==", "LINK", "link_added", "=", "False", "# last_name = start_node.v_crun", "for", "idx", ",", "name", "in", "enumerate", "(", "split_names", ")", ":", "if", "name", "not", "in", "act_node", ".", "_children", ":", "if", "idx", "==", "last_idx", ":", "if", "add_link", ":", "new_node", "=", "self", ".", "_create_link", "(", "act_node", ",", "name", ",", "instance", ")", "link_added", "=", "True", "elif", "group_type_name", "!=", "type_name", ":", "# We are at the end of the chain and we add a leaf node", "new_node", "=", "self", ".", "_create_any_param_or_result", "(", "act_node", ",", "name", ",", "type_name", ",", "instance", ",", "constructor", ",", "args", ",", "kwargs", ")", "self", ".", "_flat_leaf_storage_dict", "[", "new_node", ".", "v_full_name", "]", "=", "new_node", "else", ":", "# We add a group as desired", "new_node", "=", "self", ".", "_create_any_group", "(", "act_node", ",", "name", ",", "group_type_name", ",", "instance", ",", "constructor", ",", "args", ",", "kwargs", ")", "else", ":", "# We add a group on the fly", "new_node", "=", "self", ".", "_create_any_group", "(", "act_node", ",", "name", ",", "group_type_name", ")", "if", "name", "in", "self", ".", "_root_instance", ".", "_run_information", ":", "self", ".", "_root_instance", ".", "_run_parent_groups", "[", "act_node", ".", "v_full_name", "]", "=", "act_node", "if", "self", ".", "_root_instance", ".", "_is_run", ":", "if", "link_added", ":", "self", ".", "_root_instance", ".", "_new_links", "[", "(", "act_node", ".", "v_full_name", ",", "name", ")", "]", "=", "(", "act_node", ",", "new_node", ")", "else", ":", "self", ".", "_root_instance", ".", "_new_nodes", "[", "(", "act_node", ".", "v_full_name", ",", "name", ")", "]", "=", "(", "act_node", ",", "new_node", ")", "else", ":", "if", "name", "in", "act_node", ".", "_links", ":", "raise", "AttributeError", "(", "'You cannot hop over links when adding '", "'data to the tree. '", "'There is a link called `%s` under `%s`.'", "%", "(", "name", ",", "act_node", ".", "v_full_name", ")", ")", "if", "idx", "==", "last_idx", ":", "if", "self", ".", "_root_instance", ".", "_no_clobber", ":", "self", ".", "_logger", ".", "warning", "(", "'You already have a group/instance/link `%s` '", "'under `%s`. '", "'However, you set `v_no_clobber=True`, '", "'so I will ignore your addition of '", "'data.'", "%", "(", "name", ",", "act_node", ".", "v_full_name", ")", ")", "else", ":", "raise", "AttributeError", "(", "'You already have a group/instance/link `%s` '", "'under `%s`'", "%", "(", "name", ",", "act_node", ".", "v_full_name", ")", ")", "act_node", "=", "act_node", ".", "_children", "[", "name", "]", "return", "act_node", "except", ":", "self", ".", "_logger", ".", "error", "(", "'Failed adding `%s` under `%s`.'", "%", "(", "name", ",", "start_node", ".", "v_full_name", ")", ")", "raise" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._create_link
Creates a link and checks if names are appropriate
pypet/naturalnaming.py
def _create_link(self, act_node, name, instance): """Creates a link and checks if names are appropriate """ act_node._links[name] = instance act_node._children[name] = instance full_name = instance.v_full_name if full_name not in self._root_instance._linked_by: self._root_instance._linked_by[full_name] = {} linking = self._root_instance._linked_by[full_name] if act_node.v_full_name not in linking: linking[act_node.v_full_name] = (act_node, set()) linking[act_node.v_full_name][1].add(name) if name not in self._links_count: self._links_count[name] = 0 self._links_count[name] = self._links_count[name] + 1 self._logger.debug('Added link `%s` under `%s` pointing ' 'to `%s`.' % (name, act_node.v_full_name, instance.v_full_name)) return instance
def _create_link(self, act_node, name, instance): """Creates a link and checks if names are appropriate """ act_node._links[name] = instance act_node._children[name] = instance full_name = instance.v_full_name if full_name not in self._root_instance._linked_by: self._root_instance._linked_by[full_name] = {} linking = self._root_instance._linked_by[full_name] if act_node.v_full_name not in linking: linking[act_node.v_full_name] = (act_node, set()) linking[act_node.v_full_name][1].add(name) if name not in self._links_count: self._links_count[name] = 0 self._links_count[name] = self._links_count[name] + 1 self._logger.debug('Added link `%s` under `%s` pointing ' 'to `%s`.' % (name, act_node.v_full_name, instance.v_full_name)) return instance
[ "Creates", "a", "link", "and", "checks", "if", "names", "are", "appropriate" ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1398-L1420
[ "def", "_create_link", "(", "self", ",", "act_node", ",", "name", ",", "instance", ")", ":", "act_node", ".", "_links", "[", "name", "]", "=", "instance", "act_node", ".", "_children", "[", "name", "]", "=", "instance", "full_name", "=", "instance", ".", "v_full_name", "if", "full_name", "not", "in", "self", ".", "_root_instance", ".", "_linked_by", ":", "self", ".", "_root_instance", ".", "_linked_by", "[", "full_name", "]", "=", "{", "}", "linking", "=", "self", ".", "_root_instance", ".", "_linked_by", "[", "full_name", "]", "if", "act_node", ".", "v_full_name", "not", "in", "linking", ":", "linking", "[", "act_node", ".", "v_full_name", "]", "=", "(", "act_node", ",", "set", "(", ")", ")", "linking", "[", "act_node", ".", "v_full_name", "]", "[", "1", "]", ".", "add", "(", "name", ")", "if", "name", "not", "in", "self", ".", "_links_count", ":", "self", ".", "_links_count", "[", "name", "]", "=", "0", "self", ".", "_links_count", "[", "name", "]", "=", "self", ".", "_links_count", "[", "name", "]", "+", "1", "self", ".", "_logger", ".", "debug", "(", "'Added link `%s` under `%s` pointing '", "'to `%s`.'", "%", "(", "name", ",", "act_node", ".", "v_full_name", ",", "instance", ".", "v_full_name", ")", ")", "return", "instance" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._check_names
Checks if a list contains strings with invalid names. Returns a description of the name violations. If names are correct the empty string is returned. :param split_names: List of strings :param parent_node: The parental node from where to start (only applicable for node names)
pypet/naturalnaming.py
def _check_names(self, split_names, parent_node=None): """Checks if a list contains strings with invalid names. Returns a description of the name violations. If names are correct the empty string is returned. :param split_names: List of strings :param parent_node: The parental node from where to start (only applicable for node names) """ faulty_names = '' if parent_node is not None and parent_node.v_is_root and split_names[0] == 'overview': faulty_names = '%s `overview` cannot be added directly under the root node ' \ 'this is a reserved keyword,' % (faulty_names) for split_name in split_names: if len(split_name) == 0: faulty_names = '%s `%s` contains no characters, please use at least 1,' % ( faulty_names, split_name) elif split_name.startswith('_'): faulty_names = '%s `%s` starts with a leading underscore,' % ( faulty_names, split_name) elif re.match(CHECK_REGEXP, split_name) is None: faulty_names = '%s `%s` contains non-admissible characters ' \ '(use only [A-Za-z0-9_-]),' % \ (faulty_names, split_name) elif '$' in split_name: if split_name not in self._root_instance._wildcard_keys: faulty_names = '%s `%s` contains `$` but has no associated ' \ 'wildcard function,' % (faulty_names, split_name) elif split_name in self._not_admissible_names: warnings.warn('`%s` is a method/attribute of the ' 'trajectory/treenode/naminginterface, you may not be ' 'able to access it via natural naming but only by using ' '`[]` square bracket notation. ' % split_name, category=SyntaxWarning) elif split_name in self._python_keywords: warnings.warn('`%s` is a python keyword, you may not be ' 'able to access it via natural naming but only by using ' '`[]` square bracket notation. ' % split_name, category=SyntaxWarning) name = split_names[-1] if len(name) >= pypetconstants.HDF5_STRCOL_MAX_NAME_LENGTH: faulty_names = '%s `%s` is too long the name can only have %d characters but it has ' \ '%d,' % \ (faulty_names, name, len(name), pypetconstants.HDF5_STRCOL_MAX_NAME_LENGTH) return faulty_names
def _check_names(self, split_names, parent_node=None): """Checks if a list contains strings with invalid names. Returns a description of the name violations. If names are correct the empty string is returned. :param split_names: List of strings :param parent_node: The parental node from where to start (only applicable for node names) """ faulty_names = '' if parent_node is not None and parent_node.v_is_root and split_names[0] == 'overview': faulty_names = '%s `overview` cannot be added directly under the root node ' \ 'this is a reserved keyword,' % (faulty_names) for split_name in split_names: if len(split_name) == 0: faulty_names = '%s `%s` contains no characters, please use at least 1,' % ( faulty_names, split_name) elif split_name.startswith('_'): faulty_names = '%s `%s` starts with a leading underscore,' % ( faulty_names, split_name) elif re.match(CHECK_REGEXP, split_name) is None: faulty_names = '%s `%s` contains non-admissible characters ' \ '(use only [A-Za-z0-9_-]),' % \ (faulty_names, split_name) elif '$' in split_name: if split_name not in self._root_instance._wildcard_keys: faulty_names = '%s `%s` contains `$` but has no associated ' \ 'wildcard function,' % (faulty_names, split_name) elif split_name in self._not_admissible_names: warnings.warn('`%s` is a method/attribute of the ' 'trajectory/treenode/naminginterface, you may not be ' 'able to access it via natural naming but only by using ' '`[]` square bracket notation. ' % split_name, category=SyntaxWarning) elif split_name in self._python_keywords: warnings.warn('`%s` is a python keyword, you may not be ' 'able to access it via natural naming but only by using ' '`[]` square bracket notation. ' % split_name, category=SyntaxWarning) name = split_names[-1] if len(name) >= pypetconstants.HDF5_STRCOL_MAX_NAME_LENGTH: faulty_names = '%s `%s` is too long the name can only have %d characters but it has ' \ '%d,' % \ (faulty_names, name, len(name), pypetconstants.HDF5_STRCOL_MAX_NAME_LENGTH) return faulty_names
[ "Checks", "if", "a", "list", "contains", "strings", "with", "invalid", "names", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1422-L1482
[ "def", "_check_names", "(", "self", ",", "split_names", ",", "parent_node", "=", "None", ")", ":", "faulty_names", "=", "''", "if", "parent_node", "is", "not", "None", "and", "parent_node", ".", "v_is_root", "and", "split_names", "[", "0", "]", "==", "'overview'", ":", "faulty_names", "=", "'%s `overview` cannot be added directly under the root node '", "'this is a reserved keyword,'", "%", "(", "faulty_names", ")", "for", "split_name", "in", "split_names", ":", "if", "len", "(", "split_name", ")", "==", "0", ":", "faulty_names", "=", "'%s `%s` contains no characters, please use at least 1,'", "%", "(", "faulty_names", ",", "split_name", ")", "elif", "split_name", ".", "startswith", "(", "'_'", ")", ":", "faulty_names", "=", "'%s `%s` starts with a leading underscore,'", "%", "(", "faulty_names", ",", "split_name", ")", "elif", "re", ".", "match", "(", "CHECK_REGEXP", ",", "split_name", ")", "is", "None", ":", "faulty_names", "=", "'%s `%s` contains non-admissible characters '", "'(use only [A-Za-z0-9_-]),'", "%", "(", "faulty_names", ",", "split_name", ")", "elif", "'$'", "in", "split_name", ":", "if", "split_name", "not", "in", "self", ".", "_root_instance", ".", "_wildcard_keys", ":", "faulty_names", "=", "'%s `%s` contains `$` but has no associated '", "'wildcard function,'", "%", "(", "faulty_names", ",", "split_name", ")", "elif", "split_name", "in", "self", ".", "_not_admissible_names", ":", "warnings", ".", "warn", "(", "'`%s` is a method/attribute of the '", "'trajectory/treenode/naminginterface, you may not be '", "'able to access it via natural naming but only by using '", "'`[]` square bracket notation. '", "%", "split_name", ",", "category", "=", "SyntaxWarning", ")", "elif", "split_name", "in", "self", ".", "_python_keywords", ":", "warnings", ".", "warn", "(", "'`%s` is a python keyword, you may not be '", "'able to access it via natural naming but only by using '", "'`[]` square bracket notation. '", "%", "split_name", ",", "category", "=", "SyntaxWarning", ")", "name", "=", "split_names", "[", "-", "1", "]", "if", "len", "(", "name", ")", ">=", "pypetconstants", ".", "HDF5_STRCOL_MAX_NAME_LENGTH", ":", "faulty_names", "=", "'%s `%s` is too long the name can only have %d characters but it has '", "'%d,'", "%", "(", "faulty_names", ",", "name", ",", "len", "(", "name", ")", ",", "pypetconstants", ".", "HDF5_STRCOL_MAX_NAME_LENGTH", ")", "return", "faulty_names" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._create_any_group
Generically creates a new group inferring from the `type_name`.
pypet/naturalnaming.py
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None, args=None, kwargs=None): """Generically creates a new group inferring from the `type_name`.""" if args is None: args = [] if kwargs is None: kwargs = {} full_name = self._make_full_name(parent_node.v_full_name, name) if instance is None: if constructor is None: if type_name == RESULT_GROUP: constructor = ResultGroup elif type_name == PARAMETER_GROUP: constructor = ParameterGroup elif type_name == CONFIG_GROUP: constructor = ConfigGroup elif type_name == DERIVED_PARAMETER_GROUP: constructor = DerivedParameterGroup elif type_name == GROUP: constructor = NNGroupNode else: raise RuntimeError('You shall not pass!') instance = self._root_instance._construct_instance(constructor, full_name, *args, **kwargs) else: instance._rename(full_name) # Check if someone tries to add a particular standard group to a branch where # it does not belong: if type_name == RESULT_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under results' % str(type(instance))) elif type_name == PARAMETER_GROUP: if type(instance) in (NNGroupNode, ResultGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under parameters' % str(type(instance))) elif type_name == CONFIG_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ResultGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under config' % str(type(instance))) elif type_name == DERIVED_PARAMETER_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ConfigGroup, ResultGroup): raise TypeError('You cannot add a `%s` type of group under derived ' 'parameters' % str(type(instance))) elif type_name == GROUP: if type(instance) in (ResultGroup, ParameterGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under other data' % str(type(instance))) else: raise RuntimeError('You shall not pass!') self._set_details_tree_node(parent_node, name, instance) instance._nn_interface = self self._root_instance._all_groups[instance.v_full_name] = instance self._add_to_nodes_and_leaves(instance) parent_node._children[name] = instance parent_node._groups[name] = instance return instance
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None, args=None, kwargs=None): """Generically creates a new group inferring from the `type_name`.""" if args is None: args = [] if kwargs is None: kwargs = {} full_name = self._make_full_name(parent_node.v_full_name, name) if instance is None: if constructor is None: if type_name == RESULT_GROUP: constructor = ResultGroup elif type_name == PARAMETER_GROUP: constructor = ParameterGroup elif type_name == CONFIG_GROUP: constructor = ConfigGroup elif type_name == DERIVED_PARAMETER_GROUP: constructor = DerivedParameterGroup elif type_name == GROUP: constructor = NNGroupNode else: raise RuntimeError('You shall not pass!') instance = self._root_instance._construct_instance(constructor, full_name, *args, **kwargs) else: instance._rename(full_name) # Check if someone tries to add a particular standard group to a branch where # it does not belong: if type_name == RESULT_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under results' % str(type(instance))) elif type_name == PARAMETER_GROUP: if type(instance) in (NNGroupNode, ResultGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under parameters' % str(type(instance))) elif type_name == CONFIG_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ResultGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under config' % str(type(instance))) elif type_name == DERIVED_PARAMETER_GROUP: if type(instance) in (NNGroupNode, ParameterGroup, ConfigGroup, ResultGroup): raise TypeError('You cannot add a `%s` type of group under derived ' 'parameters' % str(type(instance))) elif type_name == GROUP: if type(instance) in (ResultGroup, ParameterGroup, ConfigGroup, DerivedParameterGroup): raise TypeError('You cannot add a `%s` type of group under other data' % str(type(instance))) else: raise RuntimeError('You shall not pass!') self._set_details_tree_node(parent_node, name, instance) instance._nn_interface = self self._root_instance._all_groups[instance.v_full_name] = instance self._add_to_nodes_and_leaves(instance) parent_node._children[name] = instance parent_node._groups[name] = instance return instance
[ "Generically", "creates", "a", "new", "group", "inferring", "from", "the", "type_name", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1484-L1561
[ "def", "_create_any_group", "(", "self", ",", "parent_node", ",", "name", ",", "type_name", ",", "instance", "=", "None", ",", "constructor", "=", "None", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "full_name", "=", "self", ".", "_make_full_name", "(", "parent_node", ".", "v_full_name", ",", "name", ")", "if", "instance", "is", "None", ":", "if", "constructor", "is", "None", ":", "if", "type_name", "==", "RESULT_GROUP", ":", "constructor", "=", "ResultGroup", "elif", "type_name", "==", "PARAMETER_GROUP", ":", "constructor", "=", "ParameterGroup", "elif", "type_name", "==", "CONFIG_GROUP", ":", "constructor", "=", "ConfigGroup", "elif", "type_name", "==", "DERIVED_PARAMETER_GROUP", ":", "constructor", "=", "DerivedParameterGroup", "elif", "type_name", "==", "GROUP", ":", "constructor", "=", "NNGroupNode", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")", "instance", "=", "self", ".", "_root_instance", ".", "_construct_instance", "(", "constructor", ",", "full_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "instance", ".", "_rename", "(", "full_name", ")", "# Check if someone tries to add a particular standard group to a branch where", "# it does not belong:", "if", "type_name", "==", "RESULT_GROUP", ":", "if", "type", "(", "instance", ")", "in", "(", "NNGroupNode", ",", "ParameterGroup", ",", "ConfigGroup", ",", "DerivedParameterGroup", ")", ":", "raise", "TypeError", "(", "'You cannot add a `%s` type of group under results'", "%", "str", "(", "type", "(", "instance", ")", ")", ")", "elif", "type_name", "==", "PARAMETER_GROUP", ":", "if", "type", "(", "instance", ")", "in", "(", "NNGroupNode", ",", "ResultGroup", ",", "ConfigGroup", ",", "DerivedParameterGroup", ")", ":", "raise", "TypeError", "(", "'You cannot add a `%s` type of group under parameters'", "%", "str", "(", "type", "(", "instance", ")", ")", ")", "elif", "type_name", "==", "CONFIG_GROUP", ":", "if", "type", "(", "instance", ")", "in", "(", "NNGroupNode", ",", "ParameterGroup", ",", "ResultGroup", ",", "DerivedParameterGroup", ")", ":", "raise", "TypeError", "(", "'You cannot add a `%s` type of group under config'", "%", "str", "(", "type", "(", "instance", ")", ")", ")", "elif", "type_name", "==", "DERIVED_PARAMETER_GROUP", ":", "if", "type", "(", "instance", ")", "in", "(", "NNGroupNode", ",", "ParameterGroup", ",", "ConfigGroup", ",", "ResultGroup", ")", ":", "raise", "TypeError", "(", "'You cannot add a `%s` type of group under derived '", "'parameters'", "%", "str", "(", "type", "(", "instance", ")", ")", ")", "elif", "type_name", "==", "GROUP", ":", "if", "type", "(", "instance", ")", "in", "(", "ResultGroup", ",", "ParameterGroup", ",", "ConfigGroup", ",", "DerivedParameterGroup", ")", ":", "raise", "TypeError", "(", "'You cannot add a `%s` type of group under other data'", "%", "str", "(", "type", "(", "instance", ")", ")", ")", "else", ":", "raise", "RuntimeError", "(", "'You shall not pass!'", ")", "self", ".", "_set_details_tree_node", "(", "parent_node", ",", "name", ",", "instance", ")", "instance", ".", "_nn_interface", "=", "self", "self", ".", "_root_instance", ".", "_all_groups", "[", "instance", ".", "v_full_name", "]", "=", "instance", "self", ".", "_add_to_nodes_and_leaves", "(", "instance", ")", "parent_node", ".", "_children", "[", "name", "]", "=", "instance", "parent_node", ".", "_groups", "[", "name", "]", "=", "instance", "return", "instance" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826
test
NaturalNamingInterface._create_any_param_or_result
Generically creates a novel parameter or result instance inferring from the `type_name`. If the instance is already supplied it is NOT constructed new. :param parent_node: Parent trajectory node :param name: Name of the new result or parameter. Here the name no longer contains colons. :param type_name: Whether it is a parameter below parameters, config, derived parameters or whether it is a result. :param instance: The instance if it has been constructed somewhere else, otherwise None. :param constructor: A constructor used if instance needs to be constructed. If None the current standard constructor is chosen. :param args: Additional arguments passed to the constructor :param kwargs: Additional keyword arguments passed to the constructor :return: The new instance
pypet/naturalnaming.py
def _create_any_param_or_result(self, parent_node, name, type_name, instance, constructor, args, kwargs): """Generically creates a novel parameter or result instance inferring from the `type_name`. If the instance is already supplied it is NOT constructed new. :param parent_node: Parent trajectory node :param name: Name of the new result or parameter. Here the name no longer contains colons. :param type_name: Whether it is a parameter below parameters, config, derived parameters or whether it is a result. :param instance: The instance if it has been constructed somewhere else, otherwise None. :param constructor: A constructor used if instance needs to be constructed. If None the current standard constructor is chosen. :param args: Additional arguments passed to the constructor :param kwargs: Additional keyword arguments passed to the constructor :return: The new instance """ root = self._root_instance full_name = self._make_full_name(parent_node.v_full_name, name) if instance is None: if constructor is None: if type_name == RESULT: constructor = root._standard_result elif type_name in [PARAMETER, CONFIG, DERIVED_PARAMETER]: constructor = root._standard_parameter else: constructor = root._standard_leaf instance = root._construct_instance(constructor, full_name, *args, **kwargs) else: instance._rename(full_name) self._set_details_tree_node(parent_node, name, instance) where_dict = self._map_type_to_dict(type_name) full_name = instance._full_name if full_name in where_dict: raise AttributeError(full_name + ' is already part of trajectory,') if type_name != RESULT and full_name in root._changed_default_parameters: self._logger.info( 'You have marked parameter %s for change before, so here you go!' % full_name) change_args, change_kwargs = root._changed_default_parameters.pop(full_name) instance.f_set(*change_args, **change_kwargs) where_dict[full_name] = instance self._add_to_nodes_and_leaves(instance) parent_node._children[name] = instance parent_node._leaves[name] = instance if full_name in self._root_instance._explored_parameters: instance._explored = True # Mark this parameter as explored. self._root_instance._explored_parameters[full_name] = instance self._logger.debug('Added `%s` to trajectory.' % full_name) return instance
def _create_any_param_or_result(self, parent_node, name, type_name, instance, constructor, args, kwargs): """Generically creates a novel parameter or result instance inferring from the `type_name`. If the instance is already supplied it is NOT constructed new. :param parent_node: Parent trajectory node :param name: Name of the new result or parameter. Here the name no longer contains colons. :param type_name: Whether it is a parameter below parameters, config, derived parameters or whether it is a result. :param instance: The instance if it has been constructed somewhere else, otherwise None. :param constructor: A constructor used if instance needs to be constructed. If None the current standard constructor is chosen. :param args: Additional arguments passed to the constructor :param kwargs: Additional keyword arguments passed to the constructor :return: The new instance """ root = self._root_instance full_name = self._make_full_name(parent_node.v_full_name, name) if instance is None: if constructor is None: if type_name == RESULT: constructor = root._standard_result elif type_name in [PARAMETER, CONFIG, DERIVED_PARAMETER]: constructor = root._standard_parameter else: constructor = root._standard_leaf instance = root._construct_instance(constructor, full_name, *args, **kwargs) else: instance._rename(full_name) self._set_details_tree_node(parent_node, name, instance) where_dict = self._map_type_to_dict(type_name) full_name = instance._full_name if full_name in where_dict: raise AttributeError(full_name + ' is already part of trajectory,') if type_name != RESULT and full_name in root._changed_default_parameters: self._logger.info( 'You have marked parameter %s for change before, so here you go!' % full_name) change_args, change_kwargs = root._changed_default_parameters.pop(full_name) instance.f_set(*change_args, **change_kwargs) where_dict[full_name] = instance self._add_to_nodes_and_leaves(instance) parent_node._children[name] = instance parent_node._leaves[name] = instance if full_name in self._root_instance._explored_parameters: instance._explored = True # Mark this parameter as explored. self._root_instance._explored_parameters[full_name] = instance self._logger.debug('Added `%s` to trajectory.' % full_name) return instance
[ "Generically", "creates", "a", "novel", "parameter", "or", "result", "instance", "inferring", "from", "the", "type_name", "." ]
SmokinCaterpillar/pypet
python
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L1563-L1643
[ "def", "_create_any_param_or_result", "(", "self", ",", "parent_node", ",", "name", ",", "type_name", ",", "instance", ",", "constructor", ",", "args", ",", "kwargs", ")", ":", "root", "=", "self", ".", "_root_instance", "full_name", "=", "self", ".", "_make_full_name", "(", "parent_node", ".", "v_full_name", ",", "name", ")", "if", "instance", "is", "None", ":", "if", "constructor", "is", "None", ":", "if", "type_name", "==", "RESULT", ":", "constructor", "=", "root", ".", "_standard_result", "elif", "type_name", "in", "[", "PARAMETER", ",", "CONFIG", ",", "DERIVED_PARAMETER", "]", ":", "constructor", "=", "root", ".", "_standard_parameter", "else", ":", "constructor", "=", "root", ".", "_standard_leaf", "instance", "=", "root", ".", "_construct_instance", "(", "constructor", ",", "full_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "instance", ".", "_rename", "(", "full_name", ")", "self", ".", "_set_details_tree_node", "(", "parent_node", ",", "name", ",", "instance", ")", "where_dict", "=", "self", ".", "_map_type_to_dict", "(", "type_name", ")", "full_name", "=", "instance", ".", "_full_name", "if", "full_name", "in", "where_dict", ":", "raise", "AttributeError", "(", "full_name", "+", "' is already part of trajectory,'", ")", "if", "type_name", "!=", "RESULT", "and", "full_name", "in", "root", ".", "_changed_default_parameters", ":", "self", ".", "_logger", ".", "info", "(", "'You have marked parameter %s for change before, so here you go!'", "%", "full_name", ")", "change_args", ",", "change_kwargs", "=", "root", ".", "_changed_default_parameters", ".", "pop", "(", "full_name", ")", "instance", ".", "f_set", "(", "*", "change_args", ",", "*", "*", "change_kwargs", ")", "where_dict", "[", "full_name", "]", "=", "instance", "self", ".", "_add_to_nodes_and_leaves", "(", "instance", ")", "parent_node", ".", "_children", "[", "name", "]", "=", "instance", "parent_node", ".", "_leaves", "[", "name", "]", "=", "instance", "if", "full_name", "in", "self", ".", "_root_instance", ".", "_explored_parameters", ":", "instance", ".", "_explored", "=", "True", "# Mark this parameter as explored.", "self", ".", "_root_instance", ".", "_explored_parameters", "[", "full_name", "]", "=", "instance", "self", ".", "_logger", ".", "debug", "(", "'Added `%s` to trajectory.'", "%", "full_name", ")", "return", "instance" ]
97ad3e80d46dbdea02deeb98ea41f05a19565826