diff --git "a/oracle_context_cache_v3/IDSIA__sacred.json" "b/oracle_context_cache_v3/IDSIA__sacred.json" new file mode 100644--- /dev/null +++ "b/oracle_context_cache_v3/IDSIA__sacred.json" @@ -0,0 +1 @@ +{"repo": "IDSIA/sacred", "n_pairs": 200, "version": "v3_compressed", "max_tokens": 6000, "contexts": {"tests/test_commands.py::157": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["ConfigSummary", "_format_config"], "enclosing_function": "test_format_config", "extracted_code": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 2471, "extracted_code_full": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_chars_compressed": 2471, "compression_ratio": 1.0}, "tests/test_serializer.py::54": {"resolved_imports": ["sacred/serializer.py", "sacred/optional.py"], "used_names": ["flatten", "pytest", "restore"], "enclosing_function": "test_serialize_numpy_arrays", "extracted_code": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 193, "extracted_code_full": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_chars_compressed": 193, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::140": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict", "DogmaticList"], "enclosing_function": "test_nested_dict_revelation", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing\n\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4472, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing\n\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 4472, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::33": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_config_dict_result_contains_keys", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_modules.py::16": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["ConfigScope", "Ingredient"], "enclosing_function": "test_ingredient_config", "extracted_code": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary\n\n\n# Source: sacred/experiment.py\nfrom sacred.observers.s3_observer import s3_option\nfrom sacred.config.signature import Signature\nfrom sacred.ingredient import Ingredient\nfrom sacred.initialize import create_run\nfrom sacred.observers.sql import sql_option\nfrom sacred.observers.tinydb_hashfs import tiny_db_option\nfrom sacred.run import Run\nfrom sacred.host_info import check_additional_host_info, HostInfoGetter\nfrom sacred.utils import (\n print_filtered_stacktrace,\n ensure_wellformed_argv,\n SacredError,\n\n\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n\n(Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 4794, "extracted_code_full": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary\n\n\n# Source: sacred/experiment.py\nfrom sacred.observers.s3_observer import s3_option\nfrom sacred.config.signature import Signature\nfrom sacred.ingredient import Ingredient\nfrom sacred.initialize import create_run\nfrom sacred.observers.sql import sql_option\nfrom sacred.observers.tinydb_hashfs import tiny_db_option\nfrom sacred.run import Run\nfrom sacred.host_info import check_additional_host_info, HostInfoGetter\nfrom sacred.utils import (\n print_filtered_stacktrace,\n ensure_wellformed_argv,\n SacredError,\n\n\n\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir", "n_chars_compressed": 4781, "compression_ratio": 0.9972882770129329}, "tests/test_config/test_readonly_containers.py::89": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["ReadOnlyList", "SacredError", "pytest"], "enclosing_function": "_check_read_only_list", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass ReadOnlyList(ReadOnlyContainer, list):\n \"\"\"A read-only variant of a `list`.\"\"\"\n\n append = ReadOnlyContainer._readonly\n clear = ReadOnlyContainer._readonly\n extend = ReadOnlyContainer._readonly\n insert = ReadOnlyContainer._readonly\n pop = ReadOnlyContainer._readonly\n remove = ReadOnlyContainer._readonly\n reverse = ReadOnlyContainer._readonly\n sort = ReadOnlyContainer._readonly\n __setitem__ = ReadOnlyContainer._readonly\n __delitem__ = ReadOnlyContainer._readonly\n\n def __copy__(self):\n return [*self]\n\n def __deepcopy__(self, memo):\n lst = list(self)\n return copy.deepcopy(lst, memo=memo)\n\n\n# Source: sacred/utils.py\nclass SacredError(Exception):\n def __init__(\n self,\n message,\n print_traceback=True,\n filter_traceback=\"default\",\n print_usage=False,\n ):\n super().__init__(message)\n self.print_traceback = print_traceback\n if filter_traceback not in [\"always\", \"default\", \"never\"]:\n raise ValueError(\n \"filter_traceback must be one of 'always', \"\n \"'default' or 'never', not \" + filter_traceback\n )\n self.filter_traceback = filter_traceback\n self.print_usage = print_usage", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 1313, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass ReadOnlyList(ReadOnlyContainer, list):\n \"\"\"A read-only variant of a `list`.\"\"\"\n\n append = ReadOnlyContainer._readonly\n clear = ReadOnlyContainer._readonly\n extend = ReadOnlyContainer._readonly\n insert = ReadOnlyContainer._readonly\n pop = ReadOnlyContainer._readonly\n remove = ReadOnlyContainer._readonly\n reverse = ReadOnlyContainer._readonly\n sort = ReadOnlyContainer._readonly\n __setitem__ = ReadOnlyContainer._readonly\n __delitem__ = ReadOnlyContainer._readonly\n\n def __copy__(self):\n return [*self]\n\n def __deepcopy__(self, memo):\n lst = list(self)\n return copy.deepcopy(lst, memo=memo)\n\n\n# Source: sacred/utils.py\nclass SacredError(Exception):\n def __init__(\n self,\n message,\n print_traceback=True,\n filter_traceback=\"default\",\n print_usage=False,\n ):\n super().__init__(message)\n self.print_traceback = print_traceback\n if filter_traceback not in [\"always\", \"default\", \"never\"]:\n raise ValueError(\n \"filter_traceback must be one of 'always', \"\n \"'default' or 'never', not \" + filter_traceback\n )\n self.filter_traceback = filter_traceback\n self.print_usage = print_usage", "n_chars_compressed": 1313, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::128": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock"], "enclosing_function": "test_captured_function_call_doesnt_modify_kwargs", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_arg_parser.py::76": {"resolved_imports": ["sacred/arg_parser.py", "sacred/experiment.py"], "used_names": ["get_config_updates", "pytest"], "enclosing_function": "test_get_config_updates", "extracted_code": "# Source: sacred/arg_parser.py\ndef get_config_updates(updates):\n \"\"\"\n Parse the UPDATES given on the commandline.\n\n Parameters\n ----------\n updates (list[str]):\n list of update-strings of the form NAME=LITERAL or just NAME.\n\n Returns\n -------\n (dict, list):\n Config updates and named configs to use\n\n \"\"\"\n config_updates = {}\n named_configs = []\n if not updates:\n return config_updates, named_configs\n for upd in updates:\n if upd == \"\":\n continue\n path, sep, value = upd.partition(\"=\")\n if sep == \"=\":\n path = path.strip() # get rid of surrounding whitespace\n value = value.strip() # get rid of surrounding whitespace\n set_by_dotted_path(config_updates, path, _convert_value(value))\n else:\n named_configs.append(path)\n return config_updates, named_configs", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 919, "extracted_code_full": "# Source: sacred/arg_parser.py\ndef get_config_updates(updates):\n \"\"\"\n Parse the UPDATES given on the commandline.\n\n Parameters\n ----------\n updates (list[str]):\n list of update-strings of the form NAME=LITERAL or just NAME.\n\n Returns\n -------\n (dict, list):\n Config updates and named configs to use\n\n \"\"\"\n config_updates = {}\n named_configs = []\n if not updates:\n return config_updates, named_configs\n for upd in updates:\n if upd == \"\":\n continue\n path, sep, value = upd.partition(\"=\")\n if sep == \"=\":\n path = path.strip() # get rid of surrounding whitespace\n value = value.strip() # get rid of surrounding whitespace\n set_by_dotted_path(config_updates, path, _convert_value(value))\n else:\n named_configs.append(path)\n return config_updates, named_configs", "n_chars_compressed": 919, "compression_ratio": 1.0}, "tests/test_stflow/test_internal.py::30": {"resolved_imports": ["sacred/stflow/internal.py"], "used_names": ["ContextMethodDecorator"], "enclosing_function": "test_context_method_decorator", "extracted_code": "# Source: sacred/stflow/internal.py\nclass ContextMethodDecorator:\n \"\"\"A helper ContextManager decorating a method with a custom function.\"\"\"\n\n def __init__(self, classx, method_name, decorator_func):\n \"\"\"\n Create a new context manager decorating a function within its scope.\n\n This is a helper Context Manager that decorates a method of a class\n with a custom function.\n The decoration is only valid within the scope.\n :param classx: A class (object)\n :param method_name A string name of the method to be decorated\n :param decorator_func: The decorator function is responsible\n for calling the original method.\n The signature should be: func(instance, original_method,\n original_args, original_kwargs)\n when called, instance refers to an instance of classx and the\n original_method refers to the original method object which can be\n called.\n args and kwargs are arguments passed to the method\n\n \"\"\"\n self.method_name = method_name\n self.decorator_func = decorator_func\n self.classx = classx\n self.patched_by_me = False\n\n def __enter__(self):\n\n self.original_method = getattr(self.classx, self.method_name)\n if not hasattr(\n self.original_method, \"sacred_patched%s\" % self.__class__.__name__\n ):\n\n @functools.wraps(self.original_method)\n def decorated(instance, *args, **kwargs):\n return self.decorator_func(instance, self.original_method, args, kwargs)\n\n setattr(self.classx, self.method_name, decorated)\n setattr(decorated, \"sacred_patched%s\" % self.__class__.__name__, True)\n self.patched_by_me = True\n\n def __exit__(self, type, value, traceback):\n if self.patched_by_me:\n # Restore original function\n setattr(self.classx, self.method_name, self.original_method)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1954, "extracted_code_full": "# Source: sacred/stflow/internal.py\nclass ContextMethodDecorator:\n \"\"\"A helper ContextManager decorating a method with a custom function.\"\"\"\n\n def __init__(self, classx, method_name, decorator_func):\n \"\"\"\n Create a new context manager decorating a function within its scope.\n\n This is a helper Context Manager that decorates a method of a class\n with a custom function.\n The decoration is only valid within the scope.\n :param classx: A class (object)\n :param method_name A string name of the method to be decorated\n :param decorator_func: The decorator function is responsible\n for calling the original method.\n The signature should be: func(instance, original_method,\n original_args, original_kwargs)\n when called, instance refers to an instance of classx and the\n original_method refers to the original method object which can be\n called.\n args and kwargs are arguments passed to the method\n\n \"\"\"\n self.method_name = method_name\n self.decorator_func = decorator_func\n self.classx = classx\n self.patched_by_me = False\n\n def __enter__(self):\n\n self.original_method = getattr(self.classx, self.method_name)\n if not hasattr(\n self.original_method, \"sacred_patched%s\" % self.__class__.__name__\n ):\n\n @functools.wraps(self.original_method)\n def decorated(instance, *args, **kwargs):\n return self.decorator_func(instance, self.original_method, args, kwargs)\n\n setattr(self.classx, self.method_name, decorated)\n setattr(decorated, \"sacred_patched%s\" % self.__class__.__name__, True)\n self.patched_by_me = True\n\n def __exit__(self, type, value, traceback):\n if self.patched_by_me:\n # Restore original function\n setattr(self.classx, self.method_name, self.original_method)", "n_chars_compressed": 1954, "compression_ratio": 1.0}, "tests/test_ingredients.py::43": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_capture_function_with_prefix", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_config/test_captured_functions.py::103": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock"], "enclosing_function": "test_captured_function_magic_config_argument", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_observer.py::66": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py", "sacred/observers/tinydb_hashfs/bases.py", "sacred/__init__.py", "sacred/optional.py", "sacred/experiment.py"], "used_names": [], "enclosing_function": "test_tinydb_observer_started_event_creates_run", "extracted_code": "", "n_imports_parsed": 13, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_observers/test_file_storage_observer.py::60": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["datetime", "json"], "enclosing_function": "test_fs_observer_queued_event_creates_rundir", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_config/test_dogmatic_list.py::15": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_init", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_commands.py::156": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["ConfigSummary", "_format_config"], "enclosing_function": "test_format_config", "extracted_code": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 2471, "extracted_code_full": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_chars_compressed": 2471, "compression_ratio": 1.0}, "tests/test_metrics_logger.py::128": {"resolved_imports": ["sacred/__init__.py", "sacred/metrics_logger.py"], "used_names": ["ScalarMetricLogEntry", "datetime", "linearize_metrics"], "enclosing_function": "test_linearize_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\nclass ScalarMetricLogEntry:\n \"\"\"Container for measurements of scalar metrics.\n\n There is exactly one ScalarMetricLogEntry per logged scalar metric value.\n \"\"\"\n\n def __init__(self, name, step, timestamp, value):\n self.name = name\n self.step = step\n self.timestamp = timestamp\n self.value = value\n\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1416, "extracted_code_full": "# Source: sacred/metrics_logger.py\nclass ScalarMetricLogEntry:\n \"\"\"Container for measurements of scalar metrics.\n\n There is exactly one ScalarMetricLogEntry per logged scalar metric value.\n \"\"\"\n\n def __init__(self, name, step, timestamp, value):\n self.name = name\n self.step = step\n self.timestamp = timestamp\n self.value = value\n\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1416, "compression_ratio": 1.0}, "tests/test_config/test_readonly_containers.py::176": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["make_read_only"], "enclosing_function": "test_nested_readonly_containers", "extracted_code": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 588, "extracted_code_full": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_chars_compressed": 588, "compression_ratio": 1.0}, "tests/test_dependencies.py::115": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py"], "used_names": ["PackageDependency", "mock"], "enclosing_function": "test_package_dependency_create_no_version", "extracted_code": "# Source: sacred/dependencies.py\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 1572, "extracted_code_full": "# Source: sacred/dependencies.py\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)", "n_chars_compressed": 1572, "compression_ratio": 1.0}, "tests/test_observers/test_mongo_observer.py::174": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_metrics_logger.py::24": {"resolved_imports": ["sacred/__init__.py", "sacred/metrics_logger.py"], "used_names": [], "enclosing_function": "main_function", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_observers/test_gcs_observer.py::194": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["json"], "enclosing_function": "test_queued_event_updates_run_json", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_serializer.py::60": {"resolved_imports": ["sacred/serializer.py", "sacred/optional.py"], "used_names": ["flatten", "restore"], "enclosing_function": "test_serialize_tuples", "extracted_code": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 193, "extracted_code_full": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_chars_compressed": 193, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::142": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature", "pytest"], "enclosing_function": "test_constructor_extracts_all_arguments", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_utils.py::31": {"resolved_imports": ["sacred/utils.py"], "used_names": ["recursive_update"], "enclosing_function": "test_recursive_update", "extracted_code": "# Source: sacred/utils.py\ndef recursive_update(d, u):\n \"\"\"\n Given two dictionaries d and u, update dict d recursively.\n\n E.g.:\n d = {'a': {'b' : 1}}\n u = {'c': 2, 'a': {'d': 3}}\n => {'a': {'b': 1, 'd': 3}, 'c': 2}\n \"\"\"\n for k, v in u.items():\n if isinstance(v, collections.abc.Mapping):\n r = recursive_update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 439, "extracted_code_full": "# Source: sacred/utils.py\ndef recursive_update(d, u):\n \"\"\"\n Given two dictionaries d and u, update dict d recursively.\n\n E.g.:\n d = {'a': {'b' : 1}}\n u = {'c': 2, 'a': {'d': 3}}\n => {'a': {'b': 1, 'd': 3}, 'c': 2}\n \"\"\"\n for k, v in u.items():\n if isinstance(v, collections.abc.Mapping):\n r = recursive_update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d", "n_chars_compressed": 439, "compression_ratio": 1.0}, "tests/test_metrics_logger.py::134": {"resolved_imports": ["sacred/__init__.py", "sacred/metrics_logger.py"], "used_names": ["ScalarMetricLogEntry", "datetime", "linearize_metrics"], "enclosing_function": "test_linearize_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\nclass ScalarMetricLogEntry:\n \"\"\"Container for measurements of scalar metrics.\n\n There is exactly one ScalarMetricLogEntry per logged scalar metric value.\n \"\"\"\n\n def __init__(self, name, step, timestamp, value):\n self.name = name\n self.step = step\n self.timestamp = timestamp\n self.value = value\n\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1416, "extracted_code_full": "# Source: sacred/metrics_logger.py\nclass ScalarMetricLogEntry:\n \"\"\"Container for measurements of scalar metrics.\n\n There is exactly one ScalarMetricLogEntry per logged scalar metric value.\n \"\"\"\n\n def __init__(self, name, step, timestamp, value):\n self.name = name\n self.step = step\n self.timestamp = timestamp\n self.value = value\n\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1416, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::115": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_utils.py::84": {"resolved_imports": ["sacred/utils.py"], "used_names": ["join_paths"], "enclosing_function": "test_join_paths", "extracted_code": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 172, "extracted_code_full": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_chars_compressed": 172, "compression_ratio": 1.0}, "tests/test_config/test_fallback_dict.py::33": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_get", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_observers/test_tinydb_reader.py::164": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader", "datetime", "get_digest", "pytest"], "enclosing_function": "test_fetch_metadata_function_with_indices", "extracted_code": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6556, "extracted_code_full": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6556, "compression_ratio": 1.0}, "tests/test_observers/test_gcs_observer.py::184": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["json"], "enclosing_function": "test_failed_event_updates_run_json", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_serializer.py::24": {"resolved_imports": ["sacred/serializer.py", "sacred/optional.py"], "used_names": ["flatten", "pytest"], "enclosing_function": "test_flatten_on_json_is_noop", "extracted_code": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 100, "extracted_code_full": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))", "n_chars_compressed": 100, "compression_ratio": 1.0}, "tests/test_experiment.py::126": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_considers_captured_functions_for_fail_on_unused_config", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_observers/test_mongo_option.py::13": {"resolved_imports": ["sacred/observers/mongo.py"], "used_names": ["parse_mongo_db_arg"], "enclosing_function": "test_parse_mongo_db_arg", "extracted_code": "# Source: sacred/observers/mongo.py\ndef parse_mongo_db_arg(mongo_db):\n g = re.match(get_pattern(), mongo_db).groupdict()\n if g is None:\n raise ValueError(\n 'mongo_db argument must have the form \"db_name\" '\n 'or \"host:port[:db_name]\" but was {}'.format(mongo_db)\n )\n\n kwargs = {}\n if g[\"host1\"]:\n kwargs[\"url\"] = \"{}:{}\".format(g[\"host1\"], g[\"port1\"])\n elif g[\"host2\"]:\n kwargs[\"url\"] = \"{}:{}\".format(g[\"host2\"], g[\"port2\"])\n\n if g[\"priority\"] is not None:\n kwargs[\"priority\"] = int(g[\"priority\"])\n\n for p in [\"db_name\", \"collection\", \"overwrite\"]:\n if g[p] is not None:\n kwargs[p] = g[p]\n\n return kwargs", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 703, "extracted_code_full": "# Source: sacred/observers/mongo.py\ndef parse_mongo_db_arg(mongo_db):\n g = re.match(get_pattern(), mongo_db).groupdict()\n if g is None:\n raise ValueError(\n 'mongo_db argument must have the form \"db_name\" '\n 'or \"host:port[:db_name]\" but was {}'.format(mongo_db)\n )\n\n kwargs = {}\n if g[\"host1\"]:\n kwargs[\"url\"] = \"{}:{}\".format(g[\"host1\"], g[\"port1\"])\n elif g[\"host2\"]:\n kwargs[\"url\"] = \"{}:{}\".format(g[\"host2\"], g[\"port2\"])\n\n if g[\"priority\"] is not None:\n kwargs[\"priority\"] = int(g[\"priority\"])\n\n for p in [\"db_name\", \"collection\", \"overwrite\"]:\n if g[p] is not None:\n kwargs[p] = g[p]\n\n return kwargs", "n_chars_compressed": 703, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_reader.py::215": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader"], "enclosing_function": "test_fetch_metadata_function_with_exp_name", "extracted_code": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6248, "extracted_code_full": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6248, "compression_ratio": 1.0}, "tests/test_config/test_fallback_dict.py::18": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_getitem", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config/test_config_scope.py::258": {"resolved_imports": ["sacred/optional.py", "sacred/config/config_scope.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigScope"], "enclosing_function": "test_fixed_subentry_of_preset", "extracted_code": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3021, "extracted_code_full": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary", "n_chars_compressed": 3021, "compression_ratio": 1.0}, "tests/test_observers/test_queue_observer.py::19": {"resolved_imports": ["sacred/observers/queue.py", "sacred/__init__.py"], "used_names": [], "enclosing_function": "test_started_event", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_config/test_captured_functions.py::92": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock"], "enclosing_function": "test_captured_function_magic_logger_argument", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_commands.py::121": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["COLOR_DOC", "ConfigEntry", "ENDC", "PathEntry", "_format_entry", "pytest"], "enclosing_function": "test_format_entry", "extracted_code": "# Source: sacred/commands.py\nCOLOR_DOC = Style.DIM\n\nENDC = Style.RESET_ALL\n\nConfigEntry = namedtuple(\"ConfigEntry\", \"key value added modified typechanged doc\")\n\nPathEntry = namedtuple(\"PathEntry\", \"key added modified typechanged doc\")\n\ndef _format_entry(indent, entry):\n color = \"\"\n indent = \" \" * indent\n if entry.typechanged:\n color = COLOR_TYPECHANGED # red\n elif entry.added:\n color = COLOR_ADDED # green\n elif entry.modified:\n color = COLOR_MODIFIED # blue\n if entry.key == \"__doc__\":\n color = COLOR_DOC # grey\n doc_string = entry.value.replace(\"\\n\", \"\\n\" + indent)\n assign = '{}\"\"\"{}\"\"\"'.format(indent, doc_string)\n elif isinstance(entry, ConfigEntry):\n assign = indent + entry.key + \" = \" + PRINTER.pformat(entry.value)\n else: # isinstance(entry, PathEntry):\n assign = indent + entry.key + \":\"\n if entry.doc:\n doc_string = COLOR_DOC + \"# \" + entry.doc + ENDC\n if len(assign) <= 35:\n assign = \"{:<35} {}\".format(assign, doc_string)\n else:\n assign += \" \" + doc_string\n end = ENDC if color else \"\"\n return color + assign + end", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 1171, "extracted_code_full": "# Source: sacred/commands.py\nCOLOR_DOC = Style.DIM\n\nENDC = Style.RESET_ALL\n\nConfigEntry = namedtuple(\"ConfigEntry\", \"key value added modified typechanged doc\")\n\nPathEntry = namedtuple(\"PathEntry\", \"key added modified typechanged doc\")\n\ndef _format_entry(indent, entry):\n color = \"\"\n indent = \" \" * indent\n if entry.typechanged:\n color = COLOR_TYPECHANGED # red\n elif entry.added:\n color = COLOR_ADDED # green\n elif entry.modified:\n color = COLOR_MODIFIED # blue\n if entry.key == \"__doc__\":\n color = COLOR_DOC # grey\n doc_string = entry.value.replace(\"\\n\", \"\\n\" + indent)\n assign = '{}\"\"\"{}\"\"\"'.format(indent, doc_string)\n elif isinstance(entry, ConfigEntry):\n assign = indent + entry.key + \" = \" + PRINTER.pformat(entry.value)\n else: # isinstance(entry, PathEntry):\n assign = indent + entry.key + \":\"\n if entry.doc:\n doc_string = COLOR_DOC + \"# \" + entry.doc + ENDC\n if len(assign) <= 35:\n assign = \"{:<35} {}\".format(assign, doc_string)\n else:\n assign += \" \" + doc_string\n end = ENDC if color else \"\"\n return color + assign + end", "n_chars_compressed": 1171, "compression_ratio": 1.0}, "tests/test_ingredients.py::51": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_capture_function_twice", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_config/test_config_dict.py::129": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_fixed_subentry_of_preset", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_modules.py::185": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment"], "enclosing_function": "test_experiment_double_named_config", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_observers/test_file_storage_observer.py::173": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["json"], "enclosing_function": "test_fs_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_utils.py::85": {"resolved_imports": ["sacred/utils.py"], "used_names": ["join_paths"], "enclosing_function": "test_join_paths", "extracted_code": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 172, "extracted_code_full": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_chars_compressed": 172, "compression_ratio": 1.0}, "tests/test_observers/test_mongo_observer.py::364": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["linearize_metrics"], "enclosing_function": "test_log_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 1080, "extracted_code_full": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1080, "compression_ratio": 1.0}, "tests/test_arg_parser.py::57": {"resolved_imports": ["sacred/arg_parser.py", "sacred/experiment.py"], "used_names": ["docopt", "format_usage", "gather_command_line_options", "pytest", "shlex"], "enclosing_function": "test_parse_individual_arguments", "extracted_code": "# Source: sacred/arg_parser.py\ndef format_usage(program_name, description, commands=None, options=()):\n \"\"\"\n Construct the usage text.\n\n Parameters\n ----------\n program_name : str\n Usually the name of the python file that contains the experiment.\n description : str\n description of this experiment (usually the docstring).\n commands : dict[str, func]\n Dictionary of supported commands.\n Each entry should be a tuple of (name, function).\n options : list[sacred.commandline_options.CommandLineOption]\n A list of all supported commandline options.\n\n Returns\n -------\n str\n The complete formatted usage text for this experiment.\n It adheres to the structure required by ``docopt``.\n\n \"\"\"\n usage = USAGE_TEMPLATE.format(\n program_name=quote(program_name),\n description=description.strip() if description else \"\",\n options=_format_options_usage(options),\n arguments=_format_arguments_usage(options),\n commands=_format_command_usage(commands),\n )\n return usage\n\n\n# Source: sacred/experiment.py\ndef gather_command_line_options(filter_disabled=None):\n \"\"\"Get a sorted list of all CommandLineOption subclasses.\"\"\"\n if filter_disabled is None:\n filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS\n\n options = []\n for opt in get_inheritors(commandline_options.CommandLineOption):\n warnings.warn(\n \"Subclassing `CommandLineOption` is deprecated. Please \"\n \"use the `sacred.cli_option` decorator and pass the function \"\n \"to the Experiment constructor.\"\n )\n if filter_disabled and not opt._enabled:\n continue\n options.append(opt)\n\n options += DEFAULT_COMMAND_LINE_OPTIONS\n\n return sorted(options, key=commandline_options.get_name)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1904, "extracted_code_full": "# Source: sacred/arg_parser.py\ndef format_usage(program_name, description, commands=None, options=()):\n \"\"\"\n Construct the usage text.\n\n Parameters\n ----------\n program_name : str\n Usually the name of the python file that contains the experiment.\n description : str\n description of this experiment (usually the docstring).\n commands : dict[str, func]\n Dictionary of supported commands.\n Each entry should be a tuple of (name, function).\n options : list[sacred.commandline_options.CommandLineOption]\n A list of all supported commandline options.\n\n Returns\n -------\n str\n The complete formatted usage text for this experiment.\n It adheres to the structure required by ``docopt``.\n\n \"\"\"\n usage = USAGE_TEMPLATE.format(\n program_name=quote(program_name),\n description=description.strip() if description else \"\",\n options=_format_options_usage(options),\n arguments=_format_arguments_usage(options),\n commands=_format_command_usage(commands),\n )\n return usage\n\n\n# Source: sacred/experiment.py\ndef gather_command_line_options(filter_disabled=None):\n \"\"\"Get a sorted list of all CommandLineOption subclasses.\"\"\"\n if filter_disabled is None:\n filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS\n\n options = []\n for opt in get_inheritors(commandline_options.CommandLineOption):\n warnings.warn(\n \"Subclassing `CommandLineOption` is deprecated. Please \"\n \"use the `sacred.cli_option` decorator and pass the function \"\n \"to the Experiment constructor.\"\n )\n if filter_disabled and not opt._enabled:\n continue\n options.append(opt)\n\n options += DEFAULT_COMMAND_LINE_OPTIONS\n\n return sorted(options, key=commandline_options.get_name)", "n_chars_compressed": 1904, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::154": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature", "pytest"], "enclosing_function": "test_constructor_extract_kwargs_wildcard_name", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_scope_chain.py::140": {"resolved_imports": ["sacred/config/__init__.py"], "used_names": ["chain_evaluate_config_scopes"], "enclosing_function": "test_empty_chain_contains_preset_and_fixed", "extracted_code": "# Source: sacred/config/__init__.py\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 577, "extracted_code_full": "# Source: sacred/config/__init__.py\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 577, "compression_ratio": 1.0}, "tests/test_ingredients.py::123": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_add_unobserved_command", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_utils.py::216": {"resolved_imports": ["sacred/utils.py"], "used_names": ["rel_path"], "enclosing_function": "test_rel_path", "extracted_code": "# Source: sacred/utils.py\ndef rel_path(base, path):\n \"\"\"Return path relative to base.\"\"\"\n if base == path:\n return \"\"\n assert is_prefix(base, path), \"{} not a prefix of {}\".format(base, path)\n return path[len(base) :].strip(\".\")", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 247, "extracted_code_full": "# Source: sacred/utils.py\ndef rel_path(base, path):\n \"\"\"Return path relative to base.\"\"\"\n if base == path:\n return \"\"\n assert is_prefix(base, path), \"{} not a prefix of {}\".format(base, path)\n return path[len(base) :].strip(\".\")", "n_chars_compressed": 247, "compression_ratio": 1.0}, "tests/test_modules.py::133": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_named_config_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_ingredients.py::164": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_add_config_dict", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::127": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_fixed_subentry_of_preset", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_utils.py::193": {"resolved_imports": ["sacred/utils.py"], "used_names": ["get_package_version"], "enclosing_function": "test_get_package_version", "extracted_code": "# Source: sacred/utils.py\ndef get_package_version(name):\n \"\"\"Returns a parsed version string of a package.\"\"\"\n version_string = importlib.import_module(name).__version__\n return parse_version(version_string)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 216, "extracted_code_full": "# Source: sacred/utils.py\ndef get_package_version(name):\n \"\"\"Returns a parsed version string of a package.\"\"\"\n version_string = importlib.import_module(name).__version__\n return parse_version(version_string)", "n_chars_compressed": 216, "compression_ratio": 1.0}, "tests/test_config/test_readonly_containers.py::281": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["deepcopy", "make_read_only"], "enclosing_function": "test_deepcopy_on_nested_readonly_list", "extracted_code": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 588, "extracted_code_full": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_chars_compressed": 588, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_dict.py::70": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_update_with_list_of_items", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_observers/test_s3_observer.py::181": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["json"], "enclosing_function": "test_failed_event_updates_run_json", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config/test_captured_functions.py::127": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock"], "enclosing_function": "test_captured_function_call_doesnt_modify_kwargs", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_reader.py::159": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader", "datetime", "get_digest", "pytest"], "enclosing_function": "test_fetch_metadata_function_with_indices", "extracted_code": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6556, "extracted_code_full": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6556, "compression_ratio": 1.0}, "tests/test_config/test_readonly_containers.py::40": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["ReadOnlyDict", "SacredError", "pytest"], "enclosing_function": "_check_read_only_dict", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass ReadOnlyDict(ReadOnlyContainer, dict):\n \"\"\"A read-only variant of a `dict`.\"\"\"\n\n # Overwrite all methods that can modify a dict\n clear = ReadOnlyContainer._readonly\n pop = ReadOnlyContainer._readonly\n popitem = ReadOnlyContainer._readonly\n setdefault = ReadOnlyContainer._readonly\n update = ReadOnlyContainer._readonly\n __setitem__ = ReadOnlyContainer._readonly\n __delitem__ = ReadOnlyContainer._readonly\n\n def __copy__(self):\n return {**self}\n\n def __deepcopy__(self, memo):\n d = dict(self)\n return copy.deepcopy(d, memo=memo)\n\n\n# Source: sacred/utils.py\nclass SacredError(Exception):\n def __init__(\n self,\n message,\n print_traceback=True,\n filter_traceback=\"default\",\n print_usage=False,\n ):\n super().__init__(message)\n self.print_traceback = print_traceback\n if filter_traceback not in [\"always\", \"default\", \"never\"]:\n raise ValueError(\n \"filter_traceback must be one of 'always', \"\n \"'default' or 'never', not \" + filter_traceback\n )\n self.filter_traceback = filter_traceback\n self.print_usage = print_usage", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass ReadOnlyDict(ReadOnlyContainer, dict):\n \"\"\"A read-only variant of a `dict`.\"\"\"\n\n # Overwrite all methods that can modify a dict\n clear = ReadOnlyContainer._readonly\n pop = ReadOnlyContainer._readonly\n popitem = ReadOnlyContainer._readonly\n setdefault = ReadOnlyContainer._readonly\n update = ReadOnlyContainer._readonly\n __setitem__ = ReadOnlyContainer._readonly\n __delitem__ = ReadOnlyContainer._readonly\n\n def __copy__(self):\n return {**self}\n\n def __deepcopy__(self, memo):\n d = dict(self)\n return copy.deepcopy(d, memo=memo)\n\n\n# Source: sacred/utils.py\nclass SacredError(Exception):\n def __init__(\n self,\n message,\n print_traceback=True,\n filter_traceback=\"default\",\n print_usage=False,\n ):\n super().__init__(message)\n self.print_traceback = print_traceback\n if filter_traceback not in [\"always\", \"default\", \"never\"]:\n raise ValueError(\n \"filter_traceback must be one of 'always', \"\n \"'default' or 'never', not \" + filter_traceback\n )\n self.filter_traceback = filter_traceback\n self.print_usage = print_usage", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_modules.py::186": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment"], "enclosing_function": "test_experiment_double_named_config", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_config/test_config_scope_chain.py::130": {"resolved_imports": ["sacred/config/__init__.py"], "used_names": ["ConfigScope", "chain_evaluate_config_scopes"], "enclosing_function": "test_chained_config_scopes_fix_subentries", "extracted_code": "# Source: sacred/config/__init__.py\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1209, "extracted_code_full": "# Source: sacred/config/__init__.py\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 1208, "compression_ratio": 0.9991728701406121}, "tests/test_metrics_logger.py::35": {"resolved_imports": ["sacred/__init__.py", "sacred/metrics_logger.py"], "used_names": [], "enclosing_function": "test_log_scalar_metric_with_run", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_observers/test_tinydb_reader.py::162": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader", "datetime", "get_digest", "pytest"], "enclosing_function": "test_fetch_metadata_function_with_indices", "extracted_code": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6556, "extracted_code_full": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()\n\n\n# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6556, "compression_ratio": 1.0}, "tests/test_modules.py::136": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_named_config_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_observers/test_tinydb_observer.py::125": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py", "sacred/observers/tinydb_hashfs/bases.py", "sacred/__init__.py", "sacred/optional.py", "sacred/experiment.py"], "used_names": ["get_digest", "io"], "enclosing_function": "test_tinydb_observer_started_event_saves_given_sources", "extracted_code": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()", "n_imports_parsed": 13, "n_files_resolved": 6, "n_chars_extracted": 305, "extracted_code_full": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()", "n_chars_compressed": 305, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::288": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_construct_arguments_completes_kwargs_from_options", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_observers/test_file_storage_observer.py::308": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["FileStorageObserver"], "enclosing_function": "test_fs_observer_equality", "extracted_code": "# Source: sacred/observers/file_storage.py\nclass FileStorageObserver(RunObserver):\n VERSION = \"FileStorageObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"FileStorageObserver.create(...) is deprecated. \"\n \"Please use FileStorageObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n basedir: PathType,\n resource_dir: Optional[PathType] = None,\n source_dir: Optional[PathType] = None,\n template: Optional[PathType] = None,\n priority: int = DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts: bool = True,\n copy_sources: bool = True,\n ):\n basedir = Path(basedir)\n resource_dir = resource_dir or basedir / \"_resources\"\n source_dir = source_dir or basedir / \"_sources\"\n if template is not None:\n if not os.path.exists(template):\n raise FileNotFoundError(\n \"Couldn't find template file '{}'\".format(template)\n )\n else:\n template = basedir / \"template.html\"\n if not template.exists():\n template = None\n self.initialize(\n basedir,\n resource_dir,\n source_dir,\n template,\n priority,\n copy_artifacts,\n copy_sources,\n )\n\n def initialize(\n self,\n basedir,\n resource_dir,\n source_dir,\n template,\n priority=DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts=True,\n copy_sources=True,\n ):\n self.basedir = str(basedir)\n self.resource_dir = resource_dir\n self.source_dir = source_dir\n self.template = template\n self.priority = priority\n self.copy_artifacts = copy_artifacts\n self.copy_sources = copy_sources\n self.dir = None\n self.run_entry = None\n self.config = None\n self.info = None\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def _maximum_existing_run_id(self):\n dir_nrs = [\n int(d)\n for d in os.listdir(self.basedir)\n if os.path.isdir(os.path.join(self.basedir, d)) and d.isdigit()\n ]\n if dir_nrs:\n return max(dir_nrs)\n else:\n return 0\n\n def _make_dir(self, _id):\n new_dir = os.path.join(self.basedir, str(_id))\n os.mkdir(new_dir)\n self.dir = new_dir # set only if mkdir is successful\n\n def _make_run_dir(self, _id):\n os.makedirs(self.basedir, exist_ok=True)\n self.dir = None\n if _id is None:\n fail_count = 0\n _id = self._maximum_existing_run_id() + 1\n while self.dir is None:\n try:\n self._make_dir(_id)\n except FileExistsError: # Catch race conditions\n if fail_count < 1000:\n fail_count += 1\n _id += 1\n else: # expect that something else went wrong\n raise\n else:\n self.dir = os.path.join(self.basedir, str(_id))\n os.mkdir(self.dir)\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n self.config = config\n self.info = {}\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n\n if self.copy_sources:\n for s, _ in ex_info[\"sources\"]:\n self.save_file(s)\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for s, _ in ex_info[\"sources\"]:\n abspath = os.path.join(base_dir, s)\n if self.copy_sources:\n store_path = self.find_or_save(abspath, self.source_dir)\n else:\n store_path = abspath\n relative_source = os.path.relpath(str(store_path), self.basedir)\n source_info.append([s, relative_source])\n return source_info\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n ex_info[\"sources\"] = self.save_sources(ex_info)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time.isoformat(),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"heartbeat\": None,\n }\n self.config = config\n self.info = {}\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n self.save_cout()\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def find_or_save(self, filename, store_dir: Path):\n try:\n Path(filename).resolve().relative_to(Path(self.basedir).resolve())\n is_relative_to = True\n except ValueError:\n is_relative_to = False\n\n if is_relative_to and not self.copy_artifacts:\n return filename\n else:\n store_dir.mkdir(parents=True, exist_ok=True)\n source_name, ext = os.path.splitext(os.path.basename(filename))\n md5sum = get_digest(filename)\n store_name = source_name + \"_\" + md5sum + ext\n store_path = store_dir / store_name\n if not store_path.exists():\n copyfile(filename, str(store_path))\n return store_path\n\n def save_json(self, obj, filename):\n with open(os.path.join(self.dir, filename), \"w\") as f:\n json.dump(flatten(obj), f, sort_keys=True, indent=2)\n f.flush()\n\n def save_file(self, filename, target_name=None):\n target_name = target_name or os.path.basename(filename)\n blacklist = [\"run.json\", \"config.json\", \"cout.txt\", \"metrics.json\"]\n blacklist = [os.path.join(self.dir, x) for x in blacklist]\n dest_file = os.path.join(self.dir, target_name)\n if dest_file in blacklist:\n raise FileExistsError(\n \"You are trying to overwrite a file necessary for the \"\n \"FileStorageObserver. \"\n \"The list of blacklisted files is: {}\".format(blacklist)\n )\n try:\n copyfile(filename, dest_file)\n except SameFileError:\n pass\n\n def save_cout(self):\n with open(os.path.join(self.dir, \"cout.txt\"), \"ab\") as f:\n f.write(self.cout[self.cout_write_cursor :].encode(\"utf-8\"))\n self.cout_write_cursor = len(self.cout)\n\n def render_template(self):\n if opt.has_mako and self.template:\n from mako.template import Template\n\n template = Template(filename=self.template)\n report = template.render(\n run=self.run_entry,\n config=self.config,\n info=self.info,\n cout=self.cout,\n savedir=self.dir,\n )\n ext = self.template.suffix\n with open(os.path.join(self.dir, \"report\" + ext), \"w\") as f:\n f.write(report)\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.info = info\n self.run_entry[\"heartbeat\"] = beat_time.isoformat()\n self.run_entry[\"result\"] = result\n self.cout = captured_out\n self.save_cout()\n self.save_json(self.run_entry, \"run.json\")\n if self.info:\n self.save_json(self.info, \"info.json\")\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time.isoformat()\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time.isoformat()\n self.run_entry[\"status\"] = status\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time.isoformat()\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def resource_event(self, filename):\n store_path = self.find_or_save(filename, self.resource_dir)\n self.run_entry[\"resources\"].append([filename, str(store_path)])\n self.save_json(self.run_entry, \"run.json\")\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n self.save_file(filename, name)\n self.run_entry[\"artifacts\"].append(name)\n self.save_json(self.run_entry, \"run.json\")\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements into metrics.json.\"\"\"\n try:\n metrics_path = os.path.join(self.dir, \"metrics.json\")\n with open(metrics_path, \"r\") as f:\n saved_metrics = json.load(f)\n except IOError:\n # We haven't recorded anything yet. Start Collecting.\n saved_metrics = {}\n\n for metric_name, metric_ptr in metrics_by_name.items():\n\n if metric_name not in saved_metrics:\n saved_metrics[metric_name] = {\n \"values\": [],\n \"steps\": [],\n \"timestamps\": [],\n }\n\n saved_metrics[metric_name][\"values\"] += metric_ptr[\"values\"]\n saved_metrics[metric_name][\"steps\"] += metric_ptr[\"steps\"]\n\n # Manually convert them to avoid passing a datetime dtype handler\n # when we're trying to convert into json.\n timestamps_norm = [ts.isoformat() for ts in metric_ptr[\"timestamps\"]]\n saved_metrics[metric_name][\"timestamps\"] += timestamps_norm\n\n self.save_json(saved_metrics, \"metrics.json\")\n\n def __eq__(self, other):\n if isinstance(other, FileStorageObserver):\n return self.basedir == other.basedir\n return False", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 10857, "extracted_code_full": "# Source: sacred/observers/file_storage.py\nclass FileStorageObserver(RunObserver):\n VERSION = \"FileStorageObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"FileStorageObserver.create(...) is deprecated. \"\n \"Please use FileStorageObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n basedir: PathType,\n resource_dir: Optional[PathType] = None,\n source_dir: Optional[PathType] = None,\n template: Optional[PathType] = None,\n priority: int = DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts: bool = True,\n copy_sources: bool = True,\n ):\n basedir = Path(basedir)\n resource_dir = resource_dir or basedir / \"_resources\"\n source_dir = source_dir or basedir / \"_sources\"\n if template is not None:\n if not os.path.exists(template):\n raise FileNotFoundError(\n \"Couldn't find template file '{}'\".format(template)\n )\n else:\n template = basedir / \"template.html\"\n if not template.exists():\n template = None\n self.initialize(\n basedir,\n resource_dir,\n source_dir,\n template,\n priority,\n copy_artifacts,\n copy_sources,\n )\n\n def initialize(\n self,\n basedir,\n resource_dir,\n source_dir,\n template,\n priority=DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts=True,\n copy_sources=True,\n ):\n self.basedir = str(basedir)\n self.resource_dir = resource_dir\n self.source_dir = source_dir\n self.template = template\n self.priority = priority\n self.copy_artifacts = copy_artifacts\n self.copy_sources = copy_sources\n self.dir = None\n self.run_entry = None\n self.config = None\n self.info = None\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def _maximum_existing_run_id(self):\n dir_nrs = [\n int(d)\n for d in os.listdir(self.basedir)\n if os.path.isdir(os.path.join(self.basedir, d)) and d.isdigit()\n ]\n if dir_nrs:\n return max(dir_nrs)\n else:\n return 0\n\n def _make_dir(self, _id):\n new_dir = os.path.join(self.basedir, str(_id))\n os.mkdir(new_dir)\n self.dir = new_dir # set only if mkdir is successful\n\n def _make_run_dir(self, _id):\n os.makedirs(self.basedir, exist_ok=True)\n self.dir = None\n if _id is None:\n fail_count = 0\n _id = self._maximum_existing_run_id() + 1\n while self.dir is None:\n try:\n self._make_dir(_id)\n except FileExistsError: # Catch race conditions\n if fail_count < 1000:\n fail_count += 1\n _id += 1\n else: # expect that something else went wrong\n raise\n else:\n self.dir = os.path.join(self.basedir, str(_id))\n os.mkdir(self.dir)\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n self.config = config\n self.info = {}\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n\n if self.copy_sources:\n for s, _ in ex_info[\"sources\"]:\n self.save_file(s)\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for s, _ in ex_info[\"sources\"]:\n abspath = os.path.join(base_dir, s)\n if self.copy_sources:\n store_path = self.find_or_save(abspath, self.source_dir)\n else:\n store_path = abspath\n relative_source = os.path.relpath(str(store_path), self.basedir)\n source_info.append([s, relative_source])\n return source_info\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n ex_info[\"sources\"] = self.save_sources(ex_info)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time.isoformat(),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"heartbeat\": None,\n }\n self.config = config\n self.info = {}\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n self.save_cout()\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def find_or_save(self, filename, store_dir: Path):\n try:\n Path(filename).resolve().relative_to(Path(self.basedir).resolve())\n is_relative_to = True\n except ValueError:\n is_relative_to = False\n\n if is_relative_to and not self.copy_artifacts:\n return filename\n else:\n store_dir.mkdir(parents=True, exist_ok=True)\n source_name, ext = os.path.splitext(os.path.basename(filename))\n md5sum = get_digest(filename)\n store_name = source_name + \"_\" + md5sum + ext\n store_path = store_dir / store_name\n if not store_path.exists():\n copyfile(filename, str(store_path))\n return store_path\n\n def save_json(self, obj, filename):\n with open(os.path.join(self.dir, filename), \"w\") as f:\n json.dump(flatten(obj), f, sort_keys=True, indent=2)\n f.flush()\n\n def save_file(self, filename, target_name=None):\n target_name = target_name or os.path.basename(filename)\n blacklist = [\"run.json\", \"config.json\", \"cout.txt\", \"metrics.json\"]\n blacklist = [os.path.join(self.dir, x) for x in blacklist]\n dest_file = os.path.join(self.dir, target_name)\n if dest_file in blacklist:\n raise FileExistsError(\n \"You are trying to overwrite a file necessary for the \"\n \"FileStorageObserver. \"\n \"The list of blacklisted files is: {}\".format(blacklist)\n )\n try:\n copyfile(filename, dest_file)\n except SameFileError:\n pass\n\n def save_cout(self):\n with open(os.path.join(self.dir, \"cout.txt\"), \"ab\") as f:\n f.write(self.cout[self.cout_write_cursor :].encode(\"utf-8\"))\n self.cout_write_cursor = len(self.cout)\n\n def render_template(self):\n if opt.has_mako and self.template:\n from mako.template import Template\n\n template = Template(filename=self.template)\n report = template.render(\n run=self.run_entry,\n config=self.config,\n info=self.info,\n cout=self.cout,\n savedir=self.dir,\n )\n ext = self.template.suffix\n with open(os.path.join(self.dir, \"report\" + ext), \"w\") as f:\n f.write(report)\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.info = info\n self.run_entry[\"heartbeat\"] = beat_time.isoformat()\n self.run_entry[\"result\"] = result\n self.cout = captured_out\n self.save_cout()\n self.save_json(self.run_entry, \"run.json\")\n if self.info:\n self.save_json(self.info, \"info.json\")\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time.isoformat()\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time.isoformat()\n self.run_entry[\"status\"] = status\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time.isoformat()\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def resource_event(self, filename):\n store_path = self.find_or_save(filename, self.resource_dir)\n self.run_entry[\"resources\"].append([filename, str(store_path)])\n self.save_json(self.run_entry, \"run.json\")\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n self.save_file(filename, name)\n self.run_entry[\"artifacts\"].append(name)\n self.save_json(self.run_entry, \"run.json\")\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements into metrics.json.\"\"\"\n try:\n metrics_path = os.path.join(self.dir, \"metrics.json\")\n with open(metrics_path, \"r\") as f:\n saved_metrics = json.load(f)\n except IOError:\n # We haven't recorded anything yet. Start Collecting.\n saved_metrics = {}\n\n for metric_name, metric_ptr in metrics_by_name.items():\n\n if metric_name not in saved_metrics:\n saved_metrics[metric_name] = {\n \"values\": [],\n \"steps\": [],\n \"timestamps\": [],\n }\n\n saved_metrics[metric_name][\"values\"] += metric_ptr[\"values\"]\n saved_metrics[metric_name][\"steps\"] += metric_ptr[\"steps\"]\n\n # Manually convert them to avoid passing a datetime dtype handler\n # when we're trying to convert into json.\n timestamps_norm = [ts.isoformat() for ts in metric_ptr[\"timestamps\"]]\n saved_metrics[metric_name][\"timestamps\"] += timestamps_norm\n\n self.save_json(saved_metrics, \"metrics.json\")\n\n def __eq__(self, other):\n if isinstance(other, FileStorageObserver):\n return self.basedir == other.basedir\n return False", "n_chars_compressed": 10857, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_reader.py::290": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader", "datetime", "io"], "enclosing_function": "test_fetch_files_function", "extracted_code": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6248, "extracted_code_full": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6248, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::276": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_construct_arguments_without_options_returns_same_args_kwargs", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::110": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_conf_scope_contains_presets", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_observers/test_s3_observer.py::109": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": [], "enclosing_function": "test_fs_observer_started_event_increments_run_id", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_run.py::44": {"resolved_imports": ["sacred/run.py", "sacred/config/config_summary.py", "sacred/utils.py"], "used_names": [], "enclosing_function": "test_run_state_attributes", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_config/test_signature.py::148": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature", "pytest"], "enclosing_function": "test_constructor_extract_vararg_name", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::59": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fixing_nested_dicts", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_queue_mongo_observer.py::244": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["linearize_metrics"], "enclosing_function": "test_log_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 1080, "extracted_code_full": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1080, "compression_ratio": 1.0}, "tests/test_config/test_config_scope.py::92": {"resolved_imports": ["sacred/optional.py", "sacred/config/config_scope.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fixing_nested_dicts", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_modules.py::79": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_run_access_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_observers/test_file_storage_observer.py::108": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["os"], "enclosing_function": "test_fs_observer_started_event_creates_rundir_with_filesystem_delay", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_experiment.py::104": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_fails_on_nested_unused_config_updates", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_dict.py::130": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_overwrite_fallback", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_config/test_config_files.py::31": {"resolved_imports": ["sacred/config/config_files.py"], "used_names": ["HANDLER_BY_EXT", "load_config_file", "os", "pytest", "tempfile"], "enclosing_function": "test_load_config_file", "extracted_code": "# Source: sacred/config/config_files.py\nHANDLER_BY_EXT = {\n \".json\": Handler(\n lambda fp: restore(json.load(fp)),\n lambda obj, fp: json.dump(flatten(obj), fp, sort_keys=True, indent=2),\n \"\",\n ),\n \".pickle\": Handler(pickle.load, pickle.dump, \"b\"),\n}\n\ndef load_config_file(filename):\n handler = get_handler(filename)\n with open(filename, \"r\" + handler.mode) as f:\n return handler.load(f)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 428, "extracted_code_full": "# Source: sacred/config/config_files.py\nHANDLER_BY_EXT = {\n \".json\": Handler(\n lambda fp: restore(json.load(fp)),\n lambda obj, fp: json.dump(flatten(obj), fp, sort_keys=True, indent=2),\n \"\",\n ),\n \".pickle\": Handler(pickle.load, pickle.dump, \"b\"),\n}\n\ndef load_config_file(filename):\n handler = get_handler(filename)\n with open(filename, \"r\" + handler.mode) as f:\n return handler.load(f)", "n_chars_compressed": 428, "compression_ratio": 1.0}, "tests/test_observers/test_file_storage_observer.py::357": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["json", "linearize_metrics"], "enclosing_function": "test_log_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1080, "extracted_code_full": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1080, "compression_ratio": 1.0}, "tests/test_run.py::129": {"resolved_imports": ["sacred/run.py", "sacred/config/config_summary.py", "sacred/utils.py"], "used_names": ["datetime"], "enclosing_function": "test_run_heartbeat_event", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_dependencies.py::245": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py"], "used_names": ["is_local_source", "pytest"], "enclosing_function": "test_is_local_source", "extracted_code": "# Source: sacred/dependencies.py\ndef is_local_source(filename, modname, experiment_path):\n \"\"\"Check if a module comes from the given experiment path.\n\n Check if a module, given by name and filename, is from (a subdirectory of )\n the given experiment path.\n This is used to determine if the module is a local source file, or rather\n a package dependency.\n\n Parameters\n ----------\n filename: str\n The absolute filename of the module in question.\n (Usually module.__file__)\n modname: str\n The full name of the module including parent namespaces.\n experiment_path: str\n The base path of the experiment.\n\n Returns\n -------\n bool:\n True if the module was imported locally from (a subdir of) the\n experiment_path, and False otherwise.\n \"\"\"\n filename = Path(os.path.abspath(os.path.realpath(filename)))\n experiment_path = Path(os.path.abspath(os.path.realpath(experiment_path)))\n if experiment_path not in filename.parents:\n return False\n rel_path = filename.relative_to(experiment_path)\n path_parts = convert_path_to_module_parts(rel_path)\n\n mod_parts = modname.split(\".\")\n if path_parts == mod_parts:\n return True\n if len(path_parts) > len(mod_parts):\n return False\n abs_path_parts = convert_path_to_module_parts(filename)\n return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 1436, "extracted_code_full": "# Source: sacred/dependencies.py\ndef is_local_source(filename, modname, experiment_path):\n \"\"\"Check if a module comes from the given experiment path.\n\n Check if a module, given by name and filename, is from (a subdirectory of )\n the given experiment path.\n This is used to determine if the module is a local source file, or rather\n a package dependency.\n\n Parameters\n ----------\n filename: str\n The absolute filename of the module in question.\n (Usually module.__file__)\n modname: str\n The full name of the module including parent namespaces.\n experiment_path: str\n The base path of the experiment.\n\n Returns\n -------\n bool:\n True if the module was imported locally from (a subdir of) the\n experiment_path, and False otherwise.\n \"\"\"\n filename = Path(os.path.abspath(os.path.realpath(filename)))\n experiment_path = Path(os.path.abspath(os.path.realpath(experiment_path)))\n if experiment_path not in filename.parents:\n return False\n rel_path = filename.relative_to(experiment_path)\n path_parts = convert_path_to_module_parts(rel_path)\n\n mod_parts = modname.split(\".\")\n if path_parts == mod_parts:\n return True\n if len(path_parts) > len(mod_parts):\n return False\n abs_path_parts = convert_path_to_module_parts(filename)\n return all([p == m for p, m in zip(reversed(abs_path_parts), reversed(mod_parts))])", "n_chars_compressed": 1436, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_observer.py::132": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py", "sacred/observers/tinydb_hashfs/bases.py", "sacred/__init__.py", "sacred/optional.py", "sacred/experiment.py"], "used_names": ["get_digest", "io"], "enclosing_function": "test_tinydb_observer_started_event_saves_given_sources", "extracted_code": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()", "n_imports_parsed": 13, "n_files_resolved": 6, "n_chars_extracted": 305, "extracted_code_full": "# Source: sacred/dependencies.py\ndef get_digest(filename):\n \"\"\"Compute the MD5 hash for a given file.\"\"\"\n h = hashlib.md5()\n with open(filename, \"rb\") as f:\n data = f.read(1 * MB)\n while data:\n h.update(data)\n data = f.read(1 * MB)\n return h.hexdigest()", "n_chars_compressed": 305, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::19": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function"], "enclosing_function": "test_create_captured_function", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_dict.py::60": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_update_with_kwargs", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_ingredients.py::240": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_get_experiment_info", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_experiment.py::84": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_fails_on_unused_config_updates", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_experiment.py::127": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_considers_captured_functions_for_fail_on_unused_config", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::142": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict", "DogmaticList"], "enclosing_function": "test_nested_dict_revelation", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing\n\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 4472, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing\n\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 4472, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::98": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_list_interface_getitem", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::117": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_host_info.py::29": {"resolved_imports": ["sacred/host_info.py"], "used_names": ["get_host_info", "host_info_gatherers", "host_info_getter"], "enclosing_function": "test_host_info_decorator", "extracted_code": "# Source: sacred/host_info.py\nhost_info_gatherers = {}\n\ndef get_host_info(additional_host_info: List[HostInfoGetter] = None):\n \"\"\"Collect some information about the machine this experiment runs on.\n\n Returns\n -------\n dict\n A dictionary with information about the CPU, the OS and the\n Python version of this machine.\n\n \"\"\"\n additional_host_info = additional_host_info or []\n # can't use += because we don't want to modify the mutable argument.\n additional_host_info = additional_host_info + _host_info_gatherers_list\n all_host_info_gatherers = host_info_gatherers.copy()\n for getter in additional_host_info:\n all_host_info_gatherers[getter.name] = getter\n host_info = {}\n for k, v in all_host_info_gatherers.items():\n try:\n host_info[k] = v()\n except IgnoreHostInfo:\n pass\n return host_info\n\ndef host_info_getter(func, name=None):\n \"\"\"\n The decorated function is added to the process of collecting the host_info.\n\n This just adds the decorated function to the global\n ``sacred.host_info.host_info_gatherers`` dictionary.\n The functions from that dictionary are used when collecting the host info\n using :py:func:`~sacred.host_info.get_host_info`.\n\n Parameters\n ----------\n func : callable\n A function that can be called without arguments and returns some\n json-serializable information.\n name : str, optional\n The name of the corresponding entry in host_info.\n Defaults to the name of the function.\n\n Returns\n -------\n The function itself.\n\n \"\"\"\n warnings.warn(\n \"The host_info_getter is deprecated. \"\n \"Please use the `additional_host_info` argument\"\n \" in the Experiment constructor.\",\n DeprecationWarning,\n )\n name = name or func.__name__\n host_info_gatherers[name] = func\n return func", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1897, "extracted_code_full": "# Source: sacred/host_info.py\nhost_info_gatherers = {}\n\ndef get_host_info(additional_host_info: List[HostInfoGetter] = None):\n \"\"\"Collect some information about the machine this experiment runs on.\n\n Returns\n -------\n dict\n A dictionary with information about the CPU, the OS and the\n Python version of this machine.\n\n \"\"\"\n additional_host_info = additional_host_info or []\n # can't use += because we don't want to modify the mutable argument.\n additional_host_info = additional_host_info + _host_info_gatherers_list\n all_host_info_gatherers = host_info_gatherers.copy()\n for getter in additional_host_info:\n all_host_info_gatherers[getter.name] = getter\n host_info = {}\n for k, v in all_host_info_gatherers.items():\n try:\n host_info[k] = v()\n except IgnoreHostInfo:\n pass\n return host_info\n\ndef host_info_getter(func, name=None):\n \"\"\"\n The decorated function is added to the process of collecting the host_info.\n\n This just adds the decorated function to the global\n ``sacred.host_info.host_info_gatherers`` dictionary.\n The functions from that dictionary are used when collecting the host info\n using :py:func:`~sacred.host_info.get_host_info`.\n\n Parameters\n ----------\n func : callable\n A function that can be called without arguments and returns some\n json-serializable information.\n name : str, optional\n The name of the corresponding entry in host_info.\n Defaults to the name of the function.\n\n Returns\n -------\n The function itself.\n\n \"\"\"\n warnings.warn(\n \"The host_info_getter is deprecated. \"\n \"Please use the `additional_host_info` argument\"\n \" in the Experiment constructor.\",\n DeprecationWarning,\n )\n name = name or func.__name__\n host_info_gatherers[name] = func\n return func", "n_chars_compressed": 1897, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::355": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_construct_arguments_for_bound_method", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_scope_chain.py::19": {"resolved_imports": ["sacred/config/__init__.py"], "used_names": ["ConfigScope", "chain_evaluate_config_scopes"], "enclosing_function": "test_chained_config_scopes_contain_combined_keys", "extracted_code": "# Source: sacred/config/__init__.py\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1209, "extracted_code_full": "# Source: sacred/config/__init__.py\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 1208, "compression_ratio": 0.9991728701406121}, "tests/test_commands.py::154": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["ConfigSummary", "_format_config"], "enclosing_function": "test_format_config", "extracted_code": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 2471, "extracted_code_full": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_chars_compressed": 2471, "compression_ratio": 1.0}, "tests/test_experiment.py::468": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["Experiment", "cli_option", "pytest"], "enclosing_function": "test_additional_cli_options", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_config/test_fallback_dict.py::28": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fallback", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_optional.py::11": {"resolved_imports": ["sacred/optional.py"], "used_names": ["optional_import", "pytest"], "enclosing_function": "test_optional_import", "extracted_code": "# Source: sacred/optional.py\ndef optional_import(*package_names):\n try:\n packages = [importlib.import_module(pn) for pn in package_names]\n return True, packages[0]\n except ImportError:\n return False, None", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 231, "extracted_code_full": "# Source: sacred/optional.py\ndef optional_import(*package_names):\n try:\n packages = [importlib.import_module(pn) for pn in package_names]\n return True, packages[0]\n except ImportError:\n return False, None", "n_chars_compressed": 231, "compression_ratio": 1.0}, "tests/test_dependencies.py::193": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py", "sacred/__init__.py"], "used_names": ["PackageDependency", "Path", "SETTINGS", "Source", "gather_sources_and_dependencies", "mock", "os", "path", "pytest", "some_func"], "enclosing_function": "test_gather_sources_and_dependencies", "extracted_code": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4304, "extracted_code_full": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_chars_compressed": 4303, "compression_ratio": 0.9997676579925651}, "tests/test_config/test_config_dict.py::58": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fixing_nested_dicts", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_experiment.py::82": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_fails_on_unused_config_updates", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_experiment.py::102": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_fails_on_nested_unused_config_updates", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_observer.py::192": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py", "sacred/observers/tinydb_hashfs/bases.py", "sacred/__init__.py", "sacred/optional.py", "sacred/experiment.py"], "used_names": [], "enclosing_function": "test_tinydb_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 13, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_config/test_dogmatic_dict.py::69": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_update_with_list_of_items", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::110": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_list_interface_len", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_run.py::42": {"resolved_imports": ["sacred/run.py", "sacred/config/config_summary.py", "sacred/utils.py"], "used_names": [], "enclosing_function": "test_run_state_attributes", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_s3_observer.py::194": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["json"], "enclosing_function": "test_queued_event_updates_run_json", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config/test_readonly_containers.py::279": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["deepcopy", "make_read_only"], "enclosing_function": "test_deepcopy_on_nested_readonly_list", "extracted_code": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 588, "extracted_code_full": "# Source: sacred/config/custom_containers.py\ndef make_read_only(o):\n \"\"\"Makes objects read-only.\n\n Converts every `list` and `dict` into `ReadOnlyList` and `ReadOnlyDict` in\n a nested structure of `list`s, `dict`s and `tuple`s. Does not modify `o`\n but returns the converted structure.\n \"\"\"\n if type(o) == dict:\n return ReadOnlyDict({k: make_read_only(v) for k, v in o.items()})\n elif type(o) == list:\n return ReadOnlyList([make_read_only(v) for v in o])\n elif type(o) == tuple:\n return tuple(map(make_read_only, o))\n else:\n return o", "n_chars_compressed": 588, "compression_ratio": 1.0}, "tests/test_ingredients.py::102": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_add_command", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_config/test_config_dict.py::100": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict", "pytest"], "enclosing_function": "test_conf_scope_handles_numpy_bools", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_config/test_fallback_dict.py::36": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_get", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_serializer.py::55": {"resolved_imports": ["sacred/serializer.py", "sacred/optional.py"], "used_names": ["flatten", "pytest", "restore"], "enclosing_function": "test_serialize_numpy_arrays", "extracted_code": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 193, "extracted_code_full": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_chars_compressed": 193, "compression_ratio": 1.0}, "tests/test_observers/test_tinydb_observer.py::176": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py", "sacred/observers/tinydb_hashfs/bases.py", "sacred/__init__.py", "sacred/optional.py", "sacred/experiment.py"], "used_names": ["HashFS", "TinyDB", "TinyDbObserver", "os"], "enclosing_function": "test_tinydb_observer_equality", "extracted_code": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbObserver(RunObserver):\n\n VERSION = \"TinyDbObserver-{}\".format(__version__)\n\n @classmethod\n def create(cls, path=\"./runs_db\", overwrite=None):\n warnings.warn(\n \"TinyDbObserver.create(...) is deprecated. \"\n \"Please use TinyDbObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(path, overwrite)\n\n def __init__(self, path=\"./runs_db\", overwrite=None):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n os.makedirs(root_dir, exist_ok=True)\n\n db, fs = get_db_file_manager(root_dir)\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n self.overwrite = overwrite\n self.run_entry = {}\n self.db_run_id = None\n self.root = root_dir\n\n @classmethod\n def create_from(cls, db, fs, overwrite=None, root=None):\n \"\"\"Instantiate a TinyDbObserver with an existing db and filesystem.\"\"\"\n self = cls.__new__(cls) # skip __init__ call\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n self.overwrite = overwrite\n self.run_entry = {}\n self.db_run_id = None\n self.root = root\n return self\n\n def save(self):\n \"\"\"Insert or update the current run entry.\"\"\"\n if self.db_run_id:\n self.runs.update(self.run_entry, doc_ids=[self.db_run_id])\n else:\n db_run_id = self.runs.insert(self.run_entry)\n self.db_run_id = db_run_id\n\n def save_sources(self, ex_info):\n from .bases import BufferedReaderWrapper\n\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n\n # Substitute any HOME or Environment Vars to get absolute path\n abs_path = os.path.join(ex_info[\"base_dir\"], source_name)\n abs_path = os.path.expanduser(abs_path)\n abs_path = os.path.expandvars(abs_path)\n handle = BufferedReaderWrapper(open(abs_path, \"rb\"))\n\n file = self.fs.get(md5)\n if file:\n id_ = file.id\n else:\n address = self.fs.put(abs_path)\n id_ = address.id\n source_info.append([source_name, id_, handle])\n return source_info\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n raise NotImplementedError(\n \"queued_event method is not implemented for\" \" local TinyDbObserver.\"\n )\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self.db_run_id = None\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": config,\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n\n # set ID if not given\n if _id is None:\n _id = uuid.uuid4().hex\n\n self.run_entry[\"_id\"] = _id\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.save()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = info\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = result\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.save()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.save()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save()\n\n def resource_event(self, filename):\n from .bases import BufferedReaderWrapper\n\n id_ = self.fs.put(filename).id\n handle = BufferedReaderWrapper(open(filename, \"rb\"))\n resource = [filename, id_, handle]\n\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n from .bases import BufferedReaderWrapper\n\n id_ = self.fs.put(filename).id\n handle = BufferedReaderWrapper(open(filename, \"rb\"))\n artifact = [name, filename, id_, handle]\n\n if artifact not in self.run_entry[\"artifacts\"]:\n self.run_entry[\"artifacts\"].append(artifact)\n self.save()\n\n def __eq__(self, other):\n if isinstance(other, TinyDbObserver):\n return self.runs.all() == other.runs.all()\n return False", "n_imports_parsed": 13, "n_files_resolved": 6, "n_chars_extracted": 5270, "extracted_code_full": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbObserver(RunObserver):\n\n VERSION = \"TinyDbObserver-{}\".format(__version__)\n\n @classmethod\n def create(cls, path=\"./runs_db\", overwrite=None):\n warnings.warn(\n \"TinyDbObserver.create(...) is deprecated. \"\n \"Please use TinyDbObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(path, overwrite)\n\n def __init__(self, path=\"./runs_db\", overwrite=None):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n os.makedirs(root_dir, exist_ok=True)\n\n db, fs = get_db_file_manager(root_dir)\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n self.overwrite = overwrite\n self.run_entry = {}\n self.db_run_id = None\n self.root = root_dir\n\n @classmethod\n def create_from(cls, db, fs, overwrite=None, root=None):\n \"\"\"Instantiate a TinyDbObserver with an existing db and filesystem.\"\"\"\n self = cls.__new__(cls) # skip __init__ call\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n self.overwrite = overwrite\n self.run_entry = {}\n self.db_run_id = None\n self.root = root\n return self\n\n def save(self):\n \"\"\"Insert or update the current run entry.\"\"\"\n if self.db_run_id:\n self.runs.update(self.run_entry, doc_ids=[self.db_run_id])\n else:\n db_run_id = self.runs.insert(self.run_entry)\n self.db_run_id = db_run_id\n\n def save_sources(self, ex_info):\n from .bases import BufferedReaderWrapper\n\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n\n # Substitute any HOME or Environment Vars to get absolute path\n abs_path = os.path.join(ex_info[\"base_dir\"], source_name)\n abs_path = os.path.expanduser(abs_path)\n abs_path = os.path.expandvars(abs_path)\n handle = BufferedReaderWrapper(open(abs_path, \"rb\"))\n\n file = self.fs.get(md5)\n if file:\n id_ = file.id\n else:\n address = self.fs.put(abs_path)\n id_ = address.id\n source_info.append([source_name, id_, handle])\n return source_info\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n raise NotImplementedError(\n \"queued_event method is not implemented for\" \" local TinyDbObserver.\"\n )\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self.db_run_id = None\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": config,\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n\n # set ID if not given\n if _id is None:\n _id = uuid.uuid4().hex\n\n self.run_entry[\"_id\"] = _id\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.save()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = info\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = result\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.save()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.save()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save()\n\n def resource_event(self, filename):\n from .bases import BufferedReaderWrapper\n\n id_ = self.fs.put(filename).id\n handle = BufferedReaderWrapper(open(filename, \"rb\"))\n resource = [filename, id_, handle]\n\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n from .bases import BufferedReaderWrapper\n\n id_ = self.fs.put(filename).id\n handle = BufferedReaderWrapper(open(filename, \"rb\"))\n artifact = [name, filename, id_, handle]\n\n if artifact not in self.run_entry[\"artifacts\"]:\n self.run_entry[\"artifacts\"].append(artifact)\n self.save()\n\n def __eq__(self, other):\n if isinstance(other, TinyDbObserver):\n return self.runs.all() == other.runs.all()\n return False", "n_chars_compressed": 5270, "compression_ratio": 1.0}, "tests/test_arg_parser.py::112": {"resolved_imports": ["sacred/arg_parser.py", "sacred/experiment.py"], "used_names": ["_convert_value", "pytest"], "enclosing_function": "test_convert_value", "extracted_code": "# Source: sacred/arg_parser.py\ndef _convert_value(value):\n \"\"\"Parse string as python literal if possible and fallback to string.\"\"\"\n try:\n return restore(ast.literal_eval(value))\n except (ValueError, SyntaxError):\n if SETTINGS.COMMAND_LINE.STRICT_PARSING:\n raise\n # use as string if nothing else worked\n return value", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 364, "extracted_code_full": "# Source: sacred/arg_parser.py\ndef _convert_value(value):\n \"\"\"Parse string as python literal if possible and fallback to string.\"\"\"\n try:\n return restore(ast.literal_eval(value))\n except (ValueError, SyntaxError):\n if SETTINGS.COMMAND_LINE.STRICT_PARSING:\n raise\n # use as string if nothing else worked\n return value", "n_chars_compressed": 364, "compression_ratio": 1.0}, "tests/test_commands.py::155": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["ConfigSummary", "_format_config"], "enclosing_function": "test_format_config", "extracted_code": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 2471, "extracted_code_full": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_chars_compressed": 2471, "compression_ratio": 1.0}, "tests/test_dependencies.py::187": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py", "sacred/__init__.py"], "used_names": ["PackageDependency", "Path", "SETTINGS", "Source", "gather_sources_and_dependencies", "mock", "os", "path", "pytest", "some_func"], "enclosing_function": "test_gather_sources_and_dependencies", "extracted_code": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4304, "extracted_code_full": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_chars_compressed": 4303, "compression_ratio": 0.9997676579925651}, "tests/test_dependencies.py::62": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py"], "used_names": ["PEP440_VERSION_PATTERN"], "enclosing_function": "test_pep440_version_pattern_invalid", "extracted_code": "# Source: sacred/dependencies.py\nPEP440_VERSION_PATTERN = re.compile(\n r\"\"\"\n^\n(\\d+!)? # epoch\n(\\d[.\\d]*(?<= \\d)) # release\n((?:[abc]|rc)\\d+)? # pre-release\n(?:(\\.post\\d+))? # post-release\n(?:(\\.dev\\d+))? # development release\n$\n\"\"\",\n flags=re.VERBOSE,\n)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 285, "extracted_code_full": "# Source: sacred/dependencies.py\nPEP440_VERSION_PATTERN = re.compile(\n r\"\"\"\n^\n(\\d+!)? # epoch\n(\\d[.\\d]*(?<= \\d)) # release\n((?:[abc]|rc)\\d+)? # pre-release\n(?:(\\.post\\d+))? # post-release\n(?:(\\.dev\\d+))? # development release\n$\n\"\"\",\n flags=re.VERBOSE,\n)", "n_chars_compressed": 285, "compression_ratio": 1.0}, "tests/test_host_info.py::30": {"resolved_imports": ["sacred/host_info.py"], "used_names": ["get_host_info", "host_info_gatherers", "host_info_getter"], "enclosing_function": "test_host_info_decorator", "extracted_code": "# Source: sacred/host_info.py\nhost_info_gatherers = {}\n\ndef get_host_info(additional_host_info: List[HostInfoGetter] = None):\n \"\"\"Collect some information about the machine this experiment runs on.\n\n Returns\n -------\n dict\n A dictionary with information about the CPU, the OS and the\n Python version of this machine.\n\n \"\"\"\n additional_host_info = additional_host_info or []\n # can't use += because we don't want to modify the mutable argument.\n additional_host_info = additional_host_info + _host_info_gatherers_list\n all_host_info_gatherers = host_info_gatherers.copy()\n for getter in additional_host_info:\n all_host_info_gatherers[getter.name] = getter\n host_info = {}\n for k, v in all_host_info_gatherers.items():\n try:\n host_info[k] = v()\n except IgnoreHostInfo:\n pass\n return host_info\n\ndef host_info_getter(func, name=None):\n \"\"\"\n The decorated function is added to the process of collecting the host_info.\n\n This just adds the decorated function to the global\n ``sacred.host_info.host_info_gatherers`` dictionary.\n The functions from that dictionary are used when collecting the host info\n using :py:func:`~sacred.host_info.get_host_info`.\n\n Parameters\n ----------\n func : callable\n A function that can be called without arguments and returns some\n json-serializable information.\n name : str, optional\n The name of the corresponding entry in host_info.\n Defaults to the name of the function.\n\n Returns\n -------\n The function itself.\n\n \"\"\"\n warnings.warn(\n \"The host_info_getter is deprecated. \"\n \"Please use the `additional_host_info` argument\"\n \" in the Experiment constructor.\",\n DeprecationWarning,\n )\n name = name or func.__name__\n host_info_gatherers[name] = func\n return func", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1897, "extracted_code_full": "# Source: sacred/host_info.py\nhost_info_gatherers = {}\n\ndef get_host_info(additional_host_info: List[HostInfoGetter] = None):\n \"\"\"Collect some information about the machine this experiment runs on.\n\n Returns\n -------\n dict\n A dictionary with information about the CPU, the OS and the\n Python version of this machine.\n\n \"\"\"\n additional_host_info = additional_host_info or []\n # can't use += because we don't want to modify the mutable argument.\n additional_host_info = additional_host_info + _host_info_gatherers_list\n all_host_info_gatherers = host_info_gatherers.copy()\n for getter in additional_host_info:\n all_host_info_gatherers[getter.name] = getter\n host_info = {}\n for k, v in all_host_info_gatherers.items():\n try:\n host_info[k] = v()\n except IgnoreHostInfo:\n pass\n return host_info\n\ndef host_info_getter(func, name=None):\n \"\"\"\n The decorated function is added to the process of collecting the host_info.\n\n This just adds the decorated function to the global\n ``sacred.host_info.host_info_gatherers`` dictionary.\n The functions from that dictionary are used when collecting the host info\n using :py:func:`~sacred.host_info.get_host_info`.\n\n Parameters\n ----------\n func : callable\n A function that can be called without arguments and returns some\n json-serializable information.\n name : str, optional\n The name of the corresponding entry in host_info.\n Defaults to the name of the function.\n\n Returns\n -------\n The function itself.\n\n \"\"\"\n warnings.warn(\n \"The host_info_getter is deprecated. \"\n \"Please use the `additional_host_info` argument\"\n \" in the Experiment constructor.\",\n DeprecationWarning,\n )\n name = name or func.__name__\n host_info_gatherers[name] = func\n return func", "n_chars_compressed": 1897, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::99": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_list_interface_getitem", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::55": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock", "random"], "enclosing_function": "test_captured_function_randomness", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::22": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function"], "enclosing_function": "test_create_captured_function", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_observers/test_gcs_observer.py::121": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["GoogleCloudStorageObserver"], "enclosing_function": "test_gcs_observer_equality", "extracted_code": "# Source: sacred/observers/__init__.py\nfrom sacred.observers.s3_observer import S3Observer\nfrom sacred.observers.queue import QueueObserver\nfrom sacred.observers.gcs_observer import GoogleCloudStorageObserver\n\n\n__all__ = (\n \"FileStorageObserver\",\n \"RunObserver\",\n \"MongoObserver\",\n \"QueuedMongoObserver\",\n \"SqlObserver\",\n \"TinyDbObserver\",\n\n \"S3Observer\",\n \"QueueObserver\",\n \"GoogleCloudStorageObserver\",\n)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 433, "extracted_code_full": "# Source: sacred/observers/__init__.py\nfrom sacred.observers.s3_observer import S3Observer\nfrom sacred.observers.queue import QueueObserver\nfrom sacred.observers.gcs_observer import GoogleCloudStorageObserver\n\n\n__all__ = (\n \"FileStorageObserver\",\n \"RunObserver\",\n \"MongoObserver\",\n \"QueuedMongoObserver\",\n \"SqlObserver\",\n \"TinyDbObserver\",\n\n \"S3Observer\",\n \"QueueObserver\",\n \"GoogleCloudStorageObserver\",\n)", "n_chars_compressed": 433, "compression_ratio": 1.0}, "tests/test_modules.py::47": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_ingredient_command", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_config/test_dogmatic_list.py::124": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList", "pytest"], "enclosing_function": "test_list_interface_index", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_modules.py::158": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_named_config_subingredient_overwrite", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_config/test_config_scope.py::151": {"resolved_imports": ["sacred/optional.py", "sacred/config/config_scope.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigScope", "pytest"], "enclosing_function": "test_conf_scope_handles_numpy_bools", "extracted_code": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3021, "extracted_code_full": "# Source: sacred/config/config_scope.py\nclass ConfigScope:\n def __init__(self, func):\n self.args, vararg_name, kw_wildcard, _, kwargs = get_argspec(func)\n assert vararg_name is None, \"*args not allowed for ConfigScope functions\"\n assert kw_wildcard is None, \"**kwargs not allowed for ConfigScope functions\"\n assert not kwargs, \"default values are not allowed for ConfigScope functions\"\n\n self._func = func\n self._body_code = get_function_body_code(func)\n self._var_docs = get_config_comments(func)\n self.__doc__ = self._func.__doc__\n\n def __call__(self, fixed=None, preset=None, fallback=None):\n \"\"\"\n Evaluate this ConfigScope.\n\n This will evaluate the function body and fill the relevant local\n variables into entries into keys in this dictionary.\n\n :param fixed: Dictionary of entries that should stay fixed during the\n evaluation. All of them will be part of the final config.\n :type fixed: dict\n :param preset: Dictionary of preset values that will be available\n during the evaluation (if they are declared in the\n function argument list). All of them will be part of the\n final config.\n :type preset: dict\n :param fallback: Dictionary of fallback values that will be available\n during the evaluation (if they are declared in the\n function argument list). They will NOT be part of the\n final config.\n :type fallback: dict\n :return: self\n :rtype: ConfigScope\n \"\"\"\n cfg_locals = dogmatize(fixed or {})\n fallback = fallback or {}\n preset = preset or {}\n fallback_view = {}\n\n available_entries = set(preset.keys()) | set(fallback.keys())\n\n for arg in self.args:\n if arg not in available_entries:\n raise KeyError(\n \"'{}' not in preset for ConfigScope. \"\n \"Available options are: {}\".format(arg, available_entries)\n )\n if arg in preset:\n cfg_locals[arg] = preset[arg]\n else: # arg in fallback\n fallback_view[arg] = fallback[arg]\n\n cfg_locals.fallback = fallback_view\n\n with ConfigError.track(cfg_locals):\n eval(self._body_code, copy(self._func.__globals__), cfg_locals)\n\n added = cfg_locals.revelation()\n config_summary = ConfigSummary(\n added,\n cfg_locals.modified,\n cfg_locals.typechanges,\n cfg_locals.fallback_writes,\n docs=self._var_docs,\n )\n # fill in the unused presets\n recursive_fill_in(cfg_locals, preset)\n\n for key, value in cfg_locals.items():\n try:\n config_summary[key] = normalize_or_die(value)\n except ValueError:\n pass\n return config_summary", "n_chars_compressed": 3021, "compression_ratio": 1.0}, "tests/test_ingredients.py::34": {"resolved_imports": ["sacred/config/__init__.py", "sacred/dependencies.py", "sacred/experiment.py", "sacred/ingredient.py", "sacred/utils.py", "sacred/serializer.py"], "used_names": [], "enclosing_function": "test_capture_function", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/test_metrics_logger.py::83": {"resolved_imports": ["sacred/__init__.py", "sacred/metrics_logger.py"], "used_names": [], "enclosing_function": "test_log_scalar_metric_with_implicit_step", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_config/test_signature.py::136": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature", "pytest"], "enclosing_function": "test_constructor_extract_function_name", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::21": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function"], "enclosing_function": "test_create_captured_function", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_dict.py::49": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_update_with_dict", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_modules.py::134": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_named_config_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_optional.py::17": {"resolved_imports": ["sacred/optional.py"], "used_names": ["optional_import"], "enclosing_function": "test_optional_import_nonexisting", "extracted_code": "# Source: sacred/optional.py\ndef optional_import(*package_names):\n try:\n packages = [importlib.import_module(pn) for pn in package_names]\n return True, packages[0]\n except ImportError:\n return False, None", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 231, "extracted_code_full": "# Source: sacred/optional.py\ndef optional_import(*package_names):\n try:\n packages = [importlib.import_module(pn) for pn in package_names]\n return True, packages[0]\n except ImportError:\n return False, None", "n_chars_compressed": 231, "compression_ratio": 1.0}, "tests/test_observers/test_s3_observer.py::117": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": ["S3Observer"], "enclosing_function": "test_s3_observer_equality", "extracted_code": "# Source: sacred/observers/__init__.py\nfrom sacred.observers.slack import SlackObserver\nfrom sacred.observers.telegram_obs import TelegramObserver\nfrom sacred.observers.s3_observer import S3Observer\nfrom sacred.observers.queue import QueueObserver\nfrom sacred.observers.gcs_observer import GoogleCloudStorageObserver\n\n\n__all__ = (\n \"FileStorageObserver\",\n \"RunObserver\",\n \"MongoObserver\",\n \"QueuedMongoObserver\",\n\n \"SlackObserver\",\n \"TelegramObserver\",\n \"S3Observer\",\n \"QueueObserver\",\n \"GoogleCloudStorageObserver\",\n)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 545, "extracted_code_full": "# Source: sacred/observers/__init__.py\nfrom sacred.observers.slack import SlackObserver\nfrom sacred.observers.telegram_obs import TelegramObserver\nfrom sacred.observers.s3_observer import S3Observer\nfrom sacred.observers.queue import QueueObserver\nfrom sacred.observers.gcs_observer import GoogleCloudStorageObserver\n\n\n__all__ = (\n \"FileStorageObserver\",\n \"RunObserver\",\n \"MongoObserver\",\n \"QueuedMongoObserver\",\n\n \"SlackObserver\",\n \"TelegramObserver\",\n \"S3Observer\",\n \"QueueObserver\",\n \"GoogleCloudStorageObserver\",\n)", "n_chars_compressed": 545, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::166": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature", "pytest"], "enclosing_function": "test_constructor_extract_kwargs", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_utils.py::132": {"resolved_imports": ["sacred/utils.py"], "used_names": ["get_inheritors"], "enclosing_function": "test_get_inheritors", "extracted_code": "# Source: sacred/utils.py\ndef get_inheritors(cls):\n \"\"\"Get a set of all classes that inherit from the given class.\"\"\"\n subclasses = set()\n work = [cls]\n while work:\n parent = work.pop()\n for child in parent.__subclasses__():\n if child not in subclasses:\n subclasses.add(child)\n work.append(child)\n return subclasses", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 385, "extracted_code_full": "# Source: sacred/utils.py\ndef get_inheritors(cls):\n \"\"\"Get a set of all classes that inherit from the given class.\"\"\"\n subclasses = set()\n work = [cls]\n while work:\n parent = work.pop()\n for child in parent.__subclasses__():\n if child not in subclasses:\n subclasses.add(child)\n work.append(child)\n return subclasses", "n_chars_compressed": 385, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::99": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["MongoObserver", "mock"], "enclosing_function": "test_mongo_observer_equality", "extracted_code": "# Source: sacred/observers/mongo.py\nclass MongoObserver(RunObserver):\n COLLECTION_NAME_BLACKLIST = {\n \"fs.files\",\n \"fs.chunks\",\n \"_properties\",\n \"system.indexes\",\n \"search_space\",\n \"search_spaces\",\n }\n VERSION = \"MongoObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"MongoObserver.create(...) is deprecated. \"\n \"Please use MongoObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n url: Optional[str] = None,\n db_name: str = \"sacred\",\n collection: str = \"runs\",\n collection_prefix: str = \"\",\n overwrite: Optional[Union[int, str]] = None,\n priority: int = DEFAULT_MONGO_PRIORITY,\n client: Optional[\"pymongo.MongoClient\"] = None,\n failure_dir: Optional[PathType] = None,\n **kwargs,\n ):\n \"\"\"Initializer for MongoObserver.\n\n Parameters\n ----------\n url\n Mongo URI to connect to.\n db_name\n Database to connect to.\n collection\n Collection to write the runs to. (default: \"runs\").\n **DEPRECATED**, please use collection_prefix instead.\n collection_prefix\n Prefix the runs and metrics collection,\n i.e. runs will be stored to PREFIX_runs, metrics to PREFIX_metrics.\n If empty runs are stored to 'runs', metrics to 'metrics'.\n overwrite\n _id of a run that should be overwritten.\n priority\n (default 30)\n client\n Client to connect to. Do not use client and URL together.\n failure_dir\n Directory to save the run of a failed observer to.\n \"\"\"\n import pymongo\n import gridfs\n\n if client is not None:\n if not isinstance(client, pymongo.MongoClient):\n raise ValueError(\n \"client needs to be a pymongo.MongoClient, \"\n \"but is {} instead\".format(type(client))\n )\n if url is not None:\n raise ValueError(\"Cannot pass both a client and a url.\")\n else:\n client = pymongo.MongoClient(url, **kwargs)\n\n self._client = client\n database = client[db_name]\n if collection != \"runs\":\n # the 'old' way of setting a custom collection name\n # still works as before for backward compatibility\n warnings.warn(\n 'Argument \"collection\" is deprecated. '\n 'Please use \"collection_prefix\" instead.',\n DeprecationWarning,\n )\n if collection_prefix != \"\":\n raise ValueError(\"Cannot pass both collection and a collection prefix.\")\n runs_collection_name = collection\n metrics_collection_name = \"metrics\"\n else:\n if collection_prefix != \"\":\n # separate prefix from 'runs' / 'collections' by an underscore.\n collection_prefix = \"{}_\".format(collection_prefix)\n\n runs_collection_name = \"{}runs\".format(collection_prefix)\n metrics_collection_name = \"{}metrics\".format(collection_prefix)\n\n if runs_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(runs_collection_name)\n )\n\n if metrics_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(metrics_collection_name)\n )\n\n runs_collection = database[runs_collection_name]\n metrics_collection = database[metrics_collection_name]\n fs = gridfs.GridFS(database)\n self.initialize(\n runs_collection,\n fs,\n overwrite=overwrite,\n metrics_collection=metrics_collection,\n failure_dir=failure_dir,\n priority=priority,\n )\n\n def initialize(\n self,\n runs_collection,\n fs,\n overwrite=None,\n metrics_collection=None,\n failure_dir=None,\n priority=DEFAULT_MONGO_PRIORITY,\n ):\n self.runs = runs_collection\n self.metrics = metrics_collection\n self.fs = fs\n if overwrite is not None:\n overwrite = int(overwrite)\n run = self.runs.find_one({\"_id\": overwrite})\n if run is None:\n raise RuntimeError(\n \"Couldn't find run to overwrite with \" \"_id='{}'\".format(overwrite)\n )\n else:\n overwrite = run\n self.overwrite = overwrite\n self.run_entry = None\n self.priority = priority\n self.failure_dir = failure_dir\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n if self.overwrite is not None:\n raise RuntimeError(\"Can't overwrite with QUEUED run.\")\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n # set ID if given\n if _id is not None:\n self.run_entry[\"_id\"] = _id\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n if self.overwrite is None:\n self.run_entry = {\"_id\": _id}\n else:\n if self.run_entry is not None:\n raise RuntimeError(\"Cannot overwrite more than once!\")\n # TODO sanity checks\n self.run_entry = self.overwrite\n\n self.run_entry.update(\n {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n )\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = flatten(info)\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = flatten(result)\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = flatten(result)\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.final_save(attempts=10)\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.final_save(attempts=3)\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.final_save(attempts=1)\n\n def resource_event(self, filename):\n if self.fs.exists(filename=filename):\n md5hash = get_digest(filename)\n if self.fs.exists(filename=filename, md5=md5hash):\n resource = (filename, md5hash)\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n return\n # Pymongo 4.0: GridFS removed support for md5, we now have to compute\n # it manually\n md5hash = get_digest(filename)\n self.run_entry[\"resources\"].append((filename, md5hash))\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n with open(filename, \"rb\") as f:\n run_id = self.run_entry[\"_id\"]\n db_filename = \"artifact://{}/{}/{}\".format(self.runs.name, run_id, name)\n if content_type is None:\n content_type = self._try_to_detect_content_type(filename)\n\n file_id = self.fs.put(\n f, filename=db_filename, metadata=metadata, content_type=content_type\n )\n\n self.run_entry[\"artifacts\"].append({\"name\": name, \"file_id\": file_id})\n self.save()\n\n @staticmethod\n def _try_to_detect_content_type(filename):\n mime_type, _ = mimetype_detector.guess_type(filename)\n if mime_type is not None:\n print(\n \"Added {} as content-type of artifact {}.\".format(mime_type, filename)\n )\n else:\n print(\n \"Failed to detect content-type automatically for \"\n \"artifact {}.\".format(filename)\n )\n return mime_type\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements to the database.\n\n Take measurements and store them into\n the metrics collection in the database.\n Additionally, reference the metrics\n in the info[\"metrics\"] dictionary.\n \"\"\"\n if self.metrics is None:\n # If, for whatever reason, the metrics collection has not been set\n # do not try to save anything there.\n return\n for key in metrics_by_name:\n query = {\"run_id\": self.run_entry[\"_id\"], \"name\": key}\n push = {\n \"steps\": {\"$each\": metrics_by_name[key][\"steps\"]},\n \"values\": {\"$each\": metrics_by_name[key][\"values\"]},\n \"timestamps\": {\"$each\": metrics_by_name[key][\"timestamps\"]},\n }\n update = {\"$push\": push}\n result = self.metrics.update_one(query, update, upsert=True)\n if result.upserted_id is not None:\n # This is the first time we are storing this metric\n info.setdefault(\"metrics\", []).append(\n {\"name\": key, \"id\": str(result.upserted_id)}\n )\n\n def insert(self):\n import pymongo.errors\n\n if self.overwrite:\n return self.save()\n\n autoinc_key = self.run_entry.get(\"_id\") is None\n while True:\n if autoinc_key:\n c = self.runs.find({}, {\"_id\": 1})\n c = c.sort(\"_id\", pymongo.DESCENDING).limit(1)\n self.run_entry[\"_id\"] = (\n c.next()[\"_id\"] + 1 if self.runs.count_documents({}, limit=1) else 1\n )\n try:\n self.runs.insert_one(self.run_entry)\n return\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\"\n \"(most likely in the info)\\n{}\".format(e)\n ) from e\n except pymongo.errors.DuplicateKeyError:\n if not autoinc_key:\n raise\n\n def save(self):\n import pymongo.errors\n\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]}, {\"$set\": self.run_entry}\n )\n except pymongo.errors.AutoReconnect:\n pass # just wait for the next save\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\" \"(most likely in the info)\"\n ) from e\n\n def final_save(self, attempts):\n import pymongo.errors\n\n for i in range(attempts):\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]},\n {\"$set\": self.run_entry},\n upsert=True,\n )\n return\n except pymongo.errors.AutoReconnect:\n if i < attempts - 1:\n time.sleep(1)\n except pymongo.errors.ConnectionFailure:\n pass\n except pymongo.errors.InvalidDocument:\n self.run_entry = force_bson_encodeable(self.run_entry)\n print(\n \"Warning: Some of the entries of the run were not \"\n \"BSON-serializable!\\n They have been altered such that \"\n \"they can be stored, but you should fix your experiment!\"\n \"Most likely it is either the 'info' or the 'result'.\",\n file=sys.stderr,\n )\n\n os.makedirs(self.failure_dir, exist_ok=True)\n with NamedTemporaryFile(\n suffix=\".pickle\",\n delete=False,\n prefix=\"sacred_mongo_fail_{}_\".format(self.run_entry[\"_id\"]),\n dir=self.failure_dir,\n ) as f:\n pickle.dump(self.run_entry, f)\n print(\n \"Warning: saving to MongoDB failed! \"\n \"Stored experiment entry in '{}'\".format(f.name),\n file=sys.stderr,\n )\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n abs_path = os.path.join(base_dir, source_name)\n file = self.fs.find_one({\"filename\": abs_path, \"md5\": md5})\n if file:\n _id = file._id\n else:\n with open(abs_path, \"rb\") as f:\n _id = self.fs.put(f, filename=abs_path)\n source_info.append([source_name, _id])\n return source_info\n\n def __eq__(self, other):\n if isinstance(other, MongoObserver):\n return self.runs == other.runs\n return False", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 14408, "extracted_code_full": "# Source: sacred/observers/mongo.py\nclass MongoObserver(RunObserver):\n COLLECTION_NAME_BLACKLIST = {\n \"fs.files\",\n \"fs.chunks\",\n \"_properties\",\n \"system.indexes\",\n \"search_space\",\n \"search_spaces\",\n }\n VERSION = \"MongoObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"MongoObserver.create(...) is deprecated. \"\n \"Please use MongoObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n url: Optional[str] = None,\n db_name: str = \"sacred\",\n collection: str = \"runs\",\n collection_prefix: str = \"\",\n overwrite: Optional[Union[int, str]] = None,\n priority: int = DEFAULT_MONGO_PRIORITY,\n client: Optional[\"pymongo.MongoClient\"] = None,\n failure_dir: Optional[PathType] = None,\n **kwargs,\n ):\n \"\"\"Initializer for MongoObserver.\n\n Parameters\n ----------\n url\n Mongo URI to connect to.\n db_name\n Database to connect to.\n collection\n Collection to write the runs to. (default: \"runs\").\n **DEPRECATED**, please use collection_prefix instead.\n collection_prefix\n Prefix the runs and metrics collection,\n i.e. runs will be stored to PREFIX_runs, metrics to PREFIX_metrics.\n If empty runs are stored to 'runs', metrics to 'metrics'.\n overwrite\n _id of a run that should be overwritten.\n priority\n (default 30)\n client\n Client to connect to. Do not use client and URL together.\n failure_dir\n Directory to save the run of a failed observer to.\n \"\"\"\n import pymongo\n import gridfs\n\n if client is not None:\n if not isinstance(client, pymongo.MongoClient):\n raise ValueError(\n \"client needs to be a pymongo.MongoClient, \"\n \"but is {} instead\".format(type(client))\n )\n if url is not None:\n raise ValueError(\"Cannot pass both a client and a url.\")\n else:\n client = pymongo.MongoClient(url, **kwargs)\n\n self._client = client\n database = client[db_name]\n if collection != \"runs\":\n # the 'old' way of setting a custom collection name\n # still works as before for backward compatibility\n warnings.warn(\n 'Argument \"collection\" is deprecated. '\n 'Please use \"collection_prefix\" instead.',\n DeprecationWarning,\n )\n if collection_prefix != \"\":\n raise ValueError(\"Cannot pass both collection and a collection prefix.\")\n runs_collection_name = collection\n metrics_collection_name = \"metrics\"\n else:\n if collection_prefix != \"\":\n # separate prefix from 'runs' / 'collections' by an underscore.\n collection_prefix = \"{}_\".format(collection_prefix)\n\n runs_collection_name = \"{}runs\".format(collection_prefix)\n metrics_collection_name = \"{}metrics\".format(collection_prefix)\n\n if runs_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(runs_collection_name)\n )\n\n if metrics_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(metrics_collection_name)\n )\n\n runs_collection = database[runs_collection_name]\n metrics_collection = database[metrics_collection_name]\n fs = gridfs.GridFS(database)\n self.initialize(\n runs_collection,\n fs,\n overwrite=overwrite,\n metrics_collection=metrics_collection,\n failure_dir=failure_dir,\n priority=priority,\n )\n\n def initialize(\n self,\n runs_collection,\n fs,\n overwrite=None,\n metrics_collection=None,\n failure_dir=None,\n priority=DEFAULT_MONGO_PRIORITY,\n ):\n self.runs = runs_collection\n self.metrics = metrics_collection\n self.fs = fs\n if overwrite is not None:\n overwrite = int(overwrite)\n run = self.runs.find_one({\"_id\": overwrite})\n if run is None:\n raise RuntimeError(\n \"Couldn't find run to overwrite with \" \"_id='{}'\".format(overwrite)\n )\n else:\n overwrite = run\n self.overwrite = overwrite\n self.run_entry = None\n self.priority = priority\n self.failure_dir = failure_dir\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n if self.overwrite is not None:\n raise RuntimeError(\"Can't overwrite with QUEUED run.\")\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n # set ID if given\n if _id is not None:\n self.run_entry[\"_id\"] = _id\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n if self.overwrite is None:\n self.run_entry = {\"_id\": _id}\n else:\n if self.run_entry is not None:\n raise RuntimeError(\"Cannot overwrite more than once!\")\n # TODO sanity checks\n self.run_entry = self.overwrite\n\n self.run_entry.update(\n {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n )\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = flatten(info)\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = flatten(result)\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = flatten(result)\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.final_save(attempts=10)\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.final_save(attempts=3)\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.final_save(attempts=1)\n\n def resource_event(self, filename):\n if self.fs.exists(filename=filename):\n md5hash = get_digest(filename)\n if self.fs.exists(filename=filename, md5=md5hash):\n resource = (filename, md5hash)\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n return\n # Pymongo 4.0: GridFS removed support for md5, we now have to compute\n # it manually\n md5hash = get_digest(filename)\n self.run_entry[\"resources\"].append((filename, md5hash))\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n with open(filename, \"rb\") as f:\n run_id = self.run_entry[\"_id\"]\n db_filename = \"artifact://{}/{}/{}\".format(self.runs.name, run_id, name)\n if content_type is None:\n content_type = self._try_to_detect_content_type(filename)\n\n file_id = self.fs.put(\n f, filename=db_filename, metadata=metadata, content_type=content_type\n )\n\n self.run_entry[\"artifacts\"].append({\"name\": name, \"file_id\": file_id})\n self.save()\n\n @staticmethod\n def _try_to_detect_content_type(filename):\n mime_type, _ = mimetype_detector.guess_type(filename)\n if mime_type is not None:\n print(\n \"Added {} as content-type of artifact {}.\".format(mime_type, filename)\n )\n else:\n print(\n \"Failed to detect content-type automatically for \"\n \"artifact {}.\".format(filename)\n )\n return mime_type\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements to the database.\n\n Take measurements and store them into\n the metrics collection in the database.\n Additionally, reference the metrics\n in the info[\"metrics\"] dictionary.\n \"\"\"\n if self.metrics is None:\n # If, for whatever reason, the metrics collection has not been set\n # do not try to save anything there.\n return\n for key in metrics_by_name:\n query = {\"run_id\": self.run_entry[\"_id\"], \"name\": key}\n push = {\n \"steps\": {\"$each\": metrics_by_name[key][\"steps\"]},\n \"values\": {\"$each\": metrics_by_name[key][\"values\"]},\n \"timestamps\": {\"$each\": metrics_by_name[key][\"timestamps\"]},\n }\n update = {\"$push\": push}\n result = self.metrics.update_one(query, update, upsert=True)\n if result.upserted_id is not None:\n # This is the first time we are storing this metric\n info.setdefault(\"metrics\", []).append(\n {\"name\": key, \"id\": str(result.upserted_id)}\n )\n\n def insert(self):\n import pymongo.errors\n\n if self.overwrite:\n return self.save()\n\n autoinc_key = self.run_entry.get(\"_id\") is None\n while True:\n if autoinc_key:\n c = self.runs.find({}, {\"_id\": 1})\n c = c.sort(\"_id\", pymongo.DESCENDING).limit(1)\n self.run_entry[\"_id\"] = (\n c.next()[\"_id\"] + 1 if self.runs.count_documents({}, limit=1) else 1\n )\n try:\n self.runs.insert_one(self.run_entry)\n return\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\"\n \"(most likely in the info)\\n{}\".format(e)\n ) from e\n except pymongo.errors.DuplicateKeyError:\n if not autoinc_key:\n raise\n\n def save(self):\n import pymongo.errors\n\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]}, {\"$set\": self.run_entry}\n )\n except pymongo.errors.AutoReconnect:\n pass # just wait for the next save\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\" \"(most likely in the info)\"\n ) from e\n\n def final_save(self, attempts):\n import pymongo.errors\n\n for i in range(attempts):\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]},\n {\"$set\": self.run_entry},\n upsert=True,\n )\n return\n except pymongo.errors.AutoReconnect:\n if i < attempts - 1:\n time.sleep(1)\n except pymongo.errors.ConnectionFailure:\n pass\n except pymongo.errors.InvalidDocument:\n self.run_entry = force_bson_encodeable(self.run_entry)\n print(\n \"Warning: Some of the entries of the run were not \"\n \"BSON-serializable!\\n They have been altered such that \"\n \"they can be stored, but you should fix your experiment!\"\n \"Most likely it is either the 'info' or the 'result'.\",\n file=sys.stderr,\n )\n\n os.makedirs(self.failure_dir, exist_ok=True)\n with NamedTemporaryFile(\n suffix=\".pickle\",\n delete=False,\n prefix=\"sacred_mongo_fail_{}_\".format(self.run_entry[\"_id\"]),\n dir=self.failure_dir,\n ) as f:\n pickle.dump(self.run_entry, f)\n print(\n \"Warning: saving to MongoDB failed! \"\n \"Stored experiment entry in '{}'\".format(f.name),\n file=sys.stderr,\n )\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n abs_path = os.path.join(base_dir, source_name)\n file = self.fs.find_one({\"filename\": abs_path, \"md5\": md5})\n if file:\n _id = file._id\n else:\n with open(abs_path, \"rb\") as f:\n _id = self.fs.put(f, filename=abs_path)\n source_info.append([source_name, _id])\n return source_info\n\n def __eq__(self, other):\n if isinstance(other, MongoObserver):\n return self.runs == other.runs\n return False", "n_chars_compressed": 14408, "compression_ratio": 1.0}, "tests/test_observers/test_sql_observer.py::229": {"resolved_imports": ["sacred/serializer.py", "sacred/observers/sql.py", "sacred/observers/sql_bases.py"], "used_names": ["Run", "Source", "SqlObserver"], "enclosing_function": "test_fs_observer_doesnt_duplicate_sources", "extracted_code": "# Source: sacred/observers/sql.py\nclass SqlObserver(RunObserver):\n @classmethod\n def create(cls, url, echo=False, priority=DEFAULT_SQL_PRIORITY):\n warnings.warn(\n \"SqlObserver.create(...) is deprecated. Please use\"\n \" SqlObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(url, echo, priority)\n\n def __init__(self, url, echo=False, priority=DEFAULT_SQL_PRIORITY):\n from sqlalchemy.orm import sessionmaker, scoped_session\n import sqlalchemy as sa\n\n engine = sa.create_engine(url, echo=echo)\n session_factory = sessionmaker(bind=engine)\n # make session thread-local to avoid problems with sqlite (see #275)\n session = scoped_session(session_factory)\n self.engine = engine\n self.session = session\n self.priority = priority\n self.run = None\n self.lock = Lock()\n\n @classmethod\n def create_from(cls, engine, session, priority=DEFAULT_SQL_PRIORITY):\n \"\"\"Instantiate a SqlObserver with an existing engine and session.\"\"\"\n self = cls.__new__(cls) # skip __init__ call\n self.engine = engine\n self.session = session\n self.priority = priority\n self.run = None\n self.lock = Lock()\n return self\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n return self._add_event(\n ex_info,\n command,\n host_info,\n config,\n meta_info,\n _id,\n \"RUNNING\",\n start_time=start_time,\n )\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n return self._add_event(\n ex_info, command, host_info, config, meta_info, _id, \"QUEUED\"\n )\n\n def _add_event(\n self, ex_info, command, host_info, config, meta_info, _id, status, **kwargs\n ):\n from .sql_bases import Base, Experiment, Host, Run\n\n Base.metadata.create_all(self.engine)\n sql_exp = Experiment.get_or_create(ex_info, self.session)\n sql_host = Host.get_or_create(host_info, self.session)\n if _id is None:\n i = self.session.query(Run).order_by(Run.id.desc()).first()\n _id = 0 if i is None else i.id + 1\n\n self.run = Run(\n run_id=str(_id),\n config=json.dumps(flatten(config)),\n command=command,\n priority=meta_info.get(\"priority\", 0),\n comment=meta_info.get(\"comment\", \"\"),\n experiment=sql_exp,\n host=sql_host,\n status=status,\n **kwargs,\n )\n self.session.add(self.run)\n self.save()\n return _id or self.run.run_id\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run.info = json.dumps(flatten(info))\n self.run.captured_out = captured_out\n self.run.heartbeat = beat_time\n self.run.result = result\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run.stop_time = stop_time\n self.run.result = result\n self.run.status = \"COMPLETED\"\n self.save()\n\n def interrupted_event(self, interrupt_time, status):\n self.run.stop_time = interrupt_time\n self.run.status = status\n self.save()\n\n def failed_event(self, fail_time, fail_trace):\n self.run.stop_time = fail_time\n self.run.fail_trace = \"\\n\".join(fail_trace)\n self.run.status = \"FAILED\"\n self.save()\n\n def resource_event(self, filename):\n from .sql_bases import Resource\n\n res = Resource.get_or_create(filename, self.session)\n self.run.resources.append(res)\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n from .sql_bases import Artifact\n\n a = Artifact.create(name, filename)\n self.run.artifacts.append(a)\n self.save()\n\n def save(self):\n with self.lock:\n self.session.commit()\n\n def query(self, _id):\n from .sql_bases import Run\n\n run = self.session.query(Run).filter_by(id=_id).first()\n return run.to_json()\n\n def __eq__(self, other):\n if isinstance(other, SqlObserver):\n # fixme: this will probably fail to detect two equivalent engines\n return self.engine == other.engine and self.session == other.session\n return False\n\n\n# Source: sacred/observers/sql_bases.py\nclass Source(Base):\n __tablename__ = \"source\"\n\n @classmethod\n def get_or_create(cls, filename, md5sum, session, basedir):\n instance = (\n session.query(cls).filter_by(filename=filename, md5sum=md5sum).first()\n )\n if instance:\n return instance\n full_path = os.path.join(basedir, filename)\n md5sum_ = get_digest(full_path)\n assert md5sum_ == md5sum, \"found md5 mismatch for {}: {} != {}\".format(\n filename, md5sum, md5sum_\n )\n with open(full_path, \"r\") as f:\n return cls(filename=filename, md5sum=md5sum, content=f.read())\n\n source_id = sa.Column(sa.Integer, primary_key=True)\n filename = sa.Column(sa.String(256))\n md5sum = sa.Column(sa.String(32))\n content = sa.Column(sa.Text)\n\n def to_json(self):\n return {\"filename\": self.filename, \"md5sum\": self.md5sum}\n\nclass Run(Base):\n __tablename__ = \"run\"\n id = sa.Column(sa.Integer, primary_key=True)\n\n run_id = sa.Column(sa.String(24), unique=True)\n\n command = sa.Column(sa.String(64))\n\n # times\n start_time = sa.Column(sa.DateTime)\n heartbeat = sa.Column(sa.DateTime)\n stop_time = sa.Column(sa.DateTime)\n queue_time = sa.Column(sa.DateTime)\n\n # meta info\n priority = sa.Column(sa.Float)\n comment = sa.Column(sa.Text)\n\n fail_trace = sa.Column(sa.Text)\n\n # Captured out\n # TODO: move to separate table?\n captured_out = sa.Column(sa.Text)\n\n # Configuration & info\n # TODO: switch type to json if possible\n config = sa.Column(sa.Text)\n info = sa.Column(sa.Text)\n\n status = sa.Column(\n sa.Enum(\n \"RUNNING\",\n \"COMPLETED\",\n \"INTERRUPTED\",\n \"TIMEOUT\",\n \"FAILED\",\n \"QUEUED\",\n name=\"status_enum\",\n )\n )\n\n host_id = sa.Column(sa.Integer, sa.ForeignKey(\"host.host_id\"))\n host = sa.orm.relationship(\"Host\", backref=sa.orm.backref(\"runs\"))\n\n experiment_id = sa.Column(sa.Integer, sa.ForeignKey(\"experiment.experiment_id\"))\n experiment = sa.orm.relationship(\"Experiment\", backref=sa.orm.backref(\"runs\"))\n\n # artifacts = backref\n resources = sa.orm.relationship(\n \"Resource\", secondary=run_resource_association, backref=\"runs\"\n )\n\n result = sa.Column(sa.Float)\n\n def to_json(self):\n return {\n \"_id\": self.run_id,\n \"command\": self.command,\n \"start_time\": self.start_time,\n \"heartbeat\": self.heartbeat,\n \"stop_time\": self.stop_time,\n \"queue_time\": self.queue_time,\n \"status\": self.status,\n \"result\": self.result,\n \"meta\": {\"comment\": self.comment, \"priority\": self.priority},\n \"resources\": [r.to_json() for r in self.resources],\n \"artifacts\": [a.to_json() for a in self.artifacts],\n \"host\": self.host.to_json(),\n \"experiment\": self.experiment.to_json(),\n \"config\": restore(json.loads(self.config)),\n \"captured_out\": self.captured_out,\n \"fail_trace\": self.fail_trace,\n }", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 7639, "extracted_code_full": "# Source: sacred/observers/sql.py\nclass SqlObserver(RunObserver):\n @classmethod\n def create(cls, url, echo=False, priority=DEFAULT_SQL_PRIORITY):\n warnings.warn(\n \"SqlObserver.create(...) is deprecated. Please use\"\n \" SqlObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(url, echo, priority)\n\n def __init__(self, url, echo=False, priority=DEFAULT_SQL_PRIORITY):\n from sqlalchemy.orm import sessionmaker, scoped_session\n import sqlalchemy as sa\n\n engine = sa.create_engine(url, echo=echo)\n session_factory = sessionmaker(bind=engine)\n # make session thread-local to avoid problems with sqlite (see #275)\n session = scoped_session(session_factory)\n self.engine = engine\n self.session = session\n self.priority = priority\n self.run = None\n self.lock = Lock()\n\n @classmethod\n def create_from(cls, engine, session, priority=DEFAULT_SQL_PRIORITY):\n \"\"\"Instantiate a SqlObserver with an existing engine and session.\"\"\"\n self = cls.__new__(cls) # skip __init__ call\n self.engine = engine\n self.session = session\n self.priority = priority\n self.run = None\n self.lock = Lock()\n return self\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n return self._add_event(\n ex_info,\n command,\n host_info,\n config,\n meta_info,\n _id,\n \"RUNNING\",\n start_time=start_time,\n )\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n return self._add_event(\n ex_info, command, host_info, config, meta_info, _id, \"QUEUED\"\n )\n\n def _add_event(\n self, ex_info, command, host_info, config, meta_info, _id, status, **kwargs\n ):\n from .sql_bases import Base, Experiment, Host, Run\n\n Base.metadata.create_all(self.engine)\n sql_exp = Experiment.get_or_create(ex_info, self.session)\n sql_host = Host.get_or_create(host_info, self.session)\n if _id is None:\n i = self.session.query(Run).order_by(Run.id.desc()).first()\n _id = 0 if i is None else i.id + 1\n\n self.run = Run(\n run_id=str(_id),\n config=json.dumps(flatten(config)),\n command=command,\n priority=meta_info.get(\"priority\", 0),\n comment=meta_info.get(\"comment\", \"\"),\n experiment=sql_exp,\n host=sql_host,\n status=status,\n **kwargs,\n )\n self.session.add(self.run)\n self.save()\n return _id or self.run.run_id\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run.info = json.dumps(flatten(info))\n self.run.captured_out = captured_out\n self.run.heartbeat = beat_time\n self.run.result = result\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run.stop_time = stop_time\n self.run.result = result\n self.run.status = \"COMPLETED\"\n self.save()\n\n def interrupted_event(self, interrupt_time, status):\n self.run.stop_time = interrupt_time\n self.run.status = status\n self.save()\n\n def failed_event(self, fail_time, fail_trace):\n self.run.stop_time = fail_time\n self.run.fail_trace = \"\\n\".join(fail_trace)\n self.run.status = \"FAILED\"\n self.save()\n\n def resource_event(self, filename):\n from .sql_bases import Resource\n\n res = Resource.get_or_create(filename, self.session)\n self.run.resources.append(res)\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n from .sql_bases import Artifact\n\n a = Artifact.create(name, filename)\n self.run.artifacts.append(a)\n self.save()\n\n def save(self):\n with self.lock:\n self.session.commit()\n\n def query(self, _id):\n from .sql_bases import Run\n\n run = self.session.query(Run).filter_by(id=_id).first()\n return run.to_json()\n\n def __eq__(self, other):\n if isinstance(other, SqlObserver):\n # fixme: this will probably fail to detect two equivalent engines\n return self.engine == other.engine and self.session == other.session\n return False\n\n\n# Source: sacred/observers/sql_bases.py\nclass Source(Base):\n __tablename__ = \"source\"\n\n @classmethod\n def get_or_create(cls, filename, md5sum, session, basedir):\n instance = (\n session.query(cls).filter_by(filename=filename, md5sum=md5sum).first()\n )\n if instance:\n return instance\n full_path = os.path.join(basedir, filename)\n md5sum_ = get_digest(full_path)\n assert md5sum_ == md5sum, \"found md5 mismatch for {}: {} != {}\".format(\n filename, md5sum, md5sum_\n )\n with open(full_path, \"r\") as f:\n return cls(filename=filename, md5sum=md5sum, content=f.read())\n\n source_id = sa.Column(sa.Integer, primary_key=True)\n filename = sa.Column(sa.String(256))\n md5sum = sa.Column(sa.String(32))\n content = sa.Column(sa.Text)\n\n def to_json(self):\n return {\"filename\": self.filename, \"md5sum\": self.md5sum}\n\nclass Run(Base):\n __tablename__ = \"run\"\n id = sa.Column(sa.Integer, primary_key=True)\n\n run_id = sa.Column(sa.String(24), unique=True)\n\n command = sa.Column(sa.String(64))\n\n # times\n start_time = sa.Column(sa.DateTime)\n heartbeat = sa.Column(sa.DateTime)\n stop_time = sa.Column(sa.DateTime)\n queue_time = sa.Column(sa.DateTime)\n\n # meta info\n priority = sa.Column(sa.Float)\n comment = sa.Column(sa.Text)\n\n fail_trace = sa.Column(sa.Text)\n\n # Captured out\n # TODO: move to separate table?\n captured_out = sa.Column(sa.Text)\n\n # Configuration & info\n # TODO: switch type to json if possible\n config = sa.Column(sa.Text)\n info = sa.Column(sa.Text)\n\n status = sa.Column(\n sa.Enum(\n \"RUNNING\",\n \"COMPLETED\",\n \"INTERRUPTED\",\n \"TIMEOUT\",\n \"FAILED\",\n \"QUEUED\",\n name=\"status_enum\",\n )\n )\n\n host_id = sa.Column(sa.Integer, sa.ForeignKey(\"host.host_id\"))\n host = sa.orm.relationship(\"Host\", backref=sa.orm.backref(\"runs\"))\n\n experiment_id = sa.Column(sa.Integer, sa.ForeignKey(\"experiment.experiment_id\"))\n experiment = sa.orm.relationship(\"Experiment\", backref=sa.orm.backref(\"runs\"))\n\n # artifacts = backref\n resources = sa.orm.relationship(\n \"Resource\", secondary=run_resource_association, backref=\"runs\"\n )\n\n result = sa.Column(sa.Float)\n\n def to_json(self):\n return {\n \"_id\": self.run_id,\n \"command\": self.command,\n \"start_time\": self.start_time,\n \"heartbeat\": self.heartbeat,\n \"stop_time\": self.stop_time,\n \"queue_time\": self.queue_time,\n \"status\": self.status,\n \"result\": self.result,\n \"meta\": {\"comment\": self.comment, \"priority\": self.priority},\n \"resources\": [r.to_json() for r in self.resources],\n \"artifacts\": [a.to_json() for a in self.artifacts],\n \"host\": self.host.to_json(),\n \"experiment\": self.experiment.to_json(),\n \"config\": restore(json.loads(self.config)),\n \"captured_out\": self.captured_out,\n \"fail_trace\": self.fail_trace,\n }", "n_chars_compressed": 7639, "compression_ratio": 1.0}, "tests/test_serializer.py::46": {"resolved_imports": ["sacred/serializer.py", "sacred/optional.py"], "used_names": ["flatten", "restore"], "enclosing_function": "test_serialize_non_str_keys", "extracted_code": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 193, "extracted_code_full": "# Source: sacred/serializer.py\ndef flatten(obj):\n return _json.loads(json.encode(obj, keys=True))\n\ndef restore(flat):\n return json.decode(_json.dumps(flat), keys=True, on_missing=\"error\")", "n_chars_compressed": 193, "compression_ratio": 1.0}, "tests/test_observers/test_file_storage_observer.py::113": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["os"], "enclosing_function": "test_fs_observer_started_event_creates_rundir_with_filesystem_delay", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_dependencies.py::195": {"resolved_imports": ["sacred/dependencies.py", "sacred/optional.py", "sacred/__init__.py"], "used_names": ["PackageDependency", "Path", "SETTINGS", "Source", "gather_sources_and_dependencies", "mock", "os", "path", "pytest", "some_func"], "enclosing_function": "test_gather_sources_and_dependencies", "extracted_code": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 4304, "extracted_code_full": "# Source: sacred/dependencies.py\nclass Source:\n def __init__(self, filename, digest, repo, commit, isdirty):\n self.filename = os.path.realpath(filename)\n self.digest = digest\n self.repo = repo\n self.commit = commit\n self.is_dirty = isdirty\n\n @staticmethod\n def create(filename, save_git_info=True):\n if not filename or not os.path.exists(filename):\n raise ValueError('invalid filename or file not found \"{}\"'.format(filename))\n\n main_file = get_py_file_if_possible(os.path.abspath(filename))\n repo, commit, is_dirty = get_commit_if_possible(main_file, save_git_info)\n return Source(main_file, get_digest(main_file), repo, commit, is_dirty)\n\n def to_json(self, base_dir=None):\n if base_dir:\n return (\n os.path.relpath(self.filename, os.path.realpath(base_dir)),\n self.digest,\n )\n else:\n return self.filename, self.digest\n\n def __hash__(self):\n return hash(self.filename)\n\n def __eq__(self, other):\n if isinstance(other, Source):\n return self.filename == other.filename\n elif isinstance(other, str):\n return self.filename == other\n else:\n return False\n\n def __le__(self, other):\n return self.filename.__le__(other.filename)\n\n def __repr__(self):\n return \"\".format(self.filename)\n\nclass PackageDependency:\n modname_to_dist = {}\n\n def __init__(self, name, version):\n self.name = name\n self.version = version\n\n def fill_missing_version(self):\n if self.version is not None:\n return\n dist = pkg_resources.working_set.by_key.get(self.name)\n self.version = dist.version if dist else None\n\n def to_json(self):\n return \"{}=={}\".format(self.name, self.version or \"\")\n\n def __hash__(self):\n return hash(self.name)\n\n def __eq__(self, other):\n if isinstance(other, PackageDependency):\n return self.name == other.name\n else:\n return False\n\n def __le__(self, other):\n return self.name.__le__(other.name)\n\n def __repr__(self):\n return \"\".format(self.name, self.version)\n\n @classmethod\n def create(cls, mod):\n if not cls.modname_to_dist:\n # some packagenames don't match the module names (e.g. PyYAML)\n # so we set up a dict to map from module name to package name\n for dist in pkg_resources.working_set:\n try:\n toplevel_names = dist._get_metadata(\"top_level.txt\")\n for tln in toplevel_names:\n cls.modname_to_dist[tln] = dist.project_name, dist.version\n except Exception:\n pass\n\n name, version = cls.modname_to_dist.get(mod.__name__, (mod.__name__, None))\n\n return PackageDependency(name, version)\n\ndef gather_sources_and_dependencies(globs, save_git_info, base_dir=None):\n \"\"\"Scan the given globals for modules and return them as dependencies.\"\"\"\n experiment_path, main = get_main_file(globs, save_git_info)\n\n base_dir = base_dir or experiment_path\n\n gather_sources = source_discovery_strategies[SETTINGS[\"DISCOVER_SOURCES\"]]\n sources = gather_sources(globs, base_dir, save_git_info)\n if main is not None:\n sources.add(main)\n\n gather_dependencies = dependency_discovery_strategies[\n SETTINGS[\"DISCOVER_DEPENDENCIES\"]\n ]\n dependencies = gather_dependencies(globs, base_dir)\n\n if opt.has_numpy:\n # Add numpy as a dependency because it might be used for randomness\n dependencies.add(PackageDependency.create(opt.np))\n\n return main, sources, dependencies\n\n\n# Source: sacred/__init__.py\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n \"cli_option\",\n)", "n_chars_compressed": 4303, "compression_ratio": 0.9997676579925651}, "tests/test_config/test_config_dict.py::36": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_config_dict_result_contains_keys", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_config/test_readonly_containers.py::33": {"resolved_imports": ["sacred/config/custom_containers.py", "sacred/utils.py"], "used_names": ["json", "pickle"], "enclosing_function": "_check_serializable", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_observers/test_tinydb_reader.py::297": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader", "datetime", "io"], "enclosing_function": "test_fetch_files_function", "extracted_code": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6248, "extracted_code_full": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6248, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::25": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_append", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_utils.py::198": {"resolved_imports": ["sacred/utils.py"], "used_names": ["parse_version"], "enclosing_function": "test_parse_version", "extracted_code": "# Source: sacred/utils.py\ndef parse_version(version_string):\n \"\"\"Returns a parsed version string.\"\"\"\n return version.parse(version_string)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 144, "extracted_code_full": "# Source: sacred/utils.py\ndef parse_version(version_string):\n \"\"\"Returns a parsed version string.\"\"\"\n return version.parse(version_string)", "n_chars_compressed": 144, "compression_ratio": 1.0}, "tests/test_commands.py::158": {"resolved_imports": ["sacred/__init__.py", "sacred/commands.py", "sacred/config/__init__.py", "sacred/config/config_summary.py", "sacred/optional.py"], "used_names": ["ConfigSummary", "_format_config"], "enclosing_function": "test_format_config", "extracted_code": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_imports_parsed": 12, "n_files_resolved": 5, "n_chars_extracted": 2471, "extracted_code_full": "# Source: sacred/commands.py\ndef _format_config(cfg, config_mods):\n lines = [\"Configuration \" + LEGEND + \":\"]\n for path, entry in _iterate_marked(cfg, config_mods):\n indent = 2 + 2 * path.count(\".\")\n lines.append(_format_entry(indent, entry))\n return \"\\n\".join(lines)\n\n\n# Source: sacred/config/config_summary.py\nclass ConfigSummary(dict):\n def __init__(\n self, added=(), modified=(), typechanged=(), ignored_fallbacks=(), docs=()\n ):\n super().__init__()\n self.added = set(added)\n self.modified = set(modified) # TODO: test for this member\n self.typechanged = dict(typechanged)\n self.ignored_fallbacks = set(ignored_fallbacks) # TODO: test\n self.docs = dict(docs)\n self.ensure_coherence()\n\n def update_from(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added &= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.ensure_coherence()\n for k, v in config_mod.docs.items():\n if not self.docs.get(k, \"\"):\n self.docs[k] = v\n\n def update_add(self, config_mod, path=\"\"):\n added = config_mod.added\n updated = config_mod.modified\n typechanged = config_mod.typechanged\n self.added |= {join_paths(path, a) for a in added}\n self.modified |= {join_paths(path, u) for u in updated}\n self.typechanged.update(\n {join_paths(path, k): v for k, v in typechanged.items()}\n )\n self.docs.update(\n {\n join_paths(path, k): v\n for k, v in config_mod.docs.items()\n if path == \"\" or k != \"seed\"\n }\n )\n self.ensure_coherence()\n\n def ensure_coherence(self):\n # make sure parent paths show up as updated appropriately\n self.modified |= {p for a in self.added for p in iter_prefixes(a)}\n self.modified |= {p for u in self.modified for p in iter_prefixes(u)}\n self.modified |= {p for t in self.typechanged for p in iter_prefixes(t)}\n\n # make sure there is no overlap\n self.added -= set(self.typechanged.keys())\n self.modified -= set(self.typechanged.keys())\n self.modified -= self.added", "n_chars_compressed": 2471, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_dict.py::25": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_set_item", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_modules.py::78": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_run_access_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_observers/test_file_storage_observer.py::356": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["json", "linearize_metrics"], "enclosing_function": "test_log_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 1080, "extracted_code_full": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1080, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::63": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_started_event_creates_run", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_file_storage_observer.py::107": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["os"], "enclosing_function": "test_fs_observer_started_event_creates_rundir_with_filesystem_delay", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_config/test_config_scope_chain.py::83": {"resolved_imports": ["sacred/config/__init__.py"], "used_names": ["ConfigScope", "chain_evaluate_config_scopes"], "enclosing_function": "test_chained_config_scopes_cannot_modify_fixed", "extracted_code": "# Source: sacred/config/__init__.py\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1209, "extracted_code_full": "# Source: sacred/config/__init__.py\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)\n\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 1208, "compression_ratio": 0.9991728701406121}, "tests/test_config/test_signature.py::171": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_get_free_parameters", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::53": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict", "pytest"], "enclosing_function": "test_config_dict_accepts_special_types", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_config/test_dogmatic_list.py::97": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticList"], "enclosing_function": "test_list_interface_getitem", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 932, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticList(list):\n def append(self, p_object):\n pass\n\n def extend(self, iterable):\n pass\n\n def insert(self, index, p_object):\n pass\n\n def reverse(self):\n pass\n\n def sort(self, compare=None, key=None, reverse=False):\n pass\n\n def __iadd__(self, other):\n return self\n\n def __imul__(self, other):\n return self\n\n def __setitem__(self, key, value):\n pass\n\n def __setslice__(self, i, j, sequence):\n pass\n\n def __delitem__(self, key):\n pass\n\n def __delslice__(self, i, j):\n pass\n\n def pop(self, index=None):\n raise TypeError(\"Cannot pop from DogmaticList\")\n\n def remove(self, value):\n pass\n\n def revelation(self):\n for obj in self:\n if isinstance(obj, (DogmaticDict, DogmaticList)):\n obj.revelation()\n return set()", "n_chars_compressed": 932, "compression_ratio": 1.0}, "tests/test_utils.py::74": {"resolved_imports": ["sacred/utils.py"], "used_names": ["get_by_dotted_path"], "enclosing_function": "test_get_by_dotted_path", "extracted_code": "# Source: sacred/utils.py\ndef get_by_dotted_path(d, path, default=None):\n \"\"\"\n Get an entry from nested dictionaries using a dotted path.\n\n Example\n -------\n >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')\n 12\n \"\"\"\n if not path:\n return d\n split_path = path.split(\".\")\n current_option = d\n for p in split_path:\n if p not in current_option:\n return default\n current_option = current_option[p]\n return current_option", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 486, "extracted_code_full": "# Source: sacred/utils.py\ndef get_by_dotted_path(d, path, default=None):\n \"\"\"\n Get an entry from nested dictionaries using a dotted path.\n\n Example\n -------\n >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')\n 12\n \"\"\"\n if not path:\n return d\n split_path = path.split(\".\")\n current_option = d\n for p in split_path:\n if p not in current_option:\n return default\n current_option = current_option[p]\n return current_option", "n_chars_compressed": 486, "compression_ratio": 1.0}, "tests/test_config/test_fallback_dict.py::26": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fallback", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config/test_config_scope.py::69": {"resolved_imports": ["sacred/optional.py", "sacred/config/config_scope.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_result_of_config_scope_contains_keys", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_examples.py::25": {"resolved_imports": [], "used_names": ["logging"], "enclosing_function": "test_example", "extracted_code": "", "n_imports_parsed": 1, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_observers/test_file_storage_observer.py::258": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["json"], "enclosing_function": "test_fs_observer_artifact_event", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_observers/test_tinydb_reader.py::343": {"resolved_imports": ["sacred/dependencies.py", "sacred/observers/tinydb_hashfs/tinydb_hashfs.py"], "used_names": ["TinyDbReader"], "enclosing_function": "test_fetch_report_function", "extracted_code": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 6248, "extracted_code_full": "# Source: sacred/observers/tinydb_hashfs/tinydb_hashfs.py\nclass TinyDbReader:\n def __init__(self, path):\n from .bases import get_db_file_manager\n\n root_dir = os.path.abspath(path)\n if not os.path.exists(root_dir):\n raise IOError(\"Path does not exist: %s\" % path)\n\n db, fs = get_db_file_manager(root_dir)\n\n self.db = db\n self.runs = db.table(\"runs\")\n self.fs = fs\n\n def search(self, *args, **kwargs):\n \"\"\"Wrapper to TinyDB's search function.\"\"\"\n return self.runs.search(*args, **kwargs)\n\n def fetch_files(self, exp_name=None, query=None, indices=None):\n \"\"\"Return Dictionary of files for experiment name or query.\n\n Returns a list of one dictionary per matched experiment. The\n dictionary is of the following structure\n\n {\n 'exp_name': 'scascasc',\n 'exp_id': 'dqwdqdqwf',\n 'date': datatime_object,\n 'sources': [ {'filename': filehandle}, ..., ],\n 'resources': [ {'filename': filehandle}, ..., ],\n 'artifacts': [ {'filename': filehandle}, ..., ]\n }\n\n \"\"\"\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n date=ent[\"start_time\"],\n )\n\n source_files = {x[0]: x[2] for x in ent[\"experiment\"][\"sources\"]}\n resource_files = {x[0]: x[2] for x in ent[\"resources\"]}\n artifact_files = {x[0]: x[3] for x in ent[\"artifacts\"]}\n\n if source_files:\n rec[\"sources\"] = source_files\n if resource_files:\n rec[\"resources\"] = resource_files\n if artifact_files:\n rec[\"artifacts\"] = artifact_files\n\n all_matched_entries.append(rec)\n\n return all_matched_entries\n\n def fetch_report(self, exp_name=None, query=None, indices=None):\n\n template = \"\"\"\n-------------------------------------------------\nExperiment: {exp_name}\n-------------------------------------------------\nID: {exp_id}\nDate: {start_date} Duration: {duration}\n\nParameters:\n{parameters}\n\nResult:\n{result}\n\nDependencies:\n{dependencies}\n\nResources:\n{resources}\n\nSource Files:\n{sources}\n\nOutputs:\n{artifacts}\n\"\"\"\n\n entries = self.fetch_metadata(exp_name, query, indices)\n\n all_matched_entries = []\n for ent in entries:\n\n date = ent[\"start_time\"]\n weekdays = \"Mon Tue Wed Thu Fri Sat Sun\".split()\n w = weekdays[date.weekday()]\n date = \" \".join([w, date.strftime(\"%d %b %Y\")])\n\n duration = ent[\"stop_time\"] - ent[\"start_time\"]\n secs = duration.total_seconds()\n hours, remainder = divmod(secs, 3600)\n minutes, seconds = divmod(remainder, 60)\n duration = \"%02d:%02d:%04.1f\" % (hours, minutes, seconds)\n\n parameters = self._dict_to_indented_list(ent[\"config\"])\n\n result = self._indent(ent[\"result\"].__repr__(), prefix=\" \")\n\n deps = ent[\"experiment\"][\"dependencies\"]\n deps = self._indent(\"\\n\".join(deps), prefix=\" \")\n\n resources = [x[0] for x in ent[\"resources\"]]\n resources = self._indent(\"\\n\".join(resources), prefix=\" \")\n\n sources = [x[0] for x in ent[\"experiment\"][\"sources\"]]\n sources = self._indent(\"\\n\".join(sources), prefix=\" \")\n\n artifacts = [x[0] for x in ent[\"artifacts\"]]\n artifacts = self._indent(\"\\n\".join(artifacts), prefix=\" \")\n\n none_str = \" None\"\n\n rec = dict(\n exp_name=ent[\"experiment\"][\"name\"],\n exp_id=ent[\"_id\"],\n start_date=date,\n duration=duration,\n parameters=parameters if parameters else none_str,\n result=result if result else none_str,\n dependencies=deps if deps else none_str,\n resources=resources if resources else none_str,\n sources=sources if sources else none_str,\n artifacts=artifacts if artifacts else none_str,\n )\n\n report = template.format(**rec)\n\n all_matched_entries.append(report)\n\n return all_matched_entries\n\n def fetch_metadata(self, exp_name=None, query=None, indices=None):\n \"\"\"Return all metadata for matching experiment name, index or query.\"\"\"\n from tinydb import Query\n\n if exp_name or query:\n if query:\n q = query\n elif exp_name:\n q = Query().experiment.name.search(exp_name)\n\n entries = self.runs.search(q)\n\n elif indices or indices == 0:\n if not isinstance(indices, (tuple, list)):\n indices = [indices]\n\n num_recs = len(self.runs)\n\n for idx in indices:\n if idx >= num_recs:\n raise ValueError(\n \"Index value ({}) must be less than \"\n \"number of records ({})\".format(idx, num_recs)\n )\n\n entries = [self.runs.all()[ind] for ind in indices]\n\n else:\n raise ValueError(\n \"Must specify an experiment name, indicies or \" \"pass custom query\"\n )\n\n return entries\n\n def _dict_to_indented_list(self, d):\n\n d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))\n\n output_str = \"\"\n\n for k, v in d.items():\n output_str += \"%s: %s\" % (k, v)\n output_str += \"\\n\"\n\n output_str = self._indent(output_str.strip(), prefix=\" \")\n\n return output_str\n\n def _indent(self, message, prefix):\n \"\"\"Wrapper for indenting strings in Python 2 and 3.\"\"\"\n preferred_width = 150\n wrapper = textwrap.TextWrapper(\n initial_indent=prefix, width=preferred_width, subsequent_indent=prefix\n )\n\n lines = message.splitlines()\n formatted_lines = [wrapper.fill(lin) for lin in lines]\n formatted_text = \"\\n\".join(formatted_lines)\n\n return formatted_text", "n_chars_compressed": 6248, "compression_ratio": 1.0}, "tests/test_observers/test_mongo_observer.py::158": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["MongoObserver", "mock"], "enclosing_function": "test_mongo_observer_equality", "extracted_code": "# Source: sacred/observers/mongo.py\nclass MongoObserver(RunObserver):\n COLLECTION_NAME_BLACKLIST = {\n \"fs.files\",\n \"fs.chunks\",\n \"_properties\",\n \"system.indexes\",\n \"search_space\",\n \"search_spaces\",\n }\n VERSION = \"MongoObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"MongoObserver.create(...) is deprecated. \"\n \"Please use MongoObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n url: Optional[str] = None,\n db_name: str = \"sacred\",\n collection: str = \"runs\",\n collection_prefix: str = \"\",\n overwrite: Optional[Union[int, str]] = None,\n priority: int = DEFAULT_MONGO_PRIORITY,\n client: Optional[\"pymongo.MongoClient\"] = None,\n failure_dir: Optional[PathType] = None,\n **kwargs,\n ):\n \"\"\"Initializer for MongoObserver.\n\n Parameters\n ----------\n url\n Mongo URI to connect to.\n db_name\n Database to connect to.\n collection\n Collection to write the runs to. (default: \"runs\").\n **DEPRECATED**, please use collection_prefix instead.\n collection_prefix\n Prefix the runs and metrics collection,\n i.e. runs will be stored to PREFIX_runs, metrics to PREFIX_metrics.\n If empty runs are stored to 'runs', metrics to 'metrics'.\n overwrite\n _id of a run that should be overwritten.\n priority\n (default 30)\n client\n Client to connect to. Do not use client and URL together.\n failure_dir\n Directory to save the run of a failed observer to.\n \"\"\"\n import pymongo\n import gridfs\n\n if client is not None:\n if not isinstance(client, pymongo.MongoClient):\n raise ValueError(\n \"client needs to be a pymongo.MongoClient, \"\n \"but is {} instead\".format(type(client))\n )\n if url is not None:\n raise ValueError(\"Cannot pass both a client and a url.\")\n else:\n client = pymongo.MongoClient(url, **kwargs)\n\n self._client = client\n database = client[db_name]\n if collection != \"runs\":\n # the 'old' way of setting a custom collection name\n # still works as before for backward compatibility\n warnings.warn(\n 'Argument \"collection\" is deprecated. '\n 'Please use \"collection_prefix\" instead.',\n DeprecationWarning,\n )\n if collection_prefix != \"\":\n raise ValueError(\"Cannot pass both collection and a collection prefix.\")\n runs_collection_name = collection\n metrics_collection_name = \"metrics\"\n else:\n if collection_prefix != \"\":\n # separate prefix from 'runs' / 'collections' by an underscore.\n collection_prefix = \"{}_\".format(collection_prefix)\n\n runs_collection_name = \"{}runs\".format(collection_prefix)\n metrics_collection_name = \"{}metrics\".format(collection_prefix)\n\n if runs_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(runs_collection_name)\n )\n\n if metrics_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(metrics_collection_name)\n )\n\n runs_collection = database[runs_collection_name]\n metrics_collection = database[metrics_collection_name]\n fs = gridfs.GridFS(database)\n self.initialize(\n runs_collection,\n fs,\n overwrite=overwrite,\n metrics_collection=metrics_collection,\n failure_dir=failure_dir,\n priority=priority,\n )\n\n def initialize(\n self,\n runs_collection,\n fs,\n overwrite=None,\n metrics_collection=None,\n failure_dir=None,\n priority=DEFAULT_MONGO_PRIORITY,\n ):\n self.runs = runs_collection\n self.metrics = metrics_collection\n self.fs = fs\n if overwrite is not None:\n overwrite = int(overwrite)\n run = self.runs.find_one({\"_id\": overwrite})\n if run is None:\n raise RuntimeError(\n \"Couldn't find run to overwrite with \" \"_id='{}'\".format(overwrite)\n )\n else:\n overwrite = run\n self.overwrite = overwrite\n self.run_entry = None\n self.priority = priority\n self.failure_dir = failure_dir\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n if self.overwrite is not None:\n raise RuntimeError(\"Can't overwrite with QUEUED run.\")\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n # set ID if given\n if _id is not None:\n self.run_entry[\"_id\"] = _id\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n if self.overwrite is None:\n self.run_entry = {\"_id\": _id}\n else:\n if self.run_entry is not None:\n raise RuntimeError(\"Cannot overwrite more than once!\")\n # TODO sanity checks\n self.run_entry = self.overwrite\n\n self.run_entry.update(\n {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n )\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = flatten(info)\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = flatten(result)\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = flatten(result)\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.final_save(attempts=10)\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.final_save(attempts=3)\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.final_save(attempts=1)\n\n def resource_event(self, filename):\n if self.fs.exists(filename=filename):\n md5hash = get_digest(filename)\n if self.fs.exists(filename=filename, md5=md5hash):\n resource = (filename, md5hash)\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n return\n # Pymongo 4.0: GridFS removed support for md5, we now have to compute\n # it manually\n md5hash = get_digest(filename)\n self.run_entry[\"resources\"].append((filename, md5hash))\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n with open(filename, \"rb\") as f:\n run_id = self.run_entry[\"_id\"]\n db_filename = \"artifact://{}/{}/{}\".format(self.runs.name, run_id, name)\n if content_type is None:\n content_type = self._try_to_detect_content_type(filename)\n\n file_id = self.fs.put(\n f, filename=db_filename, metadata=metadata, content_type=content_type\n )\n\n self.run_entry[\"artifacts\"].append({\"name\": name, \"file_id\": file_id})\n self.save()\n\n @staticmethod\n def _try_to_detect_content_type(filename):\n mime_type, _ = mimetype_detector.guess_type(filename)\n if mime_type is not None:\n print(\n \"Added {} as content-type of artifact {}.\".format(mime_type, filename)\n )\n else:\n print(\n \"Failed to detect content-type automatically for \"\n \"artifact {}.\".format(filename)\n )\n return mime_type\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements to the database.\n\n Take measurements and store them into\n the metrics collection in the database.\n Additionally, reference the metrics\n in the info[\"metrics\"] dictionary.\n \"\"\"\n if self.metrics is None:\n # If, for whatever reason, the metrics collection has not been set\n # do not try to save anything there.\n return\n for key in metrics_by_name:\n query = {\"run_id\": self.run_entry[\"_id\"], \"name\": key}\n push = {\n \"steps\": {\"$each\": metrics_by_name[key][\"steps\"]},\n \"values\": {\"$each\": metrics_by_name[key][\"values\"]},\n \"timestamps\": {\"$each\": metrics_by_name[key][\"timestamps\"]},\n }\n update = {\"$push\": push}\n result = self.metrics.update_one(query, update, upsert=True)\n if result.upserted_id is not None:\n # This is the first time we are storing this metric\n info.setdefault(\"metrics\", []).append(\n {\"name\": key, \"id\": str(result.upserted_id)}\n )\n\n def insert(self):\n import pymongo.errors\n\n if self.overwrite:\n return self.save()\n\n autoinc_key = self.run_entry.get(\"_id\") is None\n while True:\n if autoinc_key:\n c = self.runs.find({}, {\"_id\": 1})\n c = c.sort(\"_id\", pymongo.DESCENDING).limit(1)\n self.run_entry[\"_id\"] = (\n c.next()[\"_id\"] + 1 if self.runs.count_documents({}, limit=1) else 1\n )\n try:\n self.runs.insert_one(self.run_entry)\n return\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\"\n \"(most likely in the info)\\n{}\".format(e)\n ) from e\n except pymongo.errors.DuplicateKeyError:\n if not autoinc_key:\n raise\n\n def save(self):\n import pymongo.errors\n\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]}, {\"$set\": self.run_entry}\n )\n except pymongo.errors.AutoReconnect:\n pass # just wait for the next save\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\" \"(most likely in the info)\"\n ) from e\n\n def final_save(self, attempts):\n import pymongo.errors\n\n for i in range(attempts):\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]},\n {\"$set\": self.run_entry},\n upsert=True,\n )\n return\n except pymongo.errors.AutoReconnect:\n if i < attempts - 1:\n time.sleep(1)\n except pymongo.errors.ConnectionFailure:\n pass\n except pymongo.errors.InvalidDocument:\n self.run_entry = force_bson_encodeable(self.run_entry)\n print(\n \"Warning: Some of the entries of the run were not \"\n \"BSON-serializable!\\n They have been altered such that \"\n \"they can be stored, but you should fix your experiment!\"\n \"Most likely it is either the 'info' or the 'result'.\",\n file=sys.stderr,\n )\n\n os.makedirs(self.failure_dir, exist_ok=True)\n with NamedTemporaryFile(\n suffix=\".pickle\",\n delete=False,\n prefix=\"sacred_mongo_fail_{}_\".format(self.run_entry[\"_id\"]),\n dir=self.failure_dir,\n ) as f:\n pickle.dump(self.run_entry, f)\n print(\n \"Warning: saving to MongoDB failed! \"\n \"Stored experiment entry in '{}'\".format(f.name),\n file=sys.stderr,\n )\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n abs_path = os.path.join(base_dir, source_name)\n file = self.fs.find_one({\"filename\": abs_path, \"md5\": md5})\n if file:\n _id = file._id\n else:\n with open(abs_path, \"rb\") as f:\n _id = self.fs.put(f, filename=abs_path)\n source_info.append([source_name, _id])\n return source_info\n\n def __eq__(self, other):\n if isinstance(other, MongoObserver):\n return self.runs == other.runs\n return False", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 14408, "extracted_code_full": "# Source: sacred/observers/mongo.py\nclass MongoObserver(RunObserver):\n COLLECTION_NAME_BLACKLIST = {\n \"fs.files\",\n \"fs.chunks\",\n \"_properties\",\n \"system.indexes\",\n \"search_space\",\n \"search_spaces\",\n }\n VERSION = \"MongoObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"MongoObserver.create(...) is deprecated. \"\n \"Please use MongoObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n url: Optional[str] = None,\n db_name: str = \"sacred\",\n collection: str = \"runs\",\n collection_prefix: str = \"\",\n overwrite: Optional[Union[int, str]] = None,\n priority: int = DEFAULT_MONGO_PRIORITY,\n client: Optional[\"pymongo.MongoClient\"] = None,\n failure_dir: Optional[PathType] = None,\n **kwargs,\n ):\n \"\"\"Initializer for MongoObserver.\n\n Parameters\n ----------\n url\n Mongo URI to connect to.\n db_name\n Database to connect to.\n collection\n Collection to write the runs to. (default: \"runs\").\n **DEPRECATED**, please use collection_prefix instead.\n collection_prefix\n Prefix the runs and metrics collection,\n i.e. runs will be stored to PREFIX_runs, metrics to PREFIX_metrics.\n If empty runs are stored to 'runs', metrics to 'metrics'.\n overwrite\n _id of a run that should be overwritten.\n priority\n (default 30)\n client\n Client to connect to. Do not use client and URL together.\n failure_dir\n Directory to save the run of a failed observer to.\n \"\"\"\n import pymongo\n import gridfs\n\n if client is not None:\n if not isinstance(client, pymongo.MongoClient):\n raise ValueError(\n \"client needs to be a pymongo.MongoClient, \"\n \"but is {} instead\".format(type(client))\n )\n if url is not None:\n raise ValueError(\"Cannot pass both a client and a url.\")\n else:\n client = pymongo.MongoClient(url, **kwargs)\n\n self._client = client\n database = client[db_name]\n if collection != \"runs\":\n # the 'old' way of setting a custom collection name\n # still works as before for backward compatibility\n warnings.warn(\n 'Argument \"collection\" is deprecated. '\n 'Please use \"collection_prefix\" instead.',\n DeprecationWarning,\n )\n if collection_prefix != \"\":\n raise ValueError(\"Cannot pass both collection and a collection prefix.\")\n runs_collection_name = collection\n metrics_collection_name = \"metrics\"\n else:\n if collection_prefix != \"\":\n # separate prefix from 'runs' / 'collections' by an underscore.\n collection_prefix = \"{}_\".format(collection_prefix)\n\n runs_collection_name = \"{}runs\".format(collection_prefix)\n metrics_collection_name = \"{}metrics\".format(collection_prefix)\n\n if runs_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(runs_collection_name)\n )\n\n if metrics_collection_name in MongoObserver.COLLECTION_NAME_BLACKLIST:\n raise KeyError(\n 'Collection name \"{}\" is reserved. '\n \"Please use a different one.\".format(metrics_collection_name)\n )\n\n runs_collection = database[runs_collection_name]\n metrics_collection = database[metrics_collection_name]\n fs = gridfs.GridFS(database)\n self.initialize(\n runs_collection,\n fs,\n overwrite=overwrite,\n metrics_collection=metrics_collection,\n failure_dir=failure_dir,\n priority=priority,\n )\n\n def initialize(\n self,\n runs_collection,\n fs,\n overwrite=None,\n metrics_collection=None,\n failure_dir=None,\n priority=DEFAULT_MONGO_PRIORITY,\n ):\n self.runs = runs_collection\n self.metrics = metrics_collection\n self.fs = fs\n if overwrite is not None:\n overwrite = int(overwrite)\n run = self.runs.find_one({\"_id\": overwrite})\n if run is None:\n raise RuntimeError(\n \"Couldn't find run to overwrite with \" \"_id='{}'\".format(overwrite)\n )\n else:\n overwrite = run\n self.overwrite = overwrite\n self.run_entry = None\n self.priority = priority\n self.failure_dir = failure_dir\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n if self.overwrite is not None:\n raise RuntimeError(\"Can't overwrite with QUEUED run.\")\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n # set ID if given\n if _id is not None:\n self.run_entry[\"_id\"] = _id\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n if self.overwrite is None:\n self.run_entry = {\"_id\": _id}\n else:\n if self.run_entry is not None:\n raise RuntimeError(\"Cannot overwrite more than once!\")\n # TODO sanity checks\n self.run_entry = self.overwrite\n\n self.run_entry.update(\n {\n \"experiment\": dict(ex_info),\n \"format\": self.VERSION,\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time,\n \"config\": flatten(config),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"captured_out\": \"\",\n \"info\": {},\n \"heartbeat\": None,\n }\n )\n\n # save sources\n self.run_entry[\"experiment\"][\"sources\"] = self.save_sources(ex_info)\n self.insert()\n return self.run_entry[\"_id\"]\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.run_entry[\"info\"] = flatten(info)\n self.run_entry[\"captured_out\"] = captured_out\n self.run_entry[\"heartbeat\"] = beat_time\n self.run_entry[\"result\"] = flatten(result)\n self.save()\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time\n self.run_entry[\"result\"] = flatten(result)\n self.run_entry[\"status\"] = \"COMPLETED\"\n self.final_save(attempts=10)\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time\n self.run_entry[\"status\"] = status\n self.final_save(attempts=3)\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.final_save(attempts=1)\n\n def resource_event(self, filename):\n if self.fs.exists(filename=filename):\n md5hash = get_digest(filename)\n if self.fs.exists(filename=filename, md5=md5hash):\n resource = (filename, md5hash)\n if resource not in self.run_entry[\"resources\"]:\n self.run_entry[\"resources\"].append(resource)\n self.save()\n return\n # Pymongo 4.0: GridFS removed support for md5, we now have to compute\n # it manually\n md5hash = get_digest(filename)\n self.run_entry[\"resources\"].append((filename, md5hash))\n self.save()\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n with open(filename, \"rb\") as f:\n run_id = self.run_entry[\"_id\"]\n db_filename = \"artifact://{}/{}/{}\".format(self.runs.name, run_id, name)\n if content_type is None:\n content_type = self._try_to_detect_content_type(filename)\n\n file_id = self.fs.put(\n f, filename=db_filename, metadata=metadata, content_type=content_type\n )\n\n self.run_entry[\"artifacts\"].append({\"name\": name, \"file_id\": file_id})\n self.save()\n\n @staticmethod\n def _try_to_detect_content_type(filename):\n mime_type, _ = mimetype_detector.guess_type(filename)\n if mime_type is not None:\n print(\n \"Added {} as content-type of artifact {}.\".format(mime_type, filename)\n )\n else:\n print(\n \"Failed to detect content-type automatically for \"\n \"artifact {}.\".format(filename)\n )\n return mime_type\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements to the database.\n\n Take measurements and store them into\n the metrics collection in the database.\n Additionally, reference the metrics\n in the info[\"metrics\"] dictionary.\n \"\"\"\n if self.metrics is None:\n # If, for whatever reason, the metrics collection has not been set\n # do not try to save anything there.\n return\n for key in metrics_by_name:\n query = {\"run_id\": self.run_entry[\"_id\"], \"name\": key}\n push = {\n \"steps\": {\"$each\": metrics_by_name[key][\"steps\"]},\n \"values\": {\"$each\": metrics_by_name[key][\"values\"]},\n \"timestamps\": {\"$each\": metrics_by_name[key][\"timestamps\"]},\n }\n update = {\"$push\": push}\n result = self.metrics.update_one(query, update, upsert=True)\n if result.upserted_id is not None:\n # This is the first time we are storing this metric\n info.setdefault(\"metrics\", []).append(\n {\"name\": key, \"id\": str(result.upserted_id)}\n )\n\n def insert(self):\n import pymongo.errors\n\n if self.overwrite:\n return self.save()\n\n autoinc_key = self.run_entry.get(\"_id\") is None\n while True:\n if autoinc_key:\n c = self.runs.find({}, {\"_id\": 1})\n c = c.sort(\"_id\", pymongo.DESCENDING).limit(1)\n self.run_entry[\"_id\"] = (\n c.next()[\"_id\"] + 1 if self.runs.count_documents({}, limit=1) else 1\n )\n try:\n self.runs.insert_one(self.run_entry)\n return\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\"\n \"(most likely in the info)\\n{}\".format(e)\n ) from e\n except pymongo.errors.DuplicateKeyError:\n if not autoinc_key:\n raise\n\n def save(self):\n import pymongo.errors\n\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]}, {\"$set\": self.run_entry}\n )\n except pymongo.errors.AutoReconnect:\n pass # just wait for the next save\n except pymongo.errors.InvalidDocument as e:\n raise ObserverError(\n \"Run contained an unserializable entry.\" \"(most likely in the info)\"\n ) from e\n\n def final_save(self, attempts):\n import pymongo.errors\n\n for i in range(attempts):\n try:\n self.runs.update_one(\n {\"_id\": self.run_entry[\"_id\"]},\n {\"$set\": self.run_entry},\n upsert=True,\n )\n return\n except pymongo.errors.AutoReconnect:\n if i < attempts - 1:\n time.sleep(1)\n except pymongo.errors.ConnectionFailure:\n pass\n except pymongo.errors.InvalidDocument:\n self.run_entry = force_bson_encodeable(self.run_entry)\n print(\n \"Warning: Some of the entries of the run were not \"\n \"BSON-serializable!\\n They have been altered such that \"\n \"they can be stored, but you should fix your experiment!\"\n \"Most likely it is either the 'info' or the 'result'.\",\n file=sys.stderr,\n )\n\n os.makedirs(self.failure_dir, exist_ok=True)\n with NamedTemporaryFile(\n suffix=\".pickle\",\n delete=False,\n prefix=\"sacred_mongo_fail_{}_\".format(self.run_entry[\"_id\"]),\n dir=self.failure_dir,\n ) as f:\n pickle.dump(self.run_entry, f)\n print(\n \"Warning: saving to MongoDB failed! \"\n \"Stored experiment entry in '{}'\".format(f.name),\n file=sys.stderr,\n )\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for source_name, md5 in ex_info[\"sources\"]:\n abs_path = os.path.join(base_dir, source_name)\n file = self.fs.find_one({\"filename\": abs_path, \"md5\": md5})\n if file:\n _id = file._id\n else:\n with open(abs_path, \"rb\") as f:\n _id = self.fs.put(f, filename=abs_path)\n source_info.append([source_name, _id])\n return source_info\n\n def __eq__(self, other):\n if isinstance(other, MongoObserver):\n return self.runs == other.runs\n return False", "n_chars_compressed": 14408, "compression_ratio": 1.0}, "tests/test_exceptions.py::75": {"resolved_imports": ["sacred/__init__.py", "sacred/utils.py"], "used_names": ["Experiment", "format_filtered_stacktrace"], "enclosing_function": "test_format_filtered_stacktrace_true", "extracted_code": "# Source: sacred/__init__.py\nThe main module of sacred.\n\nIt provides access to the two main classes Experiment and Ingredient.\n\"\"\"\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n \"Ingredient\",\n\n\n__all__ = (\n \"Experiment\",\n \"Ingredient\",\n \"observers\",\n \"host_info_getter\",\n \"__version__\",\n \"__author__\",\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n\n\n# Source: sacred/utils.py\ndef format_filtered_stacktrace(filter_traceback=\"default\"):\n \"\"\"\n Returns the traceback as `string`.\n\n `filter_traceback` can be one of:\n - 'always': always filter out sacred internals\n - 'default': Default behaviour: filter out sacred internals\n if the exception did not originate from within sacred, and\n print just the internal stack trace otherwise\n - 'never': don't filter, always print full traceback\n - All other values will fall back to 'never'.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n # determine if last exception is from sacred\n current_tb = exc_traceback\n while current_tb.tb_next is not None:\n current_tb = current_tb.tb_next\n\n if filter_traceback == \"default\" and _is_sacred_frame(current_tb.tb_frame):\n # just print sacred internal trace\n header = [\n \"Exception originated from within Sacred.\\n\"\n \"Traceback (most recent calls):\\n\"\n ]\n texts = tb.format_exception(exc_type, exc_value, current_tb)\n return \"\".join(header + texts[1:]).strip()\n elif filter_traceback in (\"default\", \"always\"):\n # print filtered stacktrace\n tb_exception = FilteredTracebackException(\n exc_type, exc_value, exc_traceback, limit=None\n )\n return \"\".join(tb_exception.format())\n elif filter_traceback == \"never\":\n # print full stacktrace\n return \"\\n\".join(tb.format_exception(exc_type, exc_value, exc_traceback))\n else:\n raise ValueError(\"Unknown value for filter_traceback: \" + filter_traceback)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2731, "extracted_code_full": "# Source: sacred/__init__.py\nThe main module of sacred.\n\nIt provides access to the two main classes Experiment and Ingredient.\n\"\"\"\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\nfrom sacred.__about__ import __version__, __author__, __author_email__, __url__\nfrom sacred.settings import SETTINGS\nfrom sacred.experiment import Experiment\nfrom sacred.ingredient import Ingredient\nfrom sacred import observers\nfrom sacred.host_info import host_info_getter, host_info_gatherer\nfrom sacred.commandline_options import cli_option\n\n\n__all__ = (\n \"Experiment\",\n \"Ingredient\",\n\n\n__all__ = (\n \"Experiment\",\n \"Ingredient\",\n \"observers\",\n \"host_info_getter\",\n \"__version__\",\n \"__author__\",\n \"__author_email__\",\n \"__url__\",\n \"SETTINGS\",\n \"host_info_gatherer\",\n\n\n# Source: sacred/utils.py\ndef format_filtered_stacktrace(filter_traceback=\"default\"):\n \"\"\"\n Returns the traceback as `string`.\n\n `filter_traceback` can be one of:\n - 'always': always filter out sacred internals\n - 'default': Default behaviour: filter out sacred internals\n if the exception did not originate from within sacred, and\n print just the internal stack trace otherwise\n - 'never': don't filter, always print full traceback\n - All other values will fall back to 'never'.\n \"\"\"\n exc_type, exc_value, exc_traceback = sys.exc_info()\n # determine if last exception is from sacred\n current_tb = exc_traceback\n while current_tb.tb_next is not None:\n current_tb = current_tb.tb_next\n\n if filter_traceback == \"default\" and _is_sacred_frame(current_tb.tb_frame):\n # just print sacred internal trace\n header = [\n \"Exception originated from within Sacred.\\n\"\n \"Traceback (most recent calls):\\n\"\n ]\n texts = tb.format_exception(exc_type, exc_value, current_tb)\n return \"\".join(header + texts[1:]).strip()\n elif filter_traceback in (\"default\", \"always\"):\n # print filtered stacktrace\n tb_exception = FilteredTracebackException(\n exc_type, exc_value, exc_traceback, limit=None\n )\n return \"\".join(tb_exception.format())\n elif filter_traceback == \"never\":\n # print full stacktrace\n return \"\\n\".join(tb.format_exception(exc_type, exc_value, exc_traceback))\n else:\n raise ValueError(\"Unknown value for filter_traceback: \" + filter_traceback)", "n_chars_compressed": 2731, "compression_ratio": 1.0}, "tests/test_config/test_utils.py::61": {"resolved_imports": ["sacred/__init__.py", "sacred/optional.py", "sacred/config/utils.py"], "used_names": ["normalize_or_die", "pytest"], "enclosing_function": "test_normalize_or_die_for_numpy_arrays", "extracted_code": "# Source: sacred/config/utils.py\ndef normalize_or_die(obj):\n if isinstance(obj, dict):\n res = dict()\n for key, value in obj.items():\n assert_is_valid_key(key)\n res[key] = normalize_or_die(value)\n return res\n elif isinstance(obj, (list, tuple)):\n return list([normalize_or_die(value) for value in obj])\n return normalize_numpy(obj)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 389, "extracted_code_full": "# Source: sacred/config/utils.py\ndef normalize_or_die(obj):\n if isinstance(obj, dict):\n res = dict()\n for key, value in obj.items():\n assert_is_valid_key(key)\n res[key] = normalize_or_die(value)\n return res\n elif isinstance(obj, (list, tuple)):\n return list([normalize_or_die(value) for value in obj])\n return normalize_numpy(obj)", "n_chars_compressed": 389, "compression_ratio": 1.0}, "tests/test_modules.py::217": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": [], "enclosing_function": "sub_sub_ing_main", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_experiment.py::301": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": [], "enclosing_function": "test_config_hook_updates_config", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_mongo_observer.py::288": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["datetime", "force_bson_encodeable"], "enclosing_function": "test_force_bson_encodable_doesnt_change_valid_document", "extracted_code": "# Source: sacred/observers/mongo.py\ndef force_bson_encodeable(obj):\n import bson\n\n if isinstance(obj, dict):\n try:\n bson.BSON.encode(obj, check_keys=True)\n return obj\n except bson.InvalidDocument:\n return {\n force_valid_bson_key(k): force_bson_encodeable(v)\n for k, v in obj.items()\n }\n\n elif opt.has_numpy and isinstance(obj, opt.np.ndarray):\n return obj\n else:\n try:\n bson.BSON.encode({\"dict_just_for_testing\": obj})\n return obj\n except bson.InvalidDocument:\n return str(obj)", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 631, "extracted_code_full": "# Source: sacred/observers/mongo.py\ndef force_bson_encodeable(obj):\n import bson\n\n if isinstance(obj, dict):\n try:\n bson.BSON.encode(obj, check_keys=True)\n return obj\n except bson.InvalidDocument:\n return {\n force_valid_bson_key(k): force_bson_encodeable(v)\n for k, v in obj.items()\n }\n\n elif opt.has_numpy and isinstance(obj, opt.np.ndarray):\n return obj\n else:\n try:\n bson.BSON.encode({\"dict_just_for_testing\": obj})\n return obj\n except bson.InvalidDocument:\n return str(obj)", "n_chars_compressed": 631, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::61": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock", "random"], "enclosing_function": "test_captured_function_randomness", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_observers/test_file_storage_observer.py::111": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["os"], "enclosing_function": "test_fs_observer_started_event_creates_rundir_with_filesystem_delay", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_utils.py::76": {"resolved_imports": ["sacred/utils.py"], "used_names": ["get_by_dotted_path"], "enclosing_function": "test_get_by_dotted_path", "extracted_code": "# Source: sacred/utils.py\ndef get_by_dotted_path(d, path, default=None):\n \"\"\"\n Get an entry from nested dictionaries using a dotted path.\n\n Example\n -------\n >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')\n 12\n \"\"\"\n if not path:\n return d\n split_path = path.split(\".\")\n current_option = d\n for p in split_path:\n if p not in current_option:\n return default\n current_option = current_option[p]\n return current_option", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 486, "extracted_code_full": "# Source: sacred/utils.py\ndef get_by_dotted_path(d, path, default=None):\n \"\"\"\n Get an entry from nested dictionaries using a dotted path.\n\n Example\n -------\n >>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')\n 12\n \"\"\"\n if not path:\n return d\n split_path = path.split(\".\")\n current_option = d\n for p in split_path:\n if p not in current_option:\n return default\n current_option = current_option[p]\n return current_option", "n_chars_compressed": 486, "compression_ratio": 1.0}, "tests/test_observers/test_sql_observer.py::84": {"resolved_imports": ["sacred/serializer.py", "sacred/observers/sql.py", "sacred/observers/sql_bases.py"], "used_names": ["Experiment", "Host", "Run"], "enclosing_function": "test_sql_observer_started_event_creates_run", "extracted_code": "# Source: sacred/observers/sql_bases.py\nclass Host(Base):\n __tablename__ = \"host\"\n\n @classmethod\n def get_or_create(cls, host_info, session):\n h = dict(\n hostname=host_info[\"hostname\"],\n cpu=host_info[\"cpu\"],\n os=host_info[\"os\"][0],\n os_info=host_info[\"os\"][1],\n python_version=host_info[\"python_version\"],\n )\n\n return session.query(cls).filter_by(**h).first() or cls(**h)\n\n host_id = sa.Column(sa.Integer, primary_key=True)\n cpu = sa.Column(sa.String(64))\n hostname = sa.Column(sa.String(64))\n os = sa.Column(sa.String(16))\n os_info = sa.Column(sa.String(64))\n python_version = sa.Column(sa.String(16))\n\n def to_json(self):\n return {\n \"cpu\": self.cpu,\n \"hostname\": self.hostname,\n \"os\": [self.os, self.os_info],\n \"python_version\": self.python_version,\n }\n\nclass Experiment(Base):\n __tablename__ = \"experiment\"\n\n @classmethod\n def get_or_create(cls, ex_info, session):\n name = ex_info[\"name\"]\n # Compute a MD5sum of the ex_info to determine its uniqueness\n h = hashlib.md5()\n h.update(json.dumps(ex_info).encode())\n md5 = h.hexdigest()\n instance = session.query(cls).filter_by(name=name, md5sum=md5).first()\n if instance:\n return instance\n\n dependencies = [\n Dependency.get_or_create(d, session) for d in ex_info[\"dependencies\"]\n ]\n sources = [\n Source.get_or_create(s, md5sum, session, ex_info[\"base_dir\"])\n for s, md5sum in ex_info[\"sources\"]\n ]\n repositories = set()\n for r in ex_info[\"repositories\"]:\n repository = Repository.get_or_create(\n r[\"url\"], r[\"commit\"], r[\"dirty\"], session\n )\n session.add(repository)\n repositories.add(repository)\n repositories = list(repositories)\n\n return cls(\n name=name,\n dependencies=dependencies,\n sources=sources,\n repositories=repositories,\n md5sum=md5,\n base_dir=ex_info[\"base_dir\"],\n )\n\n experiment_id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(32))\n md5sum = sa.Column(sa.String(32))\n base_dir = sa.Column(sa.String(64))\n sources = sa.orm.relationship(\n \"Source\", secondary=experiment_source_association, backref=\"experiments\"\n )\n repositories = sa.orm.relationship(\n \"Repository\", secondary=experiment_repository_association, backref=\"experiments\"\n )\n dependencies = sa.orm.relationship(\n \"Dependency\", secondary=experiment_dependency_association, backref=\"experiments\"\n )\n\n def to_json(self):\n return {\n \"name\": self.name,\n \"base_dir\": self.base_dir,\n \"sources\": [s.to_json() for s in self.sources],\n \"repositories\": [r.to_json() for r in self.repositories],\n \"dependencies\": [d.to_json() for d in self.dependencies],\n }\n\nclass Run(Base):\n __tablename__ = \"run\"\n id = sa.Column(sa.Integer, primary_key=True)\n\n run_id = sa.Column(sa.String(24), unique=True)\n\n command = sa.Column(sa.String(64))\n\n # times\n start_time = sa.Column(sa.DateTime)\n heartbeat = sa.Column(sa.DateTime)\n stop_time = sa.Column(sa.DateTime)\n queue_time = sa.Column(sa.DateTime)\n\n # meta info\n priority = sa.Column(sa.Float)\n comment = sa.Column(sa.Text)\n\n fail_trace = sa.Column(sa.Text)\n\n # Captured out\n # TODO: move to separate table?\n captured_out = sa.Column(sa.Text)\n\n # Configuration & info\n # TODO: switch type to json if possible\n config = sa.Column(sa.Text)\n info = sa.Column(sa.Text)\n\n status = sa.Column(\n sa.Enum(\n \"RUNNING\",\n \"COMPLETED\",\n \"INTERRUPTED\",\n \"TIMEOUT\",\n \"FAILED\",\n \"QUEUED\",\n name=\"status_enum\",\n )\n )\n\n host_id = sa.Column(sa.Integer, sa.ForeignKey(\"host.host_id\"))\n host = sa.orm.relationship(\"Host\", backref=sa.orm.backref(\"runs\"))\n\n experiment_id = sa.Column(sa.Integer, sa.ForeignKey(\"experiment.experiment_id\"))\n experiment = sa.orm.relationship(\"Experiment\", backref=sa.orm.backref(\"runs\"))\n\n # artifacts = backref\n resources = sa.orm.relationship(\n \"Resource\", secondary=run_resource_association, backref=\"runs\"\n )\n\n result = sa.Column(sa.Float)\n\n def to_json(self):\n return {\n \"_id\": self.run_id,\n \"command\": self.command,\n \"start_time\": self.start_time,\n \"heartbeat\": self.heartbeat,\n \"stop_time\": self.stop_time,\n \"queue_time\": self.queue_time,\n \"status\": self.status,\n \"result\": self.result,\n \"meta\": {\"comment\": self.comment, \"priority\": self.priority},\n \"resources\": [r.to_json() for r in self.resources],\n \"artifacts\": [a.to_json() for a in self.artifacts],\n \"host\": self.host.to_json(),\n \"experiment\": self.experiment.to_json(),\n \"config\": restore(json.loads(self.config)),\n \"captured_out\": self.captured_out,\n \"fail_trace\": self.fail_trace,\n }", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 5291, "extracted_code_full": "# Source: sacred/observers/sql_bases.py\nclass Host(Base):\n __tablename__ = \"host\"\n\n @classmethod\n def get_or_create(cls, host_info, session):\n h = dict(\n hostname=host_info[\"hostname\"],\n cpu=host_info[\"cpu\"],\n os=host_info[\"os\"][0],\n os_info=host_info[\"os\"][1],\n python_version=host_info[\"python_version\"],\n )\n\n return session.query(cls).filter_by(**h).first() or cls(**h)\n\n host_id = sa.Column(sa.Integer, primary_key=True)\n cpu = sa.Column(sa.String(64))\n hostname = sa.Column(sa.String(64))\n os = sa.Column(sa.String(16))\n os_info = sa.Column(sa.String(64))\n python_version = sa.Column(sa.String(16))\n\n def to_json(self):\n return {\n \"cpu\": self.cpu,\n \"hostname\": self.hostname,\n \"os\": [self.os, self.os_info],\n \"python_version\": self.python_version,\n }\n\nclass Experiment(Base):\n __tablename__ = \"experiment\"\n\n @classmethod\n def get_or_create(cls, ex_info, session):\n name = ex_info[\"name\"]\n # Compute a MD5sum of the ex_info to determine its uniqueness\n h = hashlib.md5()\n h.update(json.dumps(ex_info).encode())\n md5 = h.hexdigest()\n instance = session.query(cls).filter_by(name=name, md5sum=md5).first()\n if instance:\n return instance\n\n dependencies = [\n Dependency.get_or_create(d, session) for d in ex_info[\"dependencies\"]\n ]\n sources = [\n Source.get_or_create(s, md5sum, session, ex_info[\"base_dir\"])\n for s, md5sum in ex_info[\"sources\"]\n ]\n repositories = set()\n for r in ex_info[\"repositories\"]:\n repository = Repository.get_or_create(\n r[\"url\"], r[\"commit\"], r[\"dirty\"], session\n )\n session.add(repository)\n repositories.add(repository)\n repositories = list(repositories)\n\n return cls(\n name=name,\n dependencies=dependencies,\n sources=sources,\n repositories=repositories,\n md5sum=md5,\n base_dir=ex_info[\"base_dir\"],\n )\n\n experiment_id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(32))\n md5sum = sa.Column(sa.String(32))\n base_dir = sa.Column(sa.String(64))\n sources = sa.orm.relationship(\n \"Source\", secondary=experiment_source_association, backref=\"experiments\"\n )\n repositories = sa.orm.relationship(\n \"Repository\", secondary=experiment_repository_association, backref=\"experiments\"\n )\n dependencies = sa.orm.relationship(\n \"Dependency\", secondary=experiment_dependency_association, backref=\"experiments\"\n )\n\n def to_json(self):\n return {\n \"name\": self.name,\n \"base_dir\": self.base_dir,\n \"sources\": [s.to_json() for s in self.sources],\n \"repositories\": [r.to_json() for r in self.repositories],\n \"dependencies\": [d.to_json() for d in self.dependencies],\n }\n\nclass Run(Base):\n __tablename__ = \"run\"\n id = sa.Column(sa.Integer, primary_key=True)\n\n run_id = sa.Column(sa.String(24), unique=True)\n\n command = sa.Column(sa.String(64))\n\n # times\n start_time = sa.Column(sa.DateTime)\n heartbeat = sa.Column(sa.DateTime)\n stop_time = sa.Column(sa.DateTime)\n queue_time = sa.Column(sa.DateTime)\n\n # meta info\n priority = sa.Column(sa.Float)\n comment = sa.Column(sa.Text)\n\n fail_trace = sa.Column(sa.Text)\n\n # Captured out\n # TODO: move to separate table?\n captured_out = sa.Column(sa.Text)\n\n # Configuration & info\n # TODO: switch type to json if possible\n config = sa.Column(sa.Text)\n info = sa.Column(sa.Text)\n\n status = sa.Column(\n sa.Enum(\n \"RUNNING\",\n \"COMPLETED\",\n \"INTERRUPTED\",\n \"TIMEOUT\",\n \"FAILED\",\n \"QUEUED\",\n name=\"status_enum\",\n )\n )\n\n host_id = sa.Column(sa.Integer, sa.ForeignKey(\"host.host_id\"))\n host = sa.orm.relationship(\"Host\", backref=sa.orm.backref(\"runs\"))\n\n experiment_id = sa.Column(sa.Integer, sa.ForeignKey(\"experiment.experiment_id\"))\n experiment = sa.orm.relationship(\"Experiment\", backref=sa.orm.backref(\"runs\"))\n\n # artifacts = backref\n resources = sa.orm.relationship(\n \"Resource\", secondary=run_resource_association, backref=\"runs\"\n )\n\n result = sa.Column(sa.Float)\n\n def to_json(self):\n return {\n \"_id\": self.run_id,\n \"command\": self.command,\n \"start_time\": self.start_time,\n \"heartbeat\": self.heartbeat,\n \"stop_time\": self.stop_time,\n \"queue_time\": self.queue_time,\n \"status\": self.status,\n \"result\": self.result,\n \"meta\": {\"comment\": self.comment, \"priority\": self.priority},\n \"resources\": [r.to_json() for r in self.resources],\n \"artifacts\": [a.to_json() for a in self.artifacts],\n \"host\": self.host.to_json(),\n \"experiment\": self.experiment.to_json(),\n \"config\": restore(json.loads(self.config)),\n \"captured_out\": self.captured_out,\n \"fail_trace\": self.fail_trace,\n }", "n_chars_compressed": 5291, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::118": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_heartbeat_event_updates_run", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_gcs_observer.py::115": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": [], "enclosing_function": "test_gcs_observer_started_event_increments_run_id", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_observers/test_mongo_observer.py::126": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": [], "enclosing_function": "test_mongo_observer_started_event_creates_run", "extracted_code": "", "n_imports_parsed": 12, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_config/test_config_dict.py::118": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_conf_scope_does_not_contain_fallback", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_utils.py::149": {"resolved_imports": ["sacred/utils.py"], "used_names": ["convert_camel_case_to_snake_case", "pytest"], "enclosing_function": "test_convert_camel_case_to_snake_case", "extracted_code": "# Source: sacred/utils.py\ndef convert_camel_case_to_snake_case(name):\n \"\"\"Convert CamelCase to snake_case.\"\"\"\n s1 = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", s1).lower()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 225, "extracted_code_full": "# Source: sacred/utils.py\ndef convert_camel_case_to_snake_case(name):\n \"\"\"Convert CamelCase to snake_case.\"\"\"\n s1 = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", s1).lower()", "n_chars_compressed": 225, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::37": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_config_dict_result_contains_keys", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_file_storage_observer.py::304": {"resolved_imports": ["sacred/observers/file_storage.py", "sacred/metrics_logger.py"], "used_names": ["FileStorageObserver"], "enclosing_function": "test_fs_observer_equality", "extracted_code": "# Source: sacred/observers/file_storage.py\nclass FileStorageObserver(RunObserver):\n VERSION = \"FileStorageObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"FileStorageObserver.create(...) is deprecated. \"\n \"Please use FileStorageObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n basedir: PathType,\n resource_dir: Optional[PathType] = None,\n source_dir: Optional[PathType] = None,\n template: Optional[PathType] = None,\n priority: int = DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts: bool = True,\n copy_sources: bool = True,\n ):\n basedir = Path(basedir)\n resource_dir = resource_dir or basedir / \"_resources\"\n source_dir = source_dir or basedir / \"_sources\"\n if template is not None:\n if not os.path.exists(template):\n raise FileNotFoundError(\n \"Couldn't find template file '{}'\".format(template)\n )\n else:\n template = basedir / \"template.html\"\n if not template.exists():\n template = None\n self.initialize(\n basedir,\n resource_dir,\n source_dir,\n template,\n priority,\n copy_artifacts,\n copy_sources,\n )\n\n def initialize(\n self,\n basedir,\n resource_dir,\n source_dir,\n template,\n priority=DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts=True,\n copy_sources=True,\n ):\n self.basedir = str(basedir)\n self.resource_dir = resource_dir\n self.source_dir = source_dir\n self.template = template\n self.priority = priority\n self.copy_artifacts = copy_artifacts\n self.copy_sources = copy_sources\n self.dir = None\n self.run_entry = None\n self.config = None\n self.info = None\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def _maximum_existing_run_id(self):\n dir_nrs = [\n int(d)\n for d in os.listdir(self.basedir)\n if os.path.isdir(os.path.join(self.basedir, d)) and d.isdigit()\n ]\n if dir_nrs:\n return max(dir_nrs)\n else:\n return 0\n\n def _make_dir(self, _id):\n new_dir = os.path.join(self.basedir, str(_id))\n os.mkdir(new_dir)\n self.dir = new_dir # set only if mkdir is successful\n\n def _make_run_dir(self, _id):\n os.makedirs(self.basedir, exist_ok=True)\n self.dir = None\n if _id is None:\n fail_count = 0\n _id = self._maximum_existing_run_id() + 1\n while self.dir is None:\n try:\n self._make_dir(_id)\n except FileExistsError: # Catch race conditions\n if fail_count < 1000:\n fail_count += 1\n _id += 1\n else: # expect that something else went wrong\n raise\n else:\n self.dir = os.path.join(self.basedir, str(_id))\n os.mkdir(self.dir)\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n self.config = config\n self.info = {}\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n\n if self.copy_sources:\n for s, _ in ex_info[\"sources\"]:\n self.save_file(s)\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for s, _ in ex_info[\"sources\"]:\n abspath = os.path.join(base_dir, s)\n if self.copy_sources:\n store_path = self.find_or_save(abspath, self.source_dir)\n else:\n store_path = abspath\n relative_source = os.path.relpath(str(store_path), self.basedir)\n source_info.append([s, relative_source])\n return source_info\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n ex_info[\"sources\"] = self.save_sources(ex_info)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time.isoformat(),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"heartbeat\": None,\n }\n self.config = config\n self.info = {}\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n self.save_cout()\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def find_or_save(self, filename, store_dir: Path):\n try:\n Path(filename).resolve().relative_to(Path(self.basedir).resolve())\n is_relative_to = True\n except ValueError:\n is_relative_to = False\n\n if is_relative_to and not self.copy_artifacts:\n return filename\n else:\n store_dir.mkdir(parents=True, exist_ok=True)\n source_name, ext = os.path.splitext(os.path.basename(filename))\n md5sum = get_digest(filename)\n store_name = source_name + \"_\" + md5sum + ext\n store_path = store_dir / store_name\n if not store_path.exists():\n copyfile(filename, str(store_path))\n return store_path\n\n def save_json(self, obj, filename):\n with open(os.path.join(self.dir, filename), \"w\") as f:\n json.dump(flatten(obj), f, sort_keys=True, indent=2)\n f.flush()\n\n def save_file(self, filename, target_name=None):\n target_name = target_name or os.path.basename(filename)\n blacklist = [\"run.json\", \"config.json\", \"cout.txt\", \"metrics.json\"]\n blacklist = [os.path.join(self.dir, x) for x in blacklist]\n dest_file = os.path.join(self.dir, target_name)\n if dest_file in blacklist:\n raise FileExistsError(\n \"You are trying to overwrite a file necessary for the \"\n \"FileStorageObserver. \"\n \"The list of blacklisted files is: {}\".format(blacklist)\n )\n try:\n copyfile(filename, dest_file)\n except SameFileError:\n pass\n\n def save_cout(self):\n with open(os.path.join(self.dir, \"cout.txt\"), \"ab\") as f:\n f.write(self.cout[self.cout_write_cursor :].encode(\"utf-8\"))\n self.cout_write_cursor = len(self.cout)\n\n def render_template(self):\n if opt.has_mako and self.template:\n from mako.template import Template\n\n template = Template(filename=self.template)\n report = template.render(\n run=self.run_entry,\n config=self.config,\n info=self.info,\n cout=self.cout,\n savedir=self.dir,\n )\n ext = self.template.suffix\n with open(os.path.join(self.dir, \"report\" + ext), \"w\") as f:\n f.write(report)\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.info = info\n self.run_entry[\"heartbeat\"] = beat_time.isoformat()\n self.run_entry[\"result\"] = result\n self.cout = captured_out\n self.save_cout()\n self.save_json(self.run_entry, \"run.json\")\n if self.info:\n self.save_json(self.info, \"info.json\")\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time.isoformat()\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time.isoformat()\n self.run_entry[\"status\"] = status\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time.isoformat()\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def resource_event(self, filename):\n store_path = self.find_or_save(filename, self.resource_dir)\n self.run_entry[\"resources\"].append([filename, str(store_path)])\n self.save_json(self.run_entry, \"run.json\")\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n self.save_file(filename, name)\n self.run_entry[\"artifacts\"].append(name)\n self.save_json(self.run_entry, \"run.json\")\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements into metrics.json.\"\"\"\n try:\n metrics_path = os.path.join(self.dir, \"metrics.json\")\n with open(metrics_path, \"r\") as f:\n saved_metrics = json.load(f)\n except IOError:\n # We haven't recorded anything yet. Start Collecting.\n saved_metrics = {}\n\n for metric_name, metric_ptr in metrics_by_name.items():\n\n if metric_name not in saved_metrics:\n saved_metrics[metric_name] = {\n \"values\": [],\n \"steps\": [],\n \"timestamps\": [],\n }\n\n saved_metrics[metric_name][\"values\"] += metric_ptr[\"values\"]\n saved_metrics[metric_name][\"steps\"] += metric_ptr[\"steps\"]\n\n # Manually convert them to avoid passing a datetime dtype handler\n # when we're trying to convert into json.\n timestamps_norm = [ts.isoformat() for ts in metric_ptr[\"timestamps\"]]\n saved_metrics[metric_name][\"timestamps\"] += timestamps_norm\n\n self.save_json(saved_metrics, \"metrics.json\")\n\n def __eq__(self, other):\n if isinstance(other, FileStorageObserver):\n return self.basedir == other.basedir\n return False", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 10857, "extracted_code_full": "# Source: sacred/observers/file_storage.py\nclass FileStorageObserver(RunObserver):\n VERSION = \"FileStorageObserver-0.7.0\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n warnings.warn(\n \"FileStorageObserver.create(...) is deprecated. \"\n \"Please use FileStorageObserver(...) instead.\",\n DeprecationWarning,\n )\n return cls(*args, **kwargs)\n\n def __init__(\n self,\n basedir: PathType,\n resource_dir: Optional[PathType] = None,\n source_dir: Optional[PathType] = None,\n template: Optional[PathType] = None,\n priority: int = DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts: bool = True,\n copy_sources: bool = True,\n ):\n basedir = Path(basedir)\n resource_dir = resource_dir or basedir / \"_resources\"\n source_dir = source_dir or basedir / \"_sources\"\n if template is not None:\n if not os.path.exists(template):\n raise FileNotFoundError(\n \"Couldn't find template file '{}'\".format(template)\n )\n else:\n template = basedir / \"template.html\"\n if not template.exists():\n template = None\n self.initialize(\n basedir,\n resource_dir,\n source_dir,\n template,\n priority,\n copy_artifacts,\n copy_sources,\n )\n\n def initialize(\n self,\n basedir,\n resource_dir,\n source_dir,\n template,\n priority=DEFAULT_FILE_STORAGE_PRIORITY,\n copy_artifacts=True,\n copy_sources=True,\n ):\n self.basedir = str(basedir)\n self.resource_dir = resource_dir\n self.source_dir = source_dir\n self.template = template\n self.priority = priority\n self.copy_artifacts = copy_artifacts\n self.copy_sources = copy_sources\n self.dir = None\n self.run_entry = None\n self.config = None\n self.info = None\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n @classmethod\n def create_from(cls, *args, **kwargs):\n self = cls.__new__(cls) # skip __init__ call\n self.initialize(*args, **kwargs)\n return self\n\n def _maximum_existing_run_id(self):\n dir_nrs = [\n int(d)\n for d in os.listdir(self.basedir)\n if os.path.isdir(os.path.join(self.basedir, d)) and d.isdigit()\n ]\n if dir_nrs:\n return max(dir_nrs)\n else:\n return 0\n\n def _make_dir(self, _id):\n new_dir = os.path.join(self.basedir, str(_id))\n os.mkdir(new_dir)\n self.dir = new_dir # set only if mkdir is successful\n\n def _make_run_dir(self, _id):\n os.makedirs(self.basedir, exist_ok=True)\n self.dir = None\n if _id is None:\n fail_count = 0\n _id = self._maximum_existing_run_id() + 1\n while self.dir is None:\n try:\n self._make_dir(_id)\n except FileExistsError: # Catch race conditions\n if fail_count < 1000:\n fail_count += 1\n _id += 1\n else: # expect that something else went wrong\n raise\n else:\n self.dir = os.path.join(self.basedir, str(_id))\n os.mkdir(self.dir)\n\n def queued_event(\n self, ex_info, command, host_info, queue_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"meta\": meta_info,\n \"status\": \"QUEUED\",\n }\n self.config = config\n self.info = {}\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n\n if self.copy_sources:\n for s, _ in ex_info[\"sources\"]:\n self.save_file(s)\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def save_sources(self, ex_info):\n base_dir = ex_info[\"base_dir\"]\n source_info = []\n for s, _ in ex_info[\"sources\"]:\n abspath = os.path.join(base_dir, s)\n if self.copy_sources:\n store_path = self.find_or_save(abspath, self.source_dir)\n else:\n store_path = abspath\n relative_source = os.path.relpath(str(store_path), self.basedir)\n source_info.append([s, relative_source])\n return source_info\n\n def started_event(\n self, ex_info, command, host_info, start_time, config, meta_info, _id\n ):\n self._make_run_dir(_id)\n\n ex_info[\"sources\"] = self.save_sources(ex_info)\n\n self.run_entry = {\n \"experiment\": dict(ex_info),\n \"command\": command,\n \"host\": dict(host_info),\n \"start_time\": start_time.isoformat(),\n \"meta\": meta_info,\n \"status\": \"RUNNING\",\n \"resources\": [],\n \"artifacts\": [],\n \"heartbeat\": None,\n }\n self.config = config\n self.info = {}\n self.cout = \"\"\n self.cout_write_cursor = 0\n\n self.save_json(self.run_entry, \"run.json\")\n self.save_json(self.config, \"config.json\")\n self.save_cout()\n\n return os.path.relpath(self.dir, self.basedir) if _id is None else _id\n\n def find_or_save(self, filename, store_dir: Path):\n try:\n Path(filename).resolve().relative_to(Path(self.basedir).resolve())\n is_relative_to = True\n except ValueError:\n is_relative_to = False\n\n if is_relative_to and not self.copy_artifacts:\n return filename\n else:\n store_dir.mkdir(parents=True, exist_ok=True)\n source_name, ext = os.path.splitext(os.path.basename(filename))\n md5sum = get_digest(filename)\n store_name = source_name + \"_\" + md5sum + ext\n store_path = store_dir / store_name\n if not store_path.exists():\n copyfile(filename, str(store_path))\n return store_path\n\n def save_json(self, obj, filename):\n with open(os.path.join(self.dir, filename), \"w\") as f:\n json.dump(flatten(obj), f, sort_keys=True, indent=2)\n f.flush()\n\n def save_file(self, filename, target_name=None):\n target_name = target_name or os.path.basename(filename)\n blacklist = [\"run.json\", \"config.json\", \"cout.txt\", \"metrics.json\"]\n blacklist = [os.path.join(self.dir, x) for x in blacklist]\n dest_file = os.path.join(self.dir, target_name)\n if dest_file in blacklist:\n raise FileExistsError(\n \"You are trying to overwrite a file necessary for the \"\n \"FileStorageObserver. \"\n \"The list of blacklisted files is: {}\".format(blacklist)\n )\n try:\n copyfile(filename, dest_file)\n except SameFileError:\n pass\n\n def save_cout(self):\n with open(os.path.join(self.dir, \"cout.txt\"), \"ab\") as f:\n f.write(self.cout[self.cout_write_cursor :].encode(\"utf-8\"))\n self.cout_write_cursor = len(self.cout)\n\n def render_template(self):\n if opt.has_mako and self.template:\n from mako.template import Template\n\n template = Template(filename=self.template)\n report = template.render(\n run=self.run_entry,\n config=self.config,\n info=self.info,\n cout=self.cout,\n savedir=self.dir,\n )\n ext = self.template.suffix\n with open(os.path.join(self.dir, \"report\" + ext), \"w\") as f:\n f.write(report)\n\n def heartbeat_event(self, info, captured_out, beat_time, result):\n self.info = info\n self.run_entry[\"heartbeat\"] = beat_time.isoformat()\n self.run_entry[\"result\"] = result\n self.cout = captured_out\n self.save_cout()\n self.save_json(self.run_entry, \"run.json\")\n if self.info:\n self.save_json(self.info, \"info.json\")\n\n def completed_event(self, stop_time, result):\n self.run_entry[\"stop_time\"] = stop_time.isoformat()\n self.run_entry[\"result\"] = result\n self.run_entry[\"status\"] = \"COMPLETED\"\n\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def interrupted_event(self, interrupt_time, status):\n self.run_entry[\"stop_time\"] = interrupt_time.isoformat()\n self.run_entry[\"status\"] = status\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def failed_event(self, fail_time, fail_trace):\n self.run_entry[\"stop_time\"] = fail_time.isoformat()\n self.run_entry[\"status\"] = \"FAILED\"\n self.run_entry[\"fail_trace\"] = fail_trace\n self.save_json(self.run_entry, \"run.json\")\n self.render_template()\n\n def resource_event(self, filename):\n store_path = self.find_or_save(filename, self.resource_dir)\n self.run_entry[\"resources\"].append([filename, str(store_path)])\n self.save_json(self.run_entry, \"run.json\")\n\n def artifact_event(self, name, filename, metadata=None, content_type=None):\n self.save_file(filename, name)\n self.run_entry[\"artifacts\"].append(name)\n self.save_json(self.run_entry, \"run.json\")\n\n def log_metrics(self, metrics_by_name, info):\n \"\"\"Store new measurements into metrics.json.\"\"\"\n try:\n metrics_path = os.path.join(self.dir, \"metrics.json\")\n with open(metrics_path, \"r\") as f:\n saved_metrics = json.load(f)\n except IOError:\n # We haven't recorded anything yet. Start Collecting.\n saved_metrics = {}\n\n for metric_name, metric_ptr in metrics_by_name.items():\n\n if metric_name not in saved_metrics:\n saved_metrics[metric_name] = {\n \"values\": [],\n \"steps\": [],\n \"timestamps\": [],\n }\n\n saved_metrics[metric_name][\"values\"] += metric_ptr[\"values\"]\n saved_metrics[metric_name][\"steps\"] += metric_ptr[\"steps\"]\n\n # Manually convert them to avoid passing a datetime dtype handler\n # when we're trying to convert into json.\n timestamps_norm = [ts.isoformat() for ts in metric_ptr[\"timestamps\"]]\n saved_metrics[metric_name][\"timestamps\"] += timestamps_norm\n\n self.save_json(saved_metrics, \"metrics.json\")\n\n def __eq__(self, other):\n if isinstance(other, FileStorageObserver):\n return self.basedir == other.basedir\n return False", "n_chars_compressed": 10857, "compression_ratio": 1.0}, "tests/test_observers/test_queue_observer.py::59": {"resolved_imports": ["sacred/observers/queue.py", "sacred/__init__.py"], "used_names": ["OrderedDict"], "enclosing_function": "test_log_metrics", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_modules.py::135": {"resolved_imports": ["sacred/config/config_scope.py", "sacred/experiment.py"], "used_names": ["Experiment", "Ingredient"], "enclosing_function": "test_experiment_named_config_subingredient", "extracted_code": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\nParameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 19146, "extracted_code_full": "# Source: sacred/experiment.py\nclass Experiment(Ingredient):\n \"\"\"\n The central class for each experiment in Sacred.\n\n It manages the configuration, the main function, captured methods,\n observers, commands, and further ingredients.\n\n An Experiment instance should be created as one of the first\n things in any experiment-file.\n \"\"\"\n\n def __init__(\n self,\n name: Optional[str] = None,\n ingredients: Sequence[Ingredient] = (),\n interactive: bool = False,\n base_dir: Optional[PathType] = None,\n additional_host_info: Optional[List[HostInfoGetter]] = None,\n additional_cli_options: Optional[Sequence[CLIOption]] = None,\n save_git_info: bool = True,\n ):\n \"\"\"\n Create a new experiment with the given name and optional ingredients.\n\n Parameters\n ----------\n name\n Optional name of this experiment, defaults to the filename.\n (Required in interactive mode)\n\n ingredients : list[sacred.Ingredient], optional\n A list of ingredients to be used with this experiment.\n\n interactive\n If set to True will allow the experiment to be run in interactive\n mode (e.g. IPython or Jupyter notebooks).\n However, this mode is discouraged since it won't allow storing the\n source-code or reliable reproduction of the runs.\n\n base_dir\n Optional full path to the base directory of this experiment. This\n will set the scope for automatic source file discovery.\n\n additional_host_info\n Optional dictionary containing as keys the names of the pieces of\n host info you want to collect, and as\n values the functions collecting those pieces of information.\n\n save_git_info:\n Optionally save the git commit hash and the git state\n (clean or dirty) for all source files. This requires the GitPython\n package.\n \"\"\"\n self.additional_host_info = additional_host_info or []\n check_additional_host_info(self.additional_host_info)\n self.additional_cli_options = additional_cli_options or []\n self.all_cli_options = (\n gather_command_line_options() + self.additional_cli_options\n )\n caller_globals = inspect.stack()[1][0].f_globals\n if name is None:\n if interactive:\n raise RuntimeError(\"name is required in interactive mode.\")\n mainfile = caller_globals.get(\"__file__\")\n if mainfile is None:\n raise RuntimeError(\n \"No main-file found. Are you running in \"\n \"interactive mode? If so please provide a \"\n \"name and set interactive=True.\"\n )\n name = os.path.basename(mainfile)\n if name.endswith(\".py\"):\n name = name[:-3]\n elif name.endswith(\".pyc\"):\n name = name[:-4]\n super().__init__(\n path=name,\n ingredients=ingredients,\n interactive=interactive,\n base_dir=base_dir,\n _caller_globals=caller_globals,\n save_git_info=save_git_info,\n )\n self.default_command = None\n self.command(print_config, unobserved=True)\n self.command(print_dependencies, unobserved=True)\n self.command(save_config, unobserved=True)\n self.command(print_named_configs(self), unobserved=True)\n self.observers = []\n self.current_run = None\n self.captured_out_filter = None\n \"\"\"Filter function to be applied to captured output of a run\"\"\"\n self.option_hooks = []\n\n # =========================== Decorators ==================================\n\n def main(self, function):\n \"\"\"\n Decorator to define the main function of the experiment.\n\n The main function of an experiment is the default command that is being\n run when no command is specified, or when calling the run() method.\n\n Usually it is more convenient to use ``automain`` instead.\n \"\"\"\n captured = self.command(function)\n self.default_command = captured.__name__\n return captured\n\n def automain(self, function):\n \"\"\"\n Decorator that defines *and runs* the main function of the experiment.\n\n The decorated function is marked as the default command for this\n experiment, and the command-line interface is automatically run when\n the file is executed.\n\n The method decorated by this should be last in the file because is\n equivalent to:\n\n Example\n -------\n ::\n\n @ex.main\n def my_main():\n pass\n\n if __name__ == '__main__':\n ex.run_commandline()\n \"\"\"\n captured = self.main(function)\n if function.__module__ == \"__main__\":\n # Ensure that automain is not used in interactive mode.\n import inspect\n\n main_filename = inspect.getfile(function)\n if main_filename == \"\" or (\n main_filename.startswith(\"\")\n ):\n raise RuntimeError(\n \"Cannot use @ex.automain decorator in \"\n \"interactive mode. Use @ex.main instead.\"\n )\n\n self.run_commandline()\n return captured\n\n def option_hook(self, function):\n \"\"\"\n Decorator for adding an option hook function.\n\n An option hook is a function that is called right before a run\n is created. It receives (and potentially modifies) the options\n dictionary. That is, the dictionary of commandline options used for\n this run.\n\n Notes\n -----\n The decorated function MUST have an argument called options.\n\n The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries,\n but changing them has no effect. Only modification on\n flags (entries starting with ``'--'``) are considered.\n \"\"\"\n sig = Signature(function)\n if \"options\" not in sig.arguments:\n raise KeyError(\n \"option_hook functions must have an argument called\"\n \" 'options', but got {}\".format(sig.arguments)\n )\n self.option_hooks.append(function)\n return function\n\n # =========================== Public Interface ============================\n\n def get_usage(self, program_name=None):\n \"\"\"Get the commandline usage string for this experiment.\"\"\"\n program_name = os.path.relpath(\n program_name or sys.argv[0] or \"Dummy\", self.base_dir\n )\n commands = OrderedDict(self.gather_commands())\n long_usage = format_usage(\n program_name, self.doc, commands, self.all_cli_options\n )\n # internal usage is a workaround because docopt cannot handle spaces\n # in program names. So for parsing we use 'dummy' as the program name.\n # for printing help etc. we want to use the actual program name.\n internal_usage = format_usage(\"dummy\", self.doc, commands, self.all_cli_options)\n short_usage = printable_usage(long_usage)\n return short_usage, long_usage, internal_usage\n\n def run(\n self,\n command_name: Optional[str] = None,\n config_updates: Optional[dict] = None,\n named_configs: Sequence[str] = (),\n info: Optional[dict] = None,\n meta_info: Optional[dict] = None,\n options: Optional[dict] = None,\n ) -> Run:\n \"\"\"\n Run the main function of the experiment or a given command.\n\n Parameters\n ----------\n command_name\n Name of the command to be run. Defaults to main function.\n\n config_updates\n Changes to the configuration as a nested dictionary\n\n named_configs\n list of names of named_configs to use\n\n info\n Additional information for this run.\n\n meta_info\n Additional meta information for this run.\n\n options\n Dictionary of options to use\n\n Returns\n -------\n The Run object corresponding to the finished run.\n \"\"\"\n run = self._create_run(\n command_name, config_updates, named_configs, info, meta_info, options\n )\n run()\n return run\n\n def run_commandline(self, argv=None) -> Optional[Run]:\n \"\"\"\n Run the command-line interface of this experiment.\n\n If ``argv`` is omitted it defaults to ``sys.argv``.\n\n Parameters\n ----------\n argv\n Command-line as string or list of strings like ``sys.argv``.\n\n Returns\n -------\n The Run object corresponding to the finished run.\n\n \"\"\"\n argv = ensure_wellformed_argv(argv)\n short_usage, usage, internal_usage = self.get_usage()\n args = docopt(internal_usage, [str(a) for a in argv[1:]], default_help=False)\n\n cmd_name = args.get(\"COMMAND\") or self.default_command\n config_updates, named_configs = get_config_updates(args[\"UPDATE\"])\n\n err = self._check_command(cmd_name)\n if not args[\"help\"] and err:\n print(short_usage)\n print(err)\n sys.exit(1)\n\n if self._handle_help(args, usage):\n sys.exit()\n\n try:\n return self.run(\n cmd_name,\n config_updates,\n named_configs,\n info={},\n meta_info={},\n options=args,\n )\n except Exception as e:\n if self.current_run:\n debug = self.current_run.debug\n else:\n # The usual command line options are applied after the run\n # object is built completely. Some exceptions (e.g.\n # ConfigAddedError) are raised before this. In these cases,\n # the debug flag must be checked manually.\n debug = args.get(\"--debug\", False)\n\n if debug:\n # Debug: Don't change behavior, just re-raise exception\n raise\n elif self.current_run and self.current_run.pdb:\n # Print exception and attach pdb debugger\n import traceback\n import pdb\n\n traceback.print_exception(*sys.exc_info())\n pdb.post_mortem()\n else:\n # Handle pretty printing of exceptions. This includes\n # filtering the stacktrace and printing the usage, as\n # specified by the exceptions attributes\n if isinstance(e, SacredError):\n print(format_sacred_error(e, short_usage), file=sys.stderr)\n else:\n print_filtered_stacktrace()\n sys.exit(1)\n\n def open_resource(self, filename: PathType, mode: str = \"r\"):\n \"\"\"Open a file and also save it as a resource.\n\n Opens a file, reports it to the observers as a resource, and returns\n the opened file.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.open_resource` method.\n\n Parameters\n ----------\n filename\n name of the file that should be opened\n mode\n mode that file will be open\n\n Returns\n -------\n The opened file-object.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n return self.current_run.open_resource(filename, mode)\n\n def add_resource(self, filename: PathType) -> None:\n \"\"\"Add a file as a resource.\n\n In Sacred terminology a resource is a file that the experiment needed\n to access during a run. In case of a MongoObserver that means making\n sure the file is stored in the database (but avoiding duplicates) along\n its path and md5 sum.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_resource` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as a resource\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_resource(filename)\n\n def add_artifact(\n self,\n filename: PathType,\n name: Optional[str] = None,\n metadata: Optional[dict] = None,\n content_type: Optional[str] = None,\n ) -> None:\n \"\"\"Add a file as an artifact.\n\n In Sacred terminology an artifact is a file produced by the experiment\n run. In case of a MongoObserver that means storing the file in the\n database.\n\n This function can only be called during a run, and just calls the\n :py:meth:`sacred.run.Run.add_artifact` method.\n\n Parameters\n ----------\n filename\n name of the file to be stored as artifact\n name\n optionally set the name of the artifact.\n Defaults to the relative file-path.\n metadata\n optionally attach metadata to the artifact.\n This only has an effect when using the MongoObserver.\n content_type\n optionally attach a content-type to the artifact.\n This only has an effect when using the MongoObserver.\n \"\"\"\n assert self.current_run is not None, \"Can only be called during a run.\"\n self.current_run.add_artifact(filename, name, metadata, content_type)\n\n @property\n def info(self) -> dict:\n \"\"\"Access the info-dict for storing custom information.\n\n Only works during a run and is essentially a shortcut to:\n\n Example\n -------\n ::\n\n @ex.capture\n def my_captured_function(_run):\n # [...]\n _run.info # == ex.info\n \"\"\"\n return self.current_run.info\n\n def log_scalar(self, name: str, value: float, step: Optional[int] = None) -> None:\n \"\"\"\n Add a new measurement.\n\n The measurement will be processed by the MongoDB* observer\n during a heartbeat event.\n Other observers are not yet supported.\n\n\n Parameters\n ----------\n name\n The name of the metric, e.g. training.loss\n value\n The measured value\n step\n The step number (integer), e.g. the iteration number\n If not specified, an internal counter for each metric\n is used, incremented by one.\n \"\"\"\n # Method added in change https://github.com/chovanecm/sacred/issues/4\n # The same as Run.log_scalar\n self.current_run.log_scalar(name, value, step)\n\n def post_process_name(self, name, ingredient):\n if ingredient == self:\n # Removes the experiment's path (prefix) from the names\n # of the gathered items. This means that, for example,\n # 'experiment.print_config' becomes 'print_config'.\n return name[len(self.path) + 1 :]\n return name\n\n def get_default_options(self) -> dict:\n \"\"\"Get a dictionary of default options as used with run.\n\n Returns\n -------\n A dictionary containing option keys of the form '--beat_interval'.\n Their values are boolean if the option is a flag, otherwise None or\n its default value.\n\n \"\"\"\n default_options = {}\n for option in self.all_cli_options:\n if isinstance(option, CLIOption):\n if option.is_flag:\n default_value = False\n else:\n default_value = None\n else: # legacy, should be removed later on.\n if option.arg is None:\n default_value = False\n else:\n default_value = None\n default_options[option.get_flag()] = default_value\n\n return default_options\n\n # =========================== Internal Interface ==========================\n\n def _create_run(\n self,\n command_name=None,\n config_updates=None,\n named_configs=(),\n info=None,\n meta_info=None,\n options=None,\n ):\n command_name = command_name or self.default_command\n if command_name is None:\n raise RuntimeError(\n \"No command found to be run. Specify a command \"\n \"or define a main function.\"\n )\n\n default_options = self.get_default_options()\n if options:\n default_options.update(options)\n options = default_options\n\n # call option hooks\n for oh in self.option_hooks:\n oh(options=options)\n\n run = create_run(\n self,\n command_name,\n config_updates,\n named_configs=named_configs,\n force=options.get(commandline_options.force_option.get_flag(), False),\n log_level=options.get(commandline_options.loglevel_option.get_flag(), None),\n )\n if info is not None:\n run.info.update(info)\n\n run.meta_info[\"command\"] = command_name\n run.meta_info[\"options\"] = options\n run.meta_info[\"named_configs\"] = list(named_configs)\n if config_updates is not None:\n run.meta_info[\"config_updates\"] = config_updates\n\n if meta_info:\n run.meta_info.update(meta_info)\n\n options_list = gather_command_line_options() + self.additional_cli_options\n for option in options_list:\n option_value = options.get(option.get_flag(), False)\n if option_value:\n option.apply(option_value, run)\n\n self.current_run = run\n return run\n\n def _check_command(self, cmd_name):\n commands = dict(self.gather_commands())\n if cmd_name is not None and cmd_name not in commands:\n return (\n 'Error: Command \"{}\" not found. Available commands are: '\n \"{}\".format(cmd_name, \", \".join(commands.keys()))\n )\n\n if cmd_name is None:\n return (\n \"Error: No command found to be run. Specify a command\"\n \" or define main function. Available commands\"\n \" are: {}\".format(\", \".join(commands.keys()))\n )\n\n def _handle_help(self, args, usage):\n if args[\"help\"] or args[\"--help\"]:\n if args[\"COMMAND\"] is None:\n print(usage)\n return True\n else:\n commands = dict(self.gather_commands())\n print(help_for_command(commands[args[\"COMMAND\"]]))\n return True\n return False", "n_chars_compressed": 19138, "compression_ratio": 0.999582158153139}, "tests/test_config/test_signature.py::311": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_construct_arguments_does_not_overwrite_args_and_kwargs", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_config_scope.py::93": {"resolved_imports": ["sacred/optional.py", "sacred/config/config_scope.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_fixing_nested_dicts", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_observers/test_gcs_observer.py::205": {"resolved_imports": ["sacred/observers/__init__.py"], "used_names": [], "enclosing_function": "test_artifact_event_works", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_config/test_dogmatic_dict.py::51": {"resolved_imports": ["sacred/config/custom_containers.py"], "used_names": ["DogmaticDict"], "enclosing_function": "test_dict_interface_update_with_dict", "extracted_code": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3583, "extracted_code_full": "# Source: sacred/config/custom_containers.py\nclass DogmaticDict(dict):\n def __init__(self, fixed=None, fallback=None):\n super().__init__()\n self.typechanges = {}\n self.fallback_writes = []\n self.modified = set()\n self.fixed = fixed or {}\n self._fallback = {}\n if fallback:\n self.fallback = fallback\n\n @property\n def fallback(self):\n return self._fallback\n\n @fallback.setter\n def fallback(self, newval):\n ffkeys = set(self.fixed.keys()).intersection(set(newval.keys()))\n for k in ffkeys:\n if isinstance(self.fixed[k], DogmaticDict):\n self.fixed[k].fallback = newval[k]\n elif isinstance(self.fixed[k], dict):\n self.fixed[k] = DogmaticDict(self.fixed[k])\n self.fixed[k].fallback = newval[k]\n\n self._fallback = newval\n\n def _log_blocked_setitem(self, key, value, fixed_value):\n if type_changed(value, fixed_value):\n self.typechanges[key] = (type(value), type(fixed_value))\n\n if is_different(value, fixed_value):\n self.modified.add(key)\n\n # if both are dicts recursively collect modified and typechanges\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in fixed_value.typechanges.items():\n self.typechanges[join_paths(key, k)] = val\n\n self.modified |= {join_paths(key, m) for m in fixed_value.modified}\n\n def __setitem__(self, key, value):\n if key not in self.fixed:\n if key in self.fallback:\n self.fallback_writes.append(key)\n return dict.__setitem__(self, key, value)\n\n fixed_value = self.fixed[key]\n dict.__setitem__(self, key, fixed_value)\n # if both are dicts do a recursive update\n if isinstance(fixed_value, DogmaticDict) and isinstance(value, dict):\n for k, val in value.items():\n fixed_value[k] = val\n\n self._log_blocked_setitem(key, value, fixed_value)\n\n def __getitem__(self, item):\n if dict.__contains__(self, item):\n return dict.__getitem__(self, item)\n elif item in self.fallback:\n if item in self.fixed:\n return self.fixed[item]\n else:\n return self.fallback[item]\n raise KeyError(item)\n\n def __contains__(self, item):\n return dict.__contains__(self, item) or (item in self.fallback)\n\n def get(self, k, d=None):\n if dict.__contains__(self, k):\n return dict.__getitem__(self, k)\n else:\n return self.fallback.get(k, d)\n\n def has_key(self, item):\n return self.__contains__(item)\n\n def __delitem__(self, key):\n if key not in self.fixed:\n dict.__delitem__(self, key)\n\n def update(self, iterable=None, **kwargs):\n if iterable is not None:\n if hasattr(iterable, \"keys\"):\n for key in iterable:\n self[key] = iterable[key]\n else:\n for key, value in iterable:\n self[key] = value\n for key in kwargs:\n self[key] = kwargs[key]\n\n def revelation(self):\n missing = set()\n for key in self.fixed:\n if not dict.__contains__(self, key):\n self[key] = self.fixed[key]\n missing.add(key)\n\n if isinstance(self[key], (DogmaticDict, DogmaticList)):\n missing |= {key + \".\" + k for k in self[key].revelation()}\n return missing", "n_chars_compressed": 3583, "compression_ratio": 1.0}, "tests/test_utils.py::88": {"resolved_imports": ["sacred/utils.py"], "used_names": ["join_paths"], "enclosing_function": "test_join_paths", "extracted_code": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 172, "extracted_code_full": "# Source: sacred/utils.py\ndef join_paths(*parts):\n \"\"\"Join different parts together to a valid dotted path.\"\"\"\n return \".\".join(str(p).strip(\".\") for p in parts if p)", "n_chars_compressed": 172, "compression_ratio": 1.0}, "tests/test_run.py::50": {"resolved_imports": ["sacred/run.py", "sacred/config/config_summary.py", "sacred/utils.py"], "used_names": ["datetime"], "enclosing_function": "test_run_run", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_config/test_config_dict.py::126": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": ["ConfigDict"], "enclosing_function": "test_fixed_subentry_of_preset", "extracted_code": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 658, "extracted_code_full": "# Source: sacred/config/__init__.py\n# coding=utf-8\n\nfrom sacred.config.config_dict import ConfigDict\nfrom sacred.config.config_scope import ConfigScope\nfrom sacred.config.config_files import load_config_file, save_config_file\nfrom sacred.config.captured_function import create_captured_function\nfrom sacred.config.utils import chain_evaluate_config_scopes, dogmatize, undogmatize\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n\n\n__all__ = (\n \"ConfigDict\",\n \"ConfigScope\",\n \"load_config_file\",\n \"save_config_file\",\n \"create_captured_function\",\n \"chain_evaluate_config_scopes\",\n \"dogmatize\",\n \"undogmatize\",\n)", "n_chars_compressed": 658, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::114": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock"], "enclosing_function": "test_captured_function_magic_run_argument", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_observers/test_queue_mongo_observer.py::277": {"resolved_imports": ["sacred/metrics_logger.py", "sacred/dependencies.py", "sacred/observers/mongo.py"], "used_names": ["linearize_metrics"], "enclosing_function": "test_log_metrics", "extracted_code": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_imports_parsed": 10, "n_files_resolved": 3, "n_chars_extracted": 1080, "extracted_code_full": "# Source: sacred/metrics_logger.py\ndef linearize_metrics(logged_metrics):\n \"\"\"\n Group metrics by name.\n\n Takes a list of individual measurements, possibly belonging\n to different metrics and groups them by name.\n\n :param logged_metrics: A list of ScalarMetricLogEntries\n :return: Measured values grouped by the metric name:\n {\"metric_name1\": {\"steps\": [0,1,2], \"values\": [4, 5, 6],\n \"timestamps\": [datetime, datetime, datetime]},\n \"metric_name2\": {...}}\n \"\"\"\n metrics_by_name = {}\n for metric_entry in logged_metrics:\n if metric_entry.name not in metrics_by_name:\n metrics_by_name[metric_entry.name] = {\n \"steps\": [],\n \"values\": [],\n \"timestamps\": [],\n \"name\": metric_entry.name,\n }\n metrics_by_name[metric_entry.name][\"steps\"].append(metric_entry.step)\n metrics_by_name[metric_entry.name][\"values\"].append(metric_entry.value)\n metrics_by_name[metric_entry.name][\"timestamps\"].append(metric_entry.timestamp)\n return metrics_by_name", "n_chars_compressed": 1080, "compression_ratio": 1.0}, "tests/test_config/test_config_dict.py::65": {"resolved_imports": ["sacred/optional.py", "sacred/config/__init__.py", "sacred/config/custom_containers.py"], "used_names": [], "enclosing_function": "test_adding_values", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_config/test_captured_functions.py::82": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["SETTINGS", "create_captured_function", "mock", "random"], "enclosing_function": "test_captured_function_numpy_randomness", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)\n\n\n# Source: sacred/settings.py\nSETTINGS = FrozenKeyMunch.fromDict(\n {\n \"CONFIG\": {\n # make sure all config keys are compatible with MongoDB\n \"ENFORCE_KEYS_MONGO_COMPATIBLE\": True,\n # make sure all config keys are serializable with jsonpickle\n # THIS IS IMPORTANT. Only deactivate if you know what you're doing.\n \"ENFORCE_KEYS_JSONPICKLE_COMPATIBLE\": True,\n # make sure all config keys are valid python identifiers\n \"ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS\": False,\n # make sure all config keys are strings\n \"ENFORCE_STRING_KEYS\": False,\n # make sure no config key contains an equals sign\n \"ENFORCE_KEYS_NO_EQUALS\": True,\n # if true, all dicts and lists in the configuration of a captured\n # function are replaced with a read-only container that raises an\n # Exception if it is attempted to write to those containers\n \"READ_ONLY_CONFIG\": True,\n # regex patterns to filter out certain IDE or linter directives\n # from inline comments in the documentation\n \"IGNORED_COMMENTS\": [\"^pylint:\", \"^noinspection\"],\n # if true uses the numpy legacy API, i.e. _rnd in captured functions is\n # a numpy.random.RandomState rather than numpy.random.Generator.\n # numpy.random.RandomState became legacy with numpy v1.19.\n \"NUMPY_RANDOM_LEGACY_API\": version.parse(opt.np.__version__)\n < version.parse(\"1.19\")\n if opt.has_numpy\n else False,\n },\n \"HOST_INFO\": {\n # Collect information about GPUs using the nvidia-smi tool\n \"INCLUDE_GPU_INFO\": True,\n # Collect information about CPUs using py-cpuinfo\n \"INCLUDE_CPU_INFO\": True,\n # List of ENVIRONMENT variables to store in host-info\n \"CAPTURED_ENV\": [],\n },\n \"COMMAND_LINE\": {\n # disallow string fallback, if parsing a value from command-line\n # failed\n \"STRICT_PARSING\": False,\n # show command line options that are disabled (e.g. unmet\n # dependencies)\n \"SHOW_DISABLED_OPTIONS\": True,\n },\n # configure how stdout/stderr are captured. ['no', 'sys', 'fd']\n \"CAPTURE_MODE\": \"sys\" if platform.system() == \"Windows\" else \"fd\",\n # configure how dependencies are discovered. [none, imported, sys, pkg]\n \"DISCOVER_DEPENDENCIES\": \"imported\",\n # configure how source-files are discovered. [none, imported, sys, dir]\n \"DISCOVER_SOURCES\": \"imported\",\n # Configure the default beat interval, in seconds\n \"DEFAULT_BEAT_INTERVAL\": 10.0,\n },\n)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3174, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)\n\n\n# Source: sacred/settings.py\nSETTINGS = FrozenKeyMunch.fromDict(\n {\n \"CONFIG\": {\n # make sure all config keys are compatible with MongoDB\n \"ENFORCE_KEYS_MONGO_COMPATIBLE\": True,\n # make sure all config keys are serializable with jsonpickle\n # THIS IS IMPORTANT. Only deactivate if you know what you're doing.\n \"ENFORCE_KEYS_JSONPICKLE_COMPATIBLE\": True,\n # make sure all config keys are valid python identifiers\n \"ENFORCE_VALID_PYTHON_IDENTIFIER_KEYS\": False,\n # make sure all config keys are strings\n \"ENFORCE_STRING_KEYS\": False,\n # make sure no config key contains an equals sign\n \"ENFORCE_KEYS_NO_EQUALS\": True,\n # if true, all dicts and lists in the configuration of a captured\n # function are replaced with a read-only container that raises an\n # Exception if it is attempted to write to those containers\n \"READ_ONLY_CONFIG\": True,\n # regex patterns to filter out certain IDE or linter directives\n # from inline comments in the documentation\n \"IGNORED_COMMENTS\": [\"^pylint:\", \"^noinspection\"],\n # if true uses the numpy legacy API, i.e. _rnd in captured functions is\n # a numpy.random.RandomState rather than numpy.random.Generator.\n # numpy.random.RandomState became legacy with numpy v1.19.\n \"NUMPY_RANDOM_LEGACY_API\": version.parse(opt.np.__version__)\n < version.parse(\"1.19\")\n if opt.has_numpy\n else False,\n },\n \"HOST_INFO\": {\n # Collect information about GPUs using the nvidia-smi tool\n \"INCLUDE_GPU_INFO\": True,\n # Collect information about CPUs using py-cpuinfo\n \"INCLUDE_CPU_INFO\": True,\n # List of ENVIRONMENT variables to store in host-info\n \"CAPTURED_ENV\": [],\n },\n \"COMMAND_LINE\": {\n # disallow string fallback, if parsing a value from command-line\n # failed\n \"STRICT_PARSING\": False,\n # show command line options that are disabled (e.g. unmet\n # dependencies)\n \"SHOW_DISABLED_OPTIONS\": True,\n },\n # configure how stdout/stderr are captured. ['no', 'sys', 'fd']\n \"CAPTURE_MODE\": \"sys\" if platform.system() == \"Windows\" else \"fd\",\n # configure how dependencies are discovered. [none, imported, sys, pkg]\n \"DISCOVER_DEPENDENCIES\": \"imported\",\n # configure how source-files are discovered. [none, imported, sys, dir]\n \"DISCOVER_SOURCES\": \"imported\",\n # Configure the default beat interval, in seconds\n \"DEFAULT_BEAT_INTERVAL\": 10.0,\n },\n)", "n_chars_compressed": 3174, "compression_ratio": 1.0}, "tests/test_config/test_signature.py::267": {"resolved_imports": ["sacred/config/signature.py", "sacred/utils.py"], "used_names": ["Signature"], "enclosing_function": "test_construct_arguments_without_options_returns_same_args_kwargs", "extracted_code": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4785, "extracted_code_full": "# Source: sacred/config/signature.py\nclass Signature:\n \"\"\"\n Extracts and stores information about the signature of a function.\n\n name : the functions name\n arguments : list of all arguments\n vararg_name : name of the *args variable\n kw_wildcard_name : name of the **kwargs variable\n positional_args : list of all positional-only arguments\n kwargs : dict of all keyword arguments mapped to their default\n \"\"\"\n\n def __init__(self, f):\n self.name = f.__name__\n args, vararg_name, kw_wildcard_name, pos_args, kwargs = get_argspec(f)\n self.arguments = args\n self.vararg_name = vararg_name\n self.kw_wildcard_name = kw_wildcard_name\n self.positional_args = pos_args\n self.kwargs = kwargs\n\n def get_free_parameters(self, args, kwargs, bound=False):\n expected_args = self._get_expected_args(bound)\n return [a for a in expected_args[len(args) :] if a not in kwargs]\n\n def construct_arguments(self, args, kwargs, options, bound=False):\n \"\"\"\n Construct args list and kwargs dictionary for this signature.\n\n They are created such that:\n - the original explicit call arguments (args, kwargs) are preserved\n - missing arguments are filled in by name using options (if possible)\n - default arguments are overridden by options\n - TypeError is thrown if:\n * kwargs contains one or more unexpected keyword arguments\n * conflicting values for a parameter in both args and kwargs\n * there is an unfilled parameter at the end of this process\n \"\"\"\n expected_args = self._get_expected_args(bound)\n self._assert_no_unexpected_args(expected_args, args)\n self._assert_no_unexpected_kwargs(expected_args, kwargs)\n self._assert_no_duplicate_args(expected_args, args, kwargs)\n\n args, kwargs = self._fill_in_options(args, kwargs, options, bound)\n\n self._assert_no_missing_args(args, kwargs, bound)\n return args, kwargs\n\n def __str__(self):\n pos_args = self.positional_args\n varg = [\"*\" + self.vararg_name] if self.vararg_name else []\n kwargs = [\"{}={}\".format(n, v.__repr__()) for n, v in self.kwargs.items()]\n kw_wc = [\"**\" + self.kw_wildcard_name] if self.kw_wildcard_name else []\n arglist = pos_args + varg + kwargs + kw_wc\n return \"{}({})\".format(self.name, \", \".join(arglist))\n\n def __repr__(self):\n return \"\".format(self.name, id(self))\n\n def _get_expected_args(self, bound):\n if bound:\n # When called as instance method, the instance ('self') will be\n # passed as first argument automatically, so the first argument\n # should be excluded from the signature during this invocation.\n return self.arguments[1:]\n else:\n return self.arguments\n\n def _assert_no_unexpected_args(self, expected_args, args):\n if not self.vararg_name and len(args) > len(expected_args):\n unexpected_args = args[len(expected_args) :]\n raise SignatureError(\n \"{} got unexpected argument(s): {}\".format(self.name, unexpected_args)\n )\n\n def _assert_no_unexpected_kwargs(self, expected_args, kwargs):\n if self.kw_wildcard_name:\n return\n unexpected_kwargs = set(kwargs) - set(expected_args)\n if unexpected_kwargs:\n raise SignatureError(\n \"{} got unexpected kwarg(s): {}\".format(\n self.name, sorted(unexpected_kwargs)\n )\n )\n\n def _assert_no_duplicate_args(self, expected_args, args, kwargs):\n positional_arguments = expected_args[: len(args)]\n duplicate_arguments = [v for v in positional_arguments if v in kwargs]\n if duplicate_arguments:\n raise SignatureError(\n \"{} got multiple values for argument(s) {}\".format(\n self.name, duplicate_arguments\n )\n )\n\n def _fill_in_options(self, args, kwargs, options, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n new_kwargs = dict(kwargs) if free_params else kwargs\n for param in free_params:\n if param in options:\n new_kwargs[param] = options[param]\n return args, new_kwargs\n\n def _assert_no_missing_args(self, args, kwargs, bound):\n free_params = self.get_free_parameters(args, kwargs, bound)\n missing_args = [m for m in free_params if m not in self.kwargs]\n if missing_args:\n raise MissingConfigError(\n \"{} is missing value(s):\".format(self.name),\n missing_configs=missing_args,\n )", "n_chars_compressed": 4785, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::60": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock", "random"], "enclosing_function": "test_captured_function_randomness", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_config/test_captured_functions.py::56": {"resolved_imports": ["sacred/optional.py", "sacred/config/captured_function.py", "sacred/settings.py"], "used_names": ["create_captured_function", "mock", "random"], "enclosing_function": "test_captured_function_randomness", "extracted_code": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 407, "extracted_code_full": "# Source: sacred/config/captured_function.py\ndef create_captured_function(function, prefix=None):\n sig = Signature(function)\n function.signature = sig\n function.uses_randomness = \"_seed\" in sig.arguments or \"_rnd\" in sig.arguments\n function.logger = None\n function.config = {}\n function.rnd = None\n function.run = None\n function.prefix = prefix\n return captured_function(function)", "n_chars_compressed": 407, "compression_ratio": 1.0}, "tests/test_experiment.py::80": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": ["ConfigAddedError", "pytest"], "enclosing_function": "test_fails_on_unused_config_updates", "extracted_code": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1301, "extracted_code_full": "# Source: sacred/utils.py\nclass ConfigAddedError(ConfigError):\n SPECIAL_ARGS = {\"_log\", \"_config\", \"_seed\", \"__doc__\", \"config_filename\", \"_run\"}\n \"\"\"Special args that show up in the captured args but can never be set\n by the user\"\"\"\n\n def __init__(\n self,\n conflicting_configs,\n message=\"Added new config entry that is not used anywhere\",\n captured_args=(),\n print_conflicting_configs=True,\n print_traceback=False,\n filter_traceback=\"default\",\n print_usage=False,\n print_suggestions=True,\n config=None,\n ):\n super().__init__(\n message,\n conflicting_configs=conflicting_configs,\n print_conflicting_configs=print_conflicting_configs,\n print_traceback=print_traceback,\n filter_traceback=filter_traceback,\n print_usage=print_usage,\n config=config,\n )\n self.captured_args = captured_args\n self.print_suggestions = print_suggestions\n\n def __str__(self):\n s = super().__str__()\n if self.print_suggestions:\n possible_keys = set(self.captured_args) - self.SPECIAL_ARGS\n if possible_keys:\n s += \"\\nPossible config keys are: {}\".format(possible_keys)\n return s", "n_chars_compressed": 1301, "compression_ratio": 1.0}, "tests/test_experiment.py::29": {"resolved_imports": ["sacred/__init__.py", "sacred/experiment.py", "sacred/utils.py"], "used_names": [], "enclosing_function": "test_main", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 0}}} \ No newline at end of file