Skip to main content
  • Home
  • Development
  • Documentation
  • Donate
  • Operational login
  • Browse the archive

swh logo
SoftwareHeritage
Software
Heritage
Archive
Features
  • Search

  • Downloads

  • Save code now

  • Add forge now

  • Help

Revision 1db48f3a735eb0fba06a7d503f080a7ead512604 authored by Artem Artemev on 11 July 2018, 12:50:44 UTC, committed by GitHub on 11 July 2018, 12:50:44 UTC
Update version.py file to 1.2.0 (#812)
1 parent 707b195
  • Files
  • Changes
  • 2109064
  • /
  • gpflow
  • /
  • _settings.py
Raw File Download

To reference or cite the objects present in the Software Heritage archive, permalinks based on SoftWare Hash IDentifiers (SWHIDs) must be used.
Select below a type of object currently browsed in order to display its associated SWHID and permalink.

  • revision
  • directory
  • content
revision badge
swh:1:rev:1db48f3a735eb0fba06a7d503f080a7ead512604
directory badge
swh:1:dir:610a67848d5a0de08f1f6810ca38d989c257d9cb
content badge
swh:1:cnt:0315f7c6ecdcca8afa121bca3e9c77e37a1ecf69

This interface enables to generate software citations, provided that the root directory of browsed objects contains a citation.cff or codemeta.json file.
Select below a type of object currently browsed in order to generate citations for them.

  • revision
  • directory
  • content
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
Generate software citation in BibTex format (requires biblatex-software package)
Generating citation ...
_settings.py
import os
import copy
import collections
import warnings
import logging
import inspect

from collections import OrderedDict
from six.moves import configparser

import numpy as np
import tensorflow as tf



class _SettingsContextManager(object):
    def __init__(self, manager, tmp_settings):
        self._manager = manager
        self._tmp_settings = tmp_settings

    def __enter__(self):
        self._manager.push(self._tmp_settings)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._manager.pop()


class _SettingsManager(object):
    def __init__(self, cur_settings):
        self._cur_settings = cur_settings
        self._settings_stack = []

    def __getattr__(self, name):
        try:
            return self._cur_settings[name]
        except KeyError:
            raise AttributeError("Unknown setting.")

    def push(self, extra_settings):
        self._settings_stack.append(self._cur_settings)
        self._cur_settings = extra_settings

    def pop(self):
        rem = self._cur_settings
        self._cur_settings = self._settings_stack.pop()
        return rem

    def temp_settings(self, tmp_settings):
        return _SettingsContextManager(self, tmp_settings)

    def get_settings(self):
        return copy.deepcopy(self._cur_settings)

    @property
    def jitter(self):
        return self.numerics.jitter_level

    @property
    def tf_float(self):
        warnings.warn('tf_float is deprecated and will be removed at GPflow '
                      'version 1.2.0. Use float_type.', DeprecationWarning)
        return self.float_type

    @property
    def tf_int(self):
        warnings.warn('tf_int is deprecated and will be removed at GPflow '
                      'version 1.2.0. Use int_type.', DeprecationWarning)
        return self.int_type

    @property
    def np_float(self):
        warnings.warn('np_float is deprecated and will be removed at GPflow '
                      'version 1.2.0. Use float_type.', DeprecationWarning)
        return self.float_type

    @property
    def np_int(self):
        warnings.warn('np_int is deprecated and will be removed at GPflow '
                      'version 1.2.0. Use int_type.', DeprecationWarning)
        return self.int_type

    @property
    def float_type(self):
        return self.dtypes.float_type

    @property
    def int_type(self):
        return self.dtypes.int_type

    @property
    def logging_level(self):
        return self.logging.level

    def logger(self):
        frame = inspect.currentframe().f_back
        module = inspect.getmodule(frame)
        name = 'gpflow' if module is None else module.__name__
        level = logging.getLevelName(self.logging.level)
        logging.basicConfig()
        log = logging.getLogger(name)
        log.setLevel(level)
        return log


class _MutableNamedTuple(OrderedDict):
    """
    A class that doubles as a mutable named tuple, to allow settings
    to be re-set during
    """
    def __init__(self, *args, **kwargs):
        super(_MutableNamedTuple, self).__init__(*args, **kwargs)
        self._settings_stack = []
        self._initialised = True

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        if not hasattr(self, "_initialised"):
            super(_MutableNamedTuple, self).__setattr__(name, value)
        else:
            super(_MutableNamedTuple, self).__setitem__(name, value)


# a very simple parser
def _parse(string):
    """
    Very simple config values parser.
    """
    if not isinstance(string, str):
        raise ValueError('Config value "{0}" expected to be string.'
                         .format(string))
    if string in ['true', 'True']:
        return True
    elif string in ['false', 'False']:
        return False
    elif string in ['float64', 'float32', 'float16',
                    'int64', 'int32', 'int16']:
        return getattr(np, string)
    else:
        try:
            return int(string)
        except ValueError:
            pass
        try:
            return float(string)
        except ValueError:
            return string


def _namedtuplify(mapping):
    """
    Make the dictionary into a nested series of named tuples.
    This is what allows accessing by attribute: settings.numerics.jitter
    Thank you https://gist.github.com/hangtwenty/5960435
    """
    if isinstance(mapping, collections.Mapping):
        for key, value in list(mapping.items()):
            mapping[key] = _namedtuplify(value)
        try:
            mapping.pop('__name__')
        except KeyError:
            pass
        # return collections.namedtuple('settingsa', dict(**mapping))(**mapping)
        return _MutableNamedTuple(mapping)
    return _parse(mapping)


def _read_config_file(path=None):
    """
    Reads config file.
    First look for config file in the current directory, then in the
    user's home directory, then in the same directory as this file.
    Tries to find config file both with and without preceeding 'dot'
    for hidden files (prefer non-hidden).
    """
    cfg = configparser.ConfigParser()

    if path is None:  # pragma: no cover
        dirs = [os.curdir, os.path.expanduser('~'),
                os.path.dirname(os.path.realpath(__file__))]
        locations = map(os.path.abspath, dirs)
        for loc in locations:
            if cfg.read(os.path.join(loc, 'gpflowrc')):
                break
            if cfg.read(os.path.join(loc, '.gpflowrc')):
                break
    else:
        if not cfg.read(path):
            raise RuntimeError("Config at '{0}' cannot be read".format(path))
    return cfg


__CONFIG = _read_config_file()
__LOADED_SETTINGS = _namedtuplify(__CONFIG._sections)

SETTINGS = _SettingsManager(__LOADED_SETTINGS) # pylint: disable=C0103
The diff you're trying to view is too large. Only the first 1000 changed files have been loaded.
Showing with 0 additions and 0 deletions (0 / 0 diffs computed)
swh spinner

Computing file changes ...

back to top

Software Heritage — Copyright (C) 2015–2026, The Software Heritage developers. License: GNU AGPLv3+.
The source code of Software Heritage itself is available on our development forge.
The source code files archived by Software Heritage are available under their own copyright and licenses.
Terms of use: Archive access, API— Content policy— Contact— JavaScript license information— Web API