repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
zblz/naima
naima/radiative.py
PionDecay._diffsigma
def _diffsigma(self, Ep, Egamma): """ Differential cross section dsigma/dEg = Amax(Tp) * F(Tp,Egamma) """ Tp = Ep - self._m_p diffsigma = self._Amax(Tp) * self._F(Tp, Egamma) if self.nuclear_enhancement: diffsigma *= self._nuclear_factor(Tp) ...
python
def _diffsigma(self, Ep, Egamma): """ Differential cross section dsigma/dEg = Amax(Tp) * F(Tp,Egamma) """ Tp = Ep - self._m_p diffsigma = self._Amax(Tp) * self._F(Tp, Egamma) if self.nuclear_enhancement: diffsigma *= self._nuclear_factor(Tp) ...
[ "def", "_diffsigma", "(", "self", ",", "Ep", ",", "Egamma", ")", ":", "Tp", "=", "Ep", "-", "self", ".", "_m_p", "diffsigma", "=", "self", ".", "_Amax", "(", "Tp", ")", "*", "self", ".", "_F", "(", "Tp", ",", "Egamma", ")", "if", "self", ".", ...
Differential cross section dsigma/dEg = Amax(Tp) * F(Tp,Egamma)
[ "Differential", "cross", "section" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1513-L1526
train
zblz/naima
naima/radiative.py
PionDecay._nuclear_factor
def _nuclear_factor(self, Tp): """ Compute nuclear enhancement factor """ sigmaRpp = 10 * np.pi * 1e-27 sigmainel = self._sigma_inel(Tp) sigmainel0 = self._sigma_inel(1e3) # at 1e3 GeV f = sigmainel / sigmainel0 f2 = np.where(f > 1, f, 1.0) G = 1....
python
def _nuclear_factor(self, Tp): """ Compute nuclear enhancement factor """ sigmaRpp = 10 * np.pi * 1e-27 sigmainel = self._sigma_inel(Tp) sigmainel0 = self._sigma_inel(1e3) # at 1e3 GeV f = sigmainel / sigmainel0 f2 = np.where(f > 1, f, 1.0) G = 1....
[ "def", "_nuclear_factor", "(", "self", ",", "Tp", ")", ":", "sigmaRpp", "=", "10", "*", "np", ".", "pi", "*", "1e-27", "sigmainel", "=", "self", ".", "_sigma_inel", "(", "Tp", ")", "sigmainel0", "=", "self", ".", "_sigma_inel", "(", "1e3", ")", "f", ...
Compute nuclear enhancement factor
[ "Compute", "nuclear", "enhancement", "factor" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1528-L1555
train
zblz/naima
naima/radiative.py
PionDecayKelner06._Fgamma
def _Fgamma(self, x, Ep): """ KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV] """ L = np.log(Ep) B = 1.30 + 0.14 * L + 0.011 * L ** 2 ...
python
def _Fgamma(self, x, Ep): """ KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV] """ L = np.log(Ep) B = 1.30 + 0.14 * L + 0.011 * L ** 2 ...
[ "def", "_Fgamma", "(", "self", ",", "x", ",", "Ep", ")", ":", "L", "=", "np", ".", "log", "(", "Ep", ")", "B", "=", "1.30", "+", "0.14", "*", "L", "+", "0.011", "*", "L", "**", "2", "beta", "=", "(", "1.79", "+", "0.11", "*", "L", "+", ...
KAB06 Eq.58 Note: Quantities are not used in this function Parameters ---------- x : float Egamma/Eprot Ep : float Eprot [TeV]
[ "KAB06", "Eq", ".", "58" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1673-L1699
train
zblz/naima
naima/radiative.py
PionDecayKelner06._sigma_inel
def _sigma_inel(self, Ep): """ Inelastic cross-section for p-p interaction. KAB06 Eq. 73, 79 Note: Quantities are not used in this function Parameters ---------- Ep : float Eprot [TeV] Returns ------- sigma_inel : float I...
python
def _sigma_inel(self, Ep): """ Inelastic cross-section for p-p interaction. KAB06 Eq. 73, 79 Note: Quantities are not used in this function Parameters ---------- Ep : float Eprot [TeV] Returns ------- sigma_inel : float I...
[ "def", "_sigma_inel", "(", "self", ",", "Ep", ")", ":", "L", "=", "np", ".", "log", "(", "Ep", ")", "sigma", "=", "34.3", "+", "1.88", "*", "L", "+", "0.25", "*", "L", "**", "2", "if", "Ep", "<=", "0.1", ":", "Eth", "=", "1.22e-3", "sigma", ...
Inelastic cross-section for p-p interaction. KAB06 Eq. 73, 79 Note: Quantities are not used in this function Parameters ---------- Ep : float Eprot [TeV] Returns ------- sigma_inel : float Inelastic cross-section for p-p interaction [1/c...
[ "Inelastic", "cross", "-", "section", "for", "p", "-", "p", "interaction", ".", "KAB06", "Eq", ".", "73", "79" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1701-L1723
train
zblz/naima
naima/radiative.py
PionDecayKelner06._photon_integrand
def _photon_integrand(self, x, Egamma): """ Integrand of Eq. 72 """ try: return ( self._sigma_inel(Egamma / x) * self._particle_distribution((Egamma / x)) * self._Fgamma(x, Egamma / x) / x ) e...
python
def _photon_integrand(self, x, Egamma): """ Integrand of Eq. 72 """ try: return ( self._sigma_inel(Egamma / x) * self._particle_distribution((Egamma / x)) * self._Fgamma(x, Egamma / x) / x ) e...
[ "def", "_photon_integrand", "(", "self", ",", "x", ",", "Egamma", ")", ":", "try", ":", "return", "(", "self", ".", "_sigma_inel", "(", "Egamma", "/", "x", ")", "*", "self", ".", "_particle_distribution", "(", "(", "Egamma", "/", "x", ")", ")", "*", ...
Integrand of Eq. 72
[ "Integrand", "of", "Eq", ".", "72" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1725-L1737
train
zblz/naima
naima/radiative.py
PionDecayKelner06._calc_specpp_hiE
def _calc_specpp_hiE(self, Egamma): """ Spectrum computed as in Eq. 42 for Egamma >= 0.1 TeV """ # Fixed quad with n=40 is about 15 times faster and is always within # 0.5% of the result of adaptive quad for Egamma>0.1 # WARNING: It also produces artifacts for steep distr...
python
def _calc_specpp_hiE(self, Egamma): """ Spectrum computed as in Eq. 42 for Egamma >= 0.1 TeV """ # Fixed quad with n=40 is about 15 times faster and is always within # 0.5% of the result of adaptive quad for Egamma>0.1 # WARNING: It also produces artifacts for steep distr...
[ "def", "_calc_specpp_hiE", "(", "self", ",", "Egamma", ")", ":", "from", "scipy", ".", "integrate", "import", "quad", "Egamma", "=", "Egamma", ".", "to", "(", "\"TeV\"", ")", ".", "value", "specpp", "=", "(", "c", ".", "cgs", ".", "value", "*", "quad...
Spectrum computed as in Eq. 42 for Egamma >= 0.1 TeV
[ "Spectrum", "computed", "as", "in", "Eq", ".", "42", "for", "Egamma", ">", "=", "0", ".", "1", "TeV" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1739-L1765
train
zblz/naima
naima/radiative.py
PionDecayKelner06._calc_specpp_loE
def _calc_specpp_loE(self, Egamma): """ Delta-functional approximation for low energies Egamma < 0.1 TeV """ from scipy.integrate import quad Egamma = Egamma.to("TeV").value Epimin = Egamma + self._m_pi ** 2 / (4 * Egamma) result = ( 2 * ...
python
def _calc_specpp_loE(self, Egamma): """ Delta-functional approximation for low energies Egamma < 0.1 TeV """ from scipy.integrate import quad Egamma = Egamma.to("TeV").value Epimin = Egamma + self._m_pi ** 2 / (4 * Egamma) result = ( 2 * ...
[ "def", "_calc_specpp_loE", "(", "self", ",", "Egamma", ")", ":", "from", "scipy", ".", "integrate", "import", "quad", "Egamma", "=", "Egamma", ".", "to", "(", "\"TeV\"", ")", ".", "value", "Epimin", "=", "Egamma", "+", "self", ".", "_m_pi", "**", "2", ...
Delta-functional approximation for low energies Egamma < 0.1 TeV
[ "Delta", "-", "functional", "approximation", "for", "low", "energies", "Egamma", "<", "0", ".", "1", "TeV" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1783-L1799
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
get_config_path
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): """ Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific names...
python
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): """ Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific names...
[ "def", "get_config_path", "(", "appdirs", "=", "DEFAULT_APPDIRS", ",", "file_name", "=", "DEFAULT_CONFIG_FILENAME", ")", ":", "return", "os", ".", "path", ".", "join", "(", "appdirs", ".", "user_config_dir", ",", "file_name", ")" ]
Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults ...
[ "Return", "the", "path", "where", "the", "config", "file", "is", "stored", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L141-L155
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
write_config_file
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): """ Write a ConfigParser instance to file at the correct location. Args: config_instance: Config instance to safe to file. appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` insta...
python
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): """ Write a ConfigParser instance to file at the correct location. Args: config_instance: Config instance to safe to file. appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` insta...
[ "def", "write_config_file", "(", "config_instance", ",", "appdirs", "=", "DEFAULT_APPDIRS", ",", "file_name", "=", "DEFAULT_CONFIG_FILENAME", ")", ":", "path", "=", "get_config_path", "(", "appdirs", ",", "file_name", ")", "with", "open", "(", "path", ",", "'w'"...
Write a ConfigParser instance to file at the correct location. Args: config_instance: Config instance to safe to file. appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config ...
[ "Write", "a", "ConfigParser", "instance", "to", "file", "at", "the", "correct", "location", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L158-L177
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
load_config_file
def load_config_file(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME, fallback_config_instance=None): """ Retrieve config information from file at default location. If no config file is found a new one will be created either with ``fallback_config_instance`` as content or if none is ...
python
def load_config_file(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME, fallback_config_instance=None): """ Retrieve config information from file at default location. If no config file is found a new one will be created either with ``fallback_config_instance`` as content or if none is ...
[ "def", "load_config_file", "(", "appdirs", "=", "DEFAULT_APPDIRS", ",", "file_name", "=", "DEFAULT_CONFIG_FILENAME", ",", "fallback_config_instance", "=", "None", ")", ":", "if", "not", "fallback_config_instance", ":", "fallback_config_instance", "=", "backend_config_to_c...
Retrieve config information from file at default location. If no config file is found a new one will be created either with ``fallback_config_instance`` as content or if none is provided with the result of ``get_default_backend_config``. Args: appdirs (HamsterAppDirs, optional): ``HamsterAppDirs``...
[ "Retrieve", "config", "information", "from", "file", "at", "default", "location", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L180-L211
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
get_default_backend_config
def get_default_backend_config(appdirs): """ Return a default config dictionary. Args: appdirs (HamsterAppDirs): ``HamsterAppDirs`` instance encapsulating the apps details. Returns: dict: Dictionary with a default configuration. Note: Those defaults are independent of the ...
python
def get_default_backend_config(appdirs): """ Return a default config dictionary. Args: appdirs (HamsterAppDirs): ``HamsterAppDirs`` instance encapsulating the apps details. Returns: dict: Dictionary with a default configuration. Note: Those defaults are independent of the ...
[ "def", "get_default_backend_config", "(", "appdirs", ")", ":", "return", "{", "'store'", ":", "'sqlalchemy'", ",", "'day_start'", ":", "datetime", ".", "time", "(", "5", ",", "30", ",", "0", ")", ",", "'fact_min_delta'", ":", "1", ",", "'tmpfile_path'", ":...
Return a default config dictionary. Args: appdirs (HamsterAppDirs): ``HamsterAppDirs`` instance encapsulating the apps details. Returns: dict: Dictionary with a default configuration. Note: Those defaults are independent of the particular config-store.
[ "Return", "a", "default", "config", "dictionary", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L214-L234
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
backend_config_to_configparser
def backend_config_to_configparser(config): """ Return a ConfigParser instance representing a given backend config dictionary. Args: config (dict): Dictionary of config key/value pairs. Returns: SafeConfigParser: SafeConfigParser instance representing config. Note: We do n...
python
def backend_config_to_configparser(config): """ Return a ConfigParser instance representing a given backend config dictionary. Args: config (dict): Dictionary of config key/value pairs. Returns: SafeConfigParser: SafeConfigParser instance representing config. Note: We do n...
[ "def", "backend_config_to_configparser", "(", "config", ")", ":", "def", "get_store", "(", ")", ":", "return", "config", ".", "get", "(", "'store'", ")", "def", "get_day_start", "(", ")", ":", "day_start", "=", "config", ".", "get", "(", "'day_start'", ")"...
Return a ConfigParser instance representing a given backend config dictionary. Args: config (dict): Dictionary of config key/value pairs. Returns: SafeConfigParser: SafeConfigParser instance representing config. Note: We do not provide *any* validation about mandatory values what ...
[ "Return", "a", "ConfigParser", "instance", "representing", "a", "given", "backend", "config", "dictionary", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L239-L302
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
configparser_to_backend_config
def configparser_to_backend_config(cp_instance): """ Return a config dict generated from a configparser instance. This functions main purpose is to ensure config dict values are properly typed. Note: This can be used with any ``ConfigParser`` backend instance not just the default one i...
python
def configparser_to_backend_config(cp_instance): """ Return a config dict generated from a configparser instance. This functions main purpose is to ensure config dict values are properly typed. Note: This can be used with any ``ConfigParser`` backend instance not just the default one i...
[ "def", "configparser_to_backend_config", "(", "cp_instance", ")", ":", "def", "get_store", "(", ")", ":", "store", "=", "cp_instance", ".", "get", "(", "'Backend'", ",", "'store'", ")", "if", "store", "not", "in", "hamster_lib", ".", "REGISTERED_BACKENDS", "."...
Return a config dict generated from a configparser instance. This functions main purpose is to ensure config dict values are properly typed. Note: This can be used with any ``ConfigParser`` backend instance not just the default one in order to extract its config. If a key is not found ...
[ "Return", "a", "config", "dict", "generated", "from", "a", "configparser", "instance", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L310-L381
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
HamsterAppDirs.user_data_dir
def user_data_dir(self): """Return ``user_data_dir``.""" directory = appdirs.user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) if self.create: self._ensure_directory_exists(directory) return directory
python
def user_data_dir(self): """Return ``user_data_dir``.""" directory = appdirs.user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming) if self.create: self._ensure_directory_exists(directory) return directory
[ "def", "user_data_dir", "(", "self", ")", ":", "directory", "=", "appdirs", ".", "user_data_dir", "(", "self", ".", "appname", ",", "self", ".", "appauthor", ",", "version", "=", "self", ".", "version", ",", "roaming", "=", "self", ".", "roaming", ")", ...
Return ``user_data_dir``.
[ "Return", "user_data_dir", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L76-L82
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
HamsterAppDirs.site_config_dir
def site_config_dir(self): """Return ``site_config_dir``.""" directory = appdirs.site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) if self.create: self._ensure_directory_exists(directory) return director...
python
def site_config_dir(self): """Return ``site_config_dir``.""" directory = appdirs.site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath) if self.create: self._ensure_directory_exists(directory) return director...
[ "def", "site_config_dir", "(", "self", ")", ":", "directory", "=", "appdirs", ".", "site_config_dir", "(", "self", ".", "appname", ",", "self", ".", "appauthor", ",", "version", "=", "self", ".", "version", ",", "multipath", "=", "self", ".", "multipath", ...
Return ``site_config_dir``.
[ "Return", "site_config_dir", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L103-L109
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
HamsterAppDirs.user_cache_dir
def user_cache_dir(self): """Return ``user_cache_dir``.""" directory = appdirs.user_cache_dir(self.appname, self.appauthor, version=self.version) if self.create: self._ensure_directory_exists(directory) return directory
python
def user_cache_dir(self): """Return ``user_cache_dir``.""" directory = appdirs.user_cache_dir(self.appname, self.appauthor, version=self.version) if self.create: self._ensure_directory_exists(directory) return directory
[ "def", "user_cache_dir", "(", "self", ")", ":", "directory", "=", "appdirs", ".", "user_cache_dir", "(", "self", ".", "appname", ",", "self", ".", "appauthor", ",", "version", "=", "self", ".", "version", ")", "if", "self", ".", "create", ":", "self", ...
Return ``user_cache_dir``.
[ "Return", "user_cache_dir", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L112-L118
train
projecthamster/hamster-lib
hamster_lib/helpers/config_helpers.py
HamsterAppDirs._ensure_directory_exists
def _ensure_directory_exists(self, directory): """Ensure that the passed path exists.""" if not os.path.lexists(directory): os.makedirs(directory) return directory
python
def _ensure_directory_exists(self, directory): """Ensure that the passed path exists.""" if not os.path.lexists(directory): os.makedirs(directory) return directory
[ "def", "_ensure_directory_exists", "(", "self", ",", "directory", ")", ":", "if", "not", "os", ".", "path", ".", "lexists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "return", "directory" ]
Ensure that the passed path exists.
[ "Ensure", "that", "the", "passed", "path", "exists", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/config_helpers.py#L129-L133
train
projecthamster/hamster-lib
hamster_lib/helpers/helpers.py
_load_tmp_fact
def _load_tmp_fact(filepath): """ Load an 'ongoing fact' from a given location. Args: filepath: Full path to the tmpfile location. Returns: hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False`` if no file was found. Raises: TypeError: If...
python
def _load_tmp_fact(filepath): """ Load an 'ongoing fact' from a given location. Args: filepath: Full path to the tmpfile location. Returns: hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False`` if no file was found. Raises: TypeError: If...
[ "def", "_load_tmp_fact", "(", "filepath", ")", ":", "from", "hamster_lib", "import", "Fact", "try", ":", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "fobj", ":", "fact", "=", "pickle", ".", "load", "(", "fobj", ")", "except", "IOError", ":...
Load an 'ongoing fact' from a given location. Args: filepath: Full path to the tmpfile location. Returns: hamster_lib.Fact: ``Fact`` representing the 'ongoing fact'. Returns ``False`` if no file was found. Raises: TypeError: If for some reason our stored instance is no...
[ "Load", "an", "ongoing", "fact", "from", "a", "given", "location", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/helpers.py#L33-L62
train
projecthamster/hamster-lib
hamster_lib/helpers/helpers.py
parse_raw_fact
def parse_raw_fact(raw_fact): """ Extract semantically meaningful sub-components from a ``raw fact`` text. Args: raw_fact (text_type): ``raw fact`` text to be parsed. Returns: dict: dict with sub-components as values. """ def at_split(string): """ Return everyth...
python
def parse_raw_fact(raw_fact): """ Extract semantically meaningful sub-components from a ``raw fact`` text. Args: raw_fact (text_type): ``raw fact`` text to be parsed. Returns: dict: dict with sub-components as values. """ def at_split(string): """ Return everyth...
[ "def", "parse_raw_fact", "(", "raw_fact", ")", ":", "def", "at_split", "(", "string", ")", ":", "result", "=", "string", ".", "split", "(", "'@'", ",", "1", ")", "length", "=", "len", "(", "result", ")", "if", "length", "==", "1", ":", "front", ","...
Extract semantically meaningful sub-components from a ``raw fact`` text. Args: raw_fact (text_type): ``raw fact`` text to be parsed. Returns: dict: dict with sub-components as values.
[ "Extract", "semantically", "meaningful", "sub", "-", "components", "from", "a", "raw", "fact", "text", "." ]
bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/helpers.py#L65-L147
train
zblz/naima
naima/analysis.py
read_run
def read_run(filename, modelfn=None): """ Read chain from a hdf5 saved with `save_run`. This function will also read the labels, data table, and metadata blobs stored in the original sampler. If you want to use the result object with `plot_fit` and setting the ``e_range`` parameter, you must provid...
python
def read_run(filename, modelfn=None): """ Read chain from a hdf5 saved with `save_run`. This function will also read the labels, data table, and metadata blobs stored in the original sampler. If you want to use the result object with `plot_fit` and setting the ``e_range`` parameter, you must provid...
[ "def", "read_run", "(", "filename", ",", "modelfn", "=", "None", ")", ":", "result", "=", "_result", "(", ")", "result", ".", "modelfn", "=", "modelfn", "result", ".", "run_info", "=", "{", "}", "f", "=", "h5py", ".", "File", "(", "filename", ",", ...
Read chain from a hdf5 saved with `save_run`. This function will also read the labels, data table, and metadata blobs stored in the original sampler. If you want to use the result object with `plot_fit` and setting the ``e_range`` parameter, you must provide the model function with the `modelfn` argume...
[ "Read", "chain", "from", "a", "hdf5", "saved", "with", "save_run", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/analysis.py#L530-L627
train
zblz/naima
examples/RXJ1713_IC_minimal.py
ElectronIC
def ElectronIC(pars, data): """ Define particle distribution model, radiative model, and return model flux at data energy values """ ECPL = ExponentialCutoffPowerLaw( pars[0] / u.eV, 10.0 * u.TeV, pars[1], 10 ** pars[2] * u.TeV ) IC = InverseCompton(ECPL, seed_photon_fields=["CMB"])...
python
def ElectronIC(pars, data): """ Define particle distribution model, radiative model, and return model flux at data energy values """ ECPL = ExponentialCutoffPowerLaw( pars[0] / u.eV, 10.0 * u.TeV, pars[1], 10 ** pars[2] * u.TeV ) IC = InverseCompton(ECPL, seed_photon_fields=["CMB"])...
[ "def", "ElectronIC", "(", "pars", ",", "data", ")", ":", "ECPL", "=", "ExponentialCutoffPowerLaw", "(", "pars", "[", "0", "]", "/", "u", ".", "eV", ",", "10.0", "*", "u", ".", "TeV", ",", "pars", "[", "1", "]", ",", "10", "**", "pars", "[", "2"...
Define particle distribution model, radiative model, and return model flux at data energy values
[ "Define", "particle", "distribution", "model", "radiative", "model", "and", "return", "model", "flux", "at", "data", "energy", "values" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/examples/RXJ1713_IC_minimal.py#L13-L24
train
zblz/naima
naima/sherpa_models.py
SherpaModelECPL._pdist
def _pdist(p): """ Return PL or ECPL instance based on parameters p """ index, ref, ampl, cutoff, beta = p[:5] if cutoff == 0.0: pdist = models.PowerLaw( ampl * 1e30 * u.Unit("1/eV"), ref * u.TeV, index ) else: pdist = models.Exponentia...
python
def _pdist(p): """ Return PL or ECPL instance based on parameters p """ index, ref, ampl, cutoff, beta = p[:5] if cutoff == 0.0: pdist = models.PowerLaw( ampl * 1e30 * u.Unit("1/eV"), ref * u.TeV, index ) else: pdist = models.Exponentia...
[ "def", "_pdist", "(", "p", ")", ":", "index", ",", "ref", ",", "ampl", ",", "cutoff", ",", "beta", "=", "p", "[", ":", "5", "]", "if", "cutoff", "==", "0.0", ":", "pdist", "=", "models", ".", "PowerLaw", "(", "ampl", "*", "1e30", "*", "u", "....
Return PL or ECPL instance based on parameters p
[ "Return", "PL", "or", "ECPL", "instance", "based", "on", "parameters", "p" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/sherpa_models.py#L103-L118
train
zblz/naima
naima/plot.py
plot_chain
def plot_chain(sampler, p=None, **kwargs): """Generate a diagnostic plot of the sampler chains. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler containing the chains to be plotted. p : int (optional) Index of the parameter to plot. If omitted, all chains are plotted....
python
def plot_chain(sampler, p=None, **kwargs): """Generate a diagnostic plot of the sampler chains. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler containing the chains to be plotted. p : int (optional) Index of the parameter to plot. If omitted, all chains are plotted....
[ "def", "plot_chain", "(", "sampler", ",", "p", "=", "None", ",", "**", "kwargs", ")", ":", "if", "p", "is", "None", ":", "npars", "=", "sampler", ".", "chain", ".", "shape", "[", "-", "1", "]", "for", "pp", "in", "six", ".", "moves", ".", "rang...
Generate a diagnostic plot of the sampler chains. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler containing the chains to be plotted. p : int (optional) Index of the parameter to plot. If omitted, all chains are plotted. last_step : bool (optional) Whether t...
[ "Generate", "a", "diagnostic", "plot", "of", "the", "sampler", "chains", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L34-L60
train
zblz/naima
naima/plot.py
_read_or_calc_samples
def _read_or_calc_samples( sampler, modelidx=0, n_samples=100, last_step=False, e_range=None, e_npoints=100, threads=None, ): """Get samples from blob or compute them from chain and sampler.modelfn """ if not e_range: # return the results saved in blobs modelx, m...
python
def _read_or_calc_samples( sampler, modelidx=0, n_samples=100, last_step=False, e_range=None, e_npoints=100, threads=None, ): """Get samples from blob or compute them from chain and sampler.modelfn """ if not e_range: # return the results saved in blobs modelx, m...
[ "def", "_read_or_calc_samples", "(", "sampler", ",", "modelidx", "=", "0", ",", "n_samples", "=", "100", ",", "last_step", "=", "False", ",", "e_range", "=", "None", ",", "e_npoints", "=", "100", ",", "threads", "=", "None", ",", ")", ":", "if", "not",...
Get samples from blob or compute them from chain and sampler.modelfn
[ "Get", "samples", "from", "blob", "or", "compute", "them", "from", "chain", "and", "sampler", ".", "modelfn" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L368-L421
train
zblz/naima
naima/plot.py
_calc_ML
def _calc_ML(sampler, modelidx=0, e_range=None, e_npoints=100): """Get ML model from blob or compute them from chain and sampler.modelfn """ ML, MLp, MLerr, ML_model = find_ML(sampler, modelidx) if e_range is not None: # prepare bogus data for calculation e_range = validate_array( ...
python
def _calc_ML(sampler, modelidx=0, e_range=None, e_npoints=100): """Get ML model from blob or compute them from chain and sampler.modelfn """ ML, MLp, MLerr, ML_model = find_ML(sampler, modelidx) if e_range is not None: # prepare bogus data for calculation e_range = validate_array( ...
[ "def", "_calc_ML", "(", "sampler", ",", "modelidx", "=", "0", ",", "e_range", "=", "None", ",", "e_npoints", "=", "100", ")", ":", "ML", ",", "MLp", ",", "MLerr", ",", "ML_model", "=", "find_ML", "(", "sampler", ",", "modelidx", ")", "if", "e_range",...
Get ML model from blob or compute them from chain and sampler.modelfn
[ "Get", "ML", "model", "from", "blob", "or", "compute", "them", "from", "chain", "and", "sampler", ".", "modelfn" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L424-L466
train
zblz/naima
naima/plot.py
_plot_MLmodel
def _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed): """compute and plot ML model""" ML, MLp, MLerr, ML_model = _calc_ML( sampler, modelidx, e_range=e_range, e_npoints=e_npoints ) f_unit, sedf = sed_conversion(ML_model[0], ML_model[1].unit, sed) ax.loglog( ML_...
python
def _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed): """compute and plot ML model""" ML, MLp, MLerr, ML_model = _calc_ML( sampler, modelidx, e_range=e_range, e_npoints=e_npoints ) f_unit, sedf = sed_conversion(ML_model[0], ML_model[1].unit, sed) ax.loglog( ML_...
[ "def", "_plot_MLmodel", "(", "ax", ",", "sampler", ",", "modelidx", ",", "e_range", ",", "e_npoints", ",", "e_unit", ",", "sed", ")", ":", "ML", ",", "MLp", ",", "MLerr", ",", "ML_model", "=", "_calc_ML", "(", "sampler", ",", "modelidx", ",", "e_range"...
compute and plot ML model
[ "compute", "and", "plot", "ML", "model" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L536-L550
train
zblz/naima
naima/plot.py
plot_CI
def plot_CI( ax, sampler, modelidx=0, sed=True, confs=[3, 1, 0.5], e_unit=u.eV, label=None, e_range=None, e_npoints=100, threads=None, last_step=False, ): """Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. s...
python
def plot_CI( ax, sampler, modelidx=0, sed=True, confs=[3, 1, 0.5], e_unit=u.eV, label=None, e_range=None, e_npoints=100, threads=None, last_step=False, ): """Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. s...
[ "def", "plot_CI", "(", "ax", ",", "sampler", ",", "modelidx", "=", "0", ",", "sed", "=", "True", ",", "confs", "=", "[", "3", ",", "1", ",", "0.5", "]", ",", "e_unit", "=", "u", ".", "eV", ",", "label", "=", "None", ",", "e_range", "=", "None...
Plot confidence interval. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. sampler : `emcee.EnsembleSampler` Sampler modelidx : int, optional Model index. Default is 0 sed : bool, optional Whether to plot SED or differential spectrum. If `None`, the ...
[ "Plot", "confidence", "interval", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L553-L625
train
zblz/naima
naima/plot.py
plot_samples
def plot_samples( ax, sampler, modelidx=0, sed=True, n_samples=100, e_unit=u.eV, e_range=None, e_npoints=100, threads=None, label=None, last_step=False, ): """Plot a number of samples from the sampler chain. Parameters ---------- ax : `matplotlib.Axes` ...
python
def plot_samples( ax, sampler, modelidx=0, sed=True, n_samples=100, e_unit=u.eV, e_range=None, e_npoints=100, threads=None, label=None, last_step=False, ): """Plot a number of samples from the sampler chain. Parameters ---------- ax : `matplotlib.Axes` ...
[ "def", "plot_samples", "(", "ax", ",", "sampler", ",", "modelidx", "=", "0", ",", "sed", "=", "True", ",", "n_samples", "=", "100", ",", "e_unit", "=", "u", ".", "eV", ",", "e_range", "=", "None", ",", "e_npoints", "=", "100", ",", "threads", "=", ...
Plot a number of samples from the sampler chain. Parameters ---------- ax : `matplotlib.Axes` Axes to plot on. sampler : `emcee.EnsembleSampler` Sampler modelidx : int, optional Model index. Default is 0 sed : bool, optional Whether to plot SED or differential sp...
[ "Plot", "a", "number", "of", "samples", "from", "the", "sampler", "chain", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L628-L700
train
zblz/naima
naima/plot.py
find_ML
def find_ML(sampler, modelidx): """ Find Maximum Likelihood parameters as those in the chain with a highest log probability. """ index = np.unravel_index( np.argmax(sampler.lnprobability), sampler.lnprobability.shape ) MLp = sampler.chain[index] if modelidx is not None and hasatt...
python
def find_ML(sampler, modelidx): """ Find Maximum Likelihood parameters as those in the chain with a highest log probability. """ index = np.unravel_index( np.argmax(sampler.lnprobability), sampler.lnprobability.shape ) MLp = sampler.chain[index] if modelidx is not None and hasatt...
[ "def", "find_ML", "(", "sampler", ",", "modelidx", ")", ":", "index", "=", "np", ".", "unravel_index", "(", "np", ".", "argmax", "(", "sampler", ".", "lnprobability", ")", ",", "sampler", ".", "lnprobability", ".", "shape", ")", "MLp", "=", "sampler", ...
Find Maximum Likelihood parameters as those in the chain with a highest log probability.
[ "Find", "Maximum", "Likelihood", "parameters", "as", "those", "in", "the", "chain", "with", "a", "highest", "log", "probability", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L703-L738
train
zblz/naima
naima/plot.py
plot_blob
def plot_blob( sampler, blobidx=0, label=None, last_step=False, figure=None, **kwargs ): """ Plot a metadata blob as a fit to spectral data or value distribution Additional ``kwargs`` are passed to `plot_fit`. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a s...
python
def plot_blob( sampler, blobidx=0, label=None, last_step=False, figure=None, **kwargs ): """ Plot a metadata blob as a fit to spectral data or value distribution Additional ``kwargs`` are passed to `plot_fit`. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a s...
[ "def", "plot_blob", "(", "sampler", ",", "blobidx", "=", "0", ",", "label", "=", "None", ",", "last_step", "=", "False", ",", "figure", "=", "None", ",", "**", "kwargs", ")", ":", "modelx", ",", "model", "=", "_process_blob", "(", "sampler", ",", "bl...
Plot a metadata blob as a fit to spectral data or value distribution Additional ``kwargs`` are passed to `plot_fit`. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a stored chain. blobidx : int, optional Metadata blob index to plot. label : str, optional ...
[ "Plot", "a", "metadata", "blob", "as", "a", "fit", "to", "spectral", "data", "or", "value", "distribution" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L741-L782
train
zblz/naima
naima/plot.py
_plot_ulims
def _plot_ulims( ax, x, y, xerr, color, capsize=5, height_fraction=0.25, elinewidth=2 ): """ Plot upper limits as arrows with cap at value of upper limit. uplim behaviour has been fixed in matplotlib 1.4 """ ax.errorbar( x, y, xerr=xerr, ls="", color=color, elinewidth=elinewidth, capsiz...
python
def _plot_ulims( ax, x, y, xerr, color, capsize=5, height_fraction=0.25, elinewidth=2 ): """ Plot upper limits as arrows with cap at value of upper limit. uplim behaviour has been fixed in matplotlib 1.4 """ ax.errorbar( x, y, xerr=xerr, ls="", color=color, elinewidth=elinewidth, capsiz...
[ "def", "_plot_ulims", "(", "ax", ",", "x", ",", "y", ",", "xerr", ",", "color", ",", "capsize", "=", "5", ",", "height_fraction", "=", "0.25", ",", "elinewidth", "=", "2", ")", ":", "ax", ".", "errorbar", "(", "x", ",", "y", ",", "xerr", "=", "...
Plot upper limits as arrows with cap at value of upper limit. uplim behaviour has been fixed in matplotlib 1.4
[ "Plot", "upper", "limits", "as", "arrows", "with", "cap", "at", "value", "of", "upper", "limit", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1044-L1083
train
zblz/naima
naima/plot.py
plot_data
def plot_data( input_data, xlabel=None, ylabel=None, sed=True, figure=None, e_unit=None, ulim_opts={}, errorbar_opts={}, ): """ Plot spectral data. Parameters ---------- input_data : `emcee.EnsembleSampler`, `astropy.table.Table`, or `dict` Spectral data to p...
python
def plot_data( input_data, xlabel=None, ylabel=None, sed=True, figure=None, e_unit=None, ulim_opts={}, errorbar_opts={}, ): """ Plot spectral data. Parameters ---------- input_data : `emcee.EnsembleSampler`, `astropy.table.Table`, or `dict` Spectral data to p...
[ "def", "plot_data", "(", "input_data", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "sed", "=", "True", ",", "figure", "=", "None", ",", "e_unit", "=", "None", ",", "ulim_opts", "=", "{", "}", ",", "errorbar_opts", "=", "{", "}", ",...
Plot spectral data. Parameters ---------- input_data : `emcee.EnsembleSampler`, `astropy.table.Table`, or `dict` Spectral data to plot. Can be given as a data table, a dict generated with `validate_data_table` or a `emcee.EnsembleSampler` with a data property. xlabel : str, opti...
[ "Plot", "spectral", "data", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1282-L1376
train
zblz/naima
naima/plot.py
plot_distribution
def plot_distribution(samples, label, figure=None): """ Plot a distribution and print statistics about it""" from scipy import stats import matplotlib.pyplot as plt quant = [16, 50, 84] quantiles = dict(six.moves.zip(quant, np.percentile(samples, quant))) std = np.std(samples) if isinstan...
python
def plot_distribution(samples, label, figure=None): """ Plot a distribution and print statistics about it""" from scipy import stats import matplotlib.pyplot as plt quant = [16, 50, 84] quantiles = dict(six.moves.zip(quant, np.percentile(samples, quant))) std = np.std(samples) if isinstan...
[ "def", "plot_distribution", "(", "samples", ",", "label", ",", "figure", "=", "None", ")", ":", "from", "scipy", "import", "stats", "import", "matplotlib", ".", "pyplot", "as", "plt", "quant", "=", "[", "16", ",", "50", ",", "84", "]", "quantiles", "="...
Plot a distribution and print statistics about it
[ "Plot", "a", "distribution", "and", "print", "statistics", "about", "it" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1379-L1469
train
zblz/naima
naima/plot.py
plot_corner
def plot_corner(sampler, show_ML=True, **kwargs): """ A plot that summarizes the parameter samples by showing them as individual histograms and 2D histograms against each other. The maximum likelihood parameter vector is indicated by a cross. This function is a thin wrapper around `corner.corner`, ...
python
def plot_corner(sampler, show_ML=True, **kwargs): """ A plot that summarizes the parameter samples by showing them as individual histograms and 2D histograms against each other. The maximum likelihood parameter vector is indicated by a cross. This function is a thin wrapper around `corner.corner`, ...
[ "def", "plot_corner", "(", "sampler", ",", "show_ML", "=", "True", ",", "**", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "oldlw", "=", "plt", ".", "rcParams", "[", "\"lines.linewidth\"", "]", "plt", ".", "rcParams", "[", "\"l...
A plot that summarizes the parameter samples by showing them as individual histograms and 2D histograms against each other. The maximum likelihood parameter vector is indicated by a cross. This function is a thin wrapper around `corner.corner`, found at https://github.com/corner/corner.py. Paramet...
[ "A", "plot", "that", "summarizes", "the", "parameter", "samples", "by", "showing", "them", "as", "individual", "histograms", "and", "2D", "histograms", "against", "each", "other", ".", "The", "maximum", "likelihood", "parameter", "vector", "is", "indicated", "by...
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1472-L1520
train
flowersteam/explauto
explauto/sensorimotor_model/forward/nn.py
NNForwardModel.predict_given_context
def predict_given_context(self, x, c, c_dims): """Provide a prediction of x with context c on dimensions c_dims in the output space being S - c_dims @param x an array of float of length dim_x @return predicted y as np.array of float """ assert len(c) == len(c_dims) _...
python
def predict_given_context(self, x, c, c_dims): """Provide a prediction of x with context c on dimensions c_dims in the output space being S - c_dims @param x an array of float of length dim_x @return predicted y as np.array of float """ assert len(c) == len(c_dims) _...
[ "def", "predict_given_context", "(", "self", ",", "x", ",", "c", ",", "c_dims", ")", ":", "assert", "len", "(", "c", ")", "==", "len", "(", "c_dims", ")", "_", ",", "index", "=", "self", ".", "dataset", ".", "nn_dims", "(", "x", ",", "c", ",", ...
Provide a prediction of x with context c on dimensions c_dims in the output space being S - c_dims @param x an array of float of length dim_x @return predicted y as np.array of float
[ "Provide", "a", "prediction", "of", "x", "with", "context", "c", "on", "dimensions", "c_dims", "in", "the", "output", "space", "being", "S", "-", "c_dims" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/forward/nn.py#L35-L43
train
flowersteam/explauto
explauto/models/pydmps/dmp_rhythmic.py
DMPs_rhythmic.gen_front_term
def gen_front_term(self, x, dmp_num): """Generates the front term on the forcing term. For rhythmic DMPs it's non-diminishing, so this function is just a placeholder to return 1. x float: the current value of the canonical system dmp_num int: the index of the current dmp ...
python
def gen_front_term(self, x, dmp_num): """Generates the front term on the forcing term. For rhythmic DMPs it's non-diminishing, so this function is just a placeholder to return 1. x float: the current value of the canonical system dmp_num int: the index of the current dmp ...
[ "def", "gen_front_term", "(", "self", ",", "x", ",", "dmp_num", ")", ":", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "ones", "(", "x", ".", "shape", ")", "return", "1" ]
Generates the front term on the forcing term. For rhythmic DMPs it's non-diminishing, so this function is just a placeholder to return 1. x float: the current value of the canonical system dmp_num int: the index of the current dmp
[ "Generates", "the", "front", "term", "on", "the", "forcing", "term", ".", "For", "rhythmic", "DMPs", "it", "s", "non", "-", "diminishing", "so", "this", "function", "is", "just", "a", "placeholder", "to", "return", "1", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp_rhythmic.py#L48-L59
train
flowersteam/explauto
explauto/sensorimotor_model/forward/lwr.py
LWLRForwardModel.predict_y
def predict_y(self, xq, sigma=None, k=None): """Provide a prediction of xq in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._weights(.) """ ...
python
def predict_y(self, xq, sigma=None, k=None): """Provide a prediction of xq in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._weights(.) """ ...
[ "def", "predict_y", "(", "self", ",", "xq", ",", "sigma", "=", "None", ",", "k", "=", "None", ")", ":", "assert", "len", "(", "xq", ")", "==", "self", ".", "dataset", ".", "dim_x", "sigma_sq", "=", "self", ".", "sigma_sq", "if", "sigma", "is", "N...
Provide a prediction of xq in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._weights(.)
[ "Provide", "a", "prediction", "of", "xq", "in", "the", "output", "space" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/forward/lwr.py#L89-L115
train
flowersteam/explauto
explauto/sensorimotor_model/forward/lwr.py
LWLRForwardModel.predict_dims
def predict_dims(self, q, dims_x, dims_y, dims_out, sigma=None, k=None): """Provide a prediction of q in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._we...
python
def predict_dims(self, q, dims_x, dims_y, dims_out, sigma=None, k=None): """Provide a prediction of q in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._we...
[ "def", "predict_dims", "(", "self", ",", "q", ",", "dims_x", ",", "dims_y", ",", "dims_out", ",", "sigma", "=", "None", ",", "k", "=", "None", ")", ":", "assert", "len", "(", "q", ")", "==", "len", "(", "dims_x", ")", "+", "len", "(", "dims_y", ...
Provide a prediction of q in the output space @param xq an array of float of length dim_x @param estimated_sigma if False (default), sigma_sq=self.sigma_sq, else it is estimated from the neighbor distances in self._weights(.)
[ "Provide", "a", "prediction", "of", "q", "in", "the", "output", "space" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/forward/lwr.py#L126-L153
train
flowersteam/explauto
explauto/experiment/log.py
ExperimentLog.scatter_plot
def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot): """ 2D or 3D scatter plot. :param axes ax: matplotlib axes (use Axes3D if 3D data) :param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotte...
python
def scatter_plot(self, ax, topic_dims, t=None, ms_limits=True, **kwargs_plot): """ 2D or 3D scatter plot. :param axes ax: matplotlib axes (use Axes3D if 3D data) :param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotte...
[ "def", "scatter_plot", "(", "self", ",", "ax", ",", "topic_dims", ",", "t", "=", "None", ",", "ms_limits", "=", "True", ",", "**", "kwargs_plot", ")", ":", "plot_specs", "=", "{", "'marker'", ":", "'o'", ",", "'linestyle'", ":", "'None'", "}", "plot_sp...
2D or 3D scatter plot. :param axes ax: matplotlib axes (use Axes3D if 3D data) :param tuple topic_dims: list of (topic, dims) tuples, where topic is a string and dims is a list of dimensions to be plotted for that topic. :param int t: time indexes to be plotted :param...
[ "2D", "or", "3D", "scatter", "plot", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/log.py#L67-L93
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.get_nodes
def get_nodes(self): """ Get the list of all nodes. """ return self.fold_up(lambda n, fl, fg: [n] + fl + fg, lambda leaf: [leaf])
python
def get_nodes(self): """ Get the list of all nodes. """ return self.fold_up(lambda n, fl, fg: [n] + fl + fg, lambda leaf: [leaf])
[ "def", "get_nodes", "(", "self", ")", ":", "return", "self", ".", "fold_up", "(", "lambda", "n", ",", "fl", ",", "fg", ":", "[", "n", "]", "+", "fl", "+", "fg", ",", "lambda", "leaf", ":", "[", "leaf", "]", ")" ]
Get the list of all nodes.
[ "Get", "the", "list", "of", "all", "nodes", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L189-L194
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.get_leaves
def get_leaves(self): """ Get the list of all leaves. """ return self.fold_up(lambda n, fl, fg: fl + fg, lambda leaf: [leaf])
python
def get_leaves(self): """ Get the list of all leaves. """ return self.fold_up(lambda n, fl, fg: fl + fg, lambda leaf: [leaf])
[ "def", "get_leaves", "(", "self", ")", ":", "return", "self", ".", "fold_up", "(", "lambda", "n", ",", "fl", ",", "fg", ":", "fl", "+", "fg", ",", "lambda", "leaf", ":", "[", "leaf", "]", ")" ]
Get the list of all leaves.
[ "Get", "the", "list", "of", "all", "leaves", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L197-L202
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.pt2leaf
def pt2leaf(self, x): """ Get the leaf which domain contains x. """ if self.leafnode: return self else: if x[self.split_dim] < self.split_value: return self.lower.pt2leaf(x) else: return self.greater.pt2...
python
def pt2leaf(self, x): """ Get the leaf which domain contains x. """ if self.leafnode: return self else: if x[self.split_dim] < self.split_value: return self.lower.pt2leaf(x) else: return self.greater.pt2...
[ "def", "pt2leaf", "(", "self", ",", "x", ")", ":", "if", "self", ".", "leafnode", ":", "return", "self", "else", ":", "if", "x", "[", "self", ".", "split_dim", "]", "<", "self", ".", "split_value", ":", "return", "self", ".", "lower", ".", "pt2leaf...
Get the leaf which domain contains x.
[ "Get", "the", "leaf", "which", "domain", "contains", "x", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L221-L232
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.sample_random
def sample_random(self): """ Sample a point in a random leaf. """ if self.sampling_mode['volume']: # Choose a leaf weighted by volume, randomly if self.leafnode: return self.sample_bounds() else: split_ratio =...
python
def sample_random(self): """ Sample a point in a random leaf. """ if self.sampling_mode['volume']: # Choose a leaf weighted by volume, randomly if self.leafnode: return self.sample_bounds() else: split_ratio =...
[ "def", "sample_random", "(", "self", ")", ":", "if", "self", ".", "sampling_mode", "[", "'volume'", "]", ":", "if", "self", ".", "leafnode", ":", "return", "self", ".", "sample_bounds", "(", ")", "else", ":", "split_ratio", "=", "(", "(", "self", ".", ...
Sample a point in a random leaf.
[ "Sample", "a", "point", "in", "a", "random", "leaf", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L244-L262
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.sample_greedy
def sample_greedy(self): """ Sample a point in the leaf with the max progress. """ if self.leafnode: return self.sample_bounds() else: lp = self.lower.max_leaf_progress gp = self.greater.max_leaf_progress maxp =...
python
def sample_greedy(self): """ Sample a point in the leaf with the max progress. """ if self.leafnode: return self.sample_bounds() else: lp = self.lower.max_leaf_progress gp = self.greater.max_leaf_progress maxp =...
[ "def", "sample_greedy", "(", "self", ")", ":", "if", "self", ".", "leafnode", ":", "return", "self", ".", "sample_bounds", "(", ")", "else", ":", "lp", "=", "self", ".", "lower", ".", "max_leaf_progress", "gp", "=", "self", ".", "greater", ".", "max_le...
Sample a point in the leaf with the max progress.
[ "Sample", "a", "point", "in", "the", "leaf", "with", "the", "max", "progress", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L265-L288
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.progress_all
def progress_all(self): """ Competence progress of the overall tree. """ return self.progress_idxs(range(np.shape(self.get_data_x())[0] - self.progress_win_size, np.shape(self.get_data_x())[0]))
python
def progress_all(self): """ Competence progress of the overall tree. """ return self.progress_idxs(range(np.shape(self.get_data_x())[0] - self.progress_win_size, np.shape(self.get_data_x())[0]))
[ "def", "progress_all", "(", "self", ")", ":", "return", "self", ".", "progress_idxs", "(", "range", "(", "np", ".", "shape", "(", "self", ".", "get_data_x", "(", ")", ")", "[", "0", "]", "-", "self", ".", "progress_win_size", ",", "np", ".", "shape",...
Competence progress of the overall tree.
[ "Competence", "progress", "of", "the", "overall", "tree", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L372-L378
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.progress_idxs
def progress_idxs(self, idxs): """ Competence progress on points of given indexes. """ if self.progress_measure == 'abs_deriv_cov': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] ...
python
def progress_idxs(self, idxs): """ Competence progress on points of given indexes. """ if self.progress_measure == 'abs_deriv_cov': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] ...
[ "def", "progress_idxs", "(", "self", ",", "idxs", ")", ":", "if", "self", ".", "progress_measure", "==", "'abs_deriv_cov'", ":", "if", "len", "(", "idxs", ")", "<=", "1", ":", "return", "0", "else", ":", "idxs", "=", "sorted", "(", "idxs", ")", "[", ...
Competence progress on points of given indexes.
[ "Competence", "progress", "on", "points", "of", "given", "indexes", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L381-L411
train
flowersteam/explauto
explauto/interest_model/tree.py
Tree.fold_up
def fold_up(self, f_inter, f_leaf): """ Apply recursively the function f_inter from leaves to root, begining with function f_leaf on leaves. """ return f_leaf(self) if self.leafnode else f_inter(self, self.lower.fold_up(f...
python
def fold_up(self, f_inter, f_leaf): """ Apply recursively the function f_inter from leaves to root, begining with function f_leaf on leaves. """ return f_leaf(self) if self.leafnode else f_inter(self, self.lower.fold_up(f...
[ "def", "fold_up", "(", "self", ",", "f_inter", ",", "f_leaf", ")", ":", "return", "f_leaf", "(", "self", ")", "if", "self", ".", "leafnode", "else", "f_inter", "(", "self", ",", "self", ".", "lower", ".", "fold_up", "(", "f_inter", ",", "f_leaf", ")"...
Apply recursively the function f_inter from leaves to root, begining with function f_leaf on leaves.
[ "Apply", "recursively", "the", "function", "f_inter", "from", "leaves", "to", "root", "begining", "with", "function", "f_leaf", "on", "leaves", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/interest_model/tree.py#L736-L743
train
flowersteam/explauto
explauto/sensorimotor_model/bayesian_optimisation.py
F_to_minimize.f
def f(self, m): ''' Function to minimize ''' M = reshape(m,self.input_dim) n = M.shape[0] if M.shape[1] != self.input_dim: return 'Wrong input dimension' else: S = self.environment.update(M) m = M[0] s = S[0] # Store the...
python
def f(self, m): ''' Function to minimize ''' M = reshape(m,self.input_dim) n = M.shape[0] if M.shape[1] != self.input_dim: return 'Wrong input dimension' else: S = self.environment.update(M) m = M[0] s = S[0] # Store the...
[ "def", "f", "(", "self", ",", "m", ")", ":", "M", "=", "reshape", "(", "m", ",", "self", ".", "input_dim", ")", "n", "=", "M", ".", "shape", "[", "0", "]", "if", "M", ".", "shape", "[", "1", "]", "!=", "self", ".", "input_dim", ":", "return...
Function to minimize
[ "Function", "to", "minimize" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/bayesian_optimisation.py#L25-L37
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/inverse.py
InverseModel.from_forward
def from_forward(cls, fmodel, **kwargs): """Construst an inverse model from a forward model and constraints. """ im = cls(fmodel.dim_x, fmodel.dim_y, **kwargs) im.fmodel = fmodel return im
python
def from_forward(cls, fmodel, **kwargs): """Construst an inverse model from a forward model and constraints. """ im = cls(fmodel.dim_x, fmodel.dim_y, **kwargs) im.fmodel = fmodel return im
[ "def", "from_forward", "(", "cls", ",", "fmodel", ",", "**", "kwargs", ")", ":", "im", "=", "cls", "(", "fmodel", ".", "dim_x", ",", "fmodel", ".", "dim_y", ",", "**", "kwargs", ")", "im", ".", "fmodel", "=", "fmodel", "return", "im" ]
Construst an inverse model from a forward model and constraints.
[ "Construst", "an", "inverse", "model", "from", "a", "forward", "model", "and", "constraints", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/inverse.py#L18-L23
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/inverse.py
InverseModel._random_x
def _random_x(self): """If the database is empty, generate a random vector.""" return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)
python
def _random_x(self): """If the database is empty, generate a random vector.""" return (tuple(random.random() for _ in range(self.fmodel.dim_x)),)
[ "def", "_random_x", "(", "self", ")", ":", "return", "(", "tuple", "(", "random", ".", "random", "(", ")", "for", "_", "in", "range", "(", "self", ".", "fmodel", ".", "dim_x", ")", ")", ",", ")" ]
If the database is empty, generate a random vector.
[ "If", "the", "database", "is", "empty", "generate", "a", "random", "vector", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/inverse.py#L48-L50
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/inverse.py
InverseModel.config
def config(self): """Return a string with the configuration""" return ", ".join('%s:%s' % (key, value) for key, value in self.conf.items())
python
def config(self): """Return a string with the configuration""" return ", ".join('%s:%s' % (key, value) for key, value in self.conf.items())
[ "def", "config", "(", "self", ")", ":", "return", "\", \"", ".", "join", "(", "'%s:%s'", "%", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "self", ".", "conf", ".", "items", "(", ")", ")" ]
Return a string with the configuration
[ "Return", "a", "string", "with", "the", "configuration" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/inverse.py#L104-L106
train
flowersteam/explauto
explauto/experiment/experiment.py
Experiment.run
def run(self, n_iter=-1, bg=False): """ Run the experiment. :param int n_iter: Number of run iterations, by default will run until the last evaluation step. :param bool bg: whether to run in background (using a Thread) """ if n_iter == -1: if not self.eval_a...
python
def run(self, n_iter=-1, bg=False): """ Run the experiment. :param int n_iter: Number of run iterations, by default will run until the last evaluation step. :param bool bg: whether to run in background (using a Thread) """ if n_iter == -1: if not self.eval_a...
[ "def", "run", "(", "self", ",", "n_iter", "=", "-", "1", ",", "bg", "=", "False", ")", ":", "if", "n_iter", "==", "-", "1", ":", "if", "not", "self", ".", "eval_at", ":", "raise", "ValueError", "(", "'Set n_iter or define evaluate_at.'", ")", "n_iter",...
Run the experiment. :param int n_iter: Number of run iterations, by default will run until the last evaluation step. :param bool bg: whether to run in background (using a Thread)
[ "Run", "the", "experiment", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/experiment.py#L55-L74
train
flowersteam/explauto
explauto/experiment/experiment.py
Experiment.evaluate_at
def evaluate_at(self, eval_at, testcases, mode=None): """ Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation """ self.eval_at = eval_at ...
python
def evaluate_at(self, eval_at, testcases, mode=None): """ Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation """ self.eval_at = eval_at ...
[ "def", "evaluate_at", "(", "self", ",", "eval_at", ",", "testcases", ",", "mode", "=", "None", ")", ":", "self", ".", "eval_at", "=", "eval_at", "self", ".", "log", ".", "eval_at", "=", "eval_at", "if", "mode", "is", "None", ":", "if", "self", ".", ...
Sets the evaluation interation indices. :param list eval_at: iteration indices where an evaluation should be performed :param numpy.array testcases: testcases used for evaluation
[ "Sets", "the", "evaluation", "interation", "indices", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/experiment.py#L149-L168
train
flowersteam/explauto
explauto/models/pydmps/cs.py
CanonicalSystem.rollout
def rollout(self, **kwargs): """Generate x for open loop movements. """ if kwargs.has_key('tau'): timesteps = int(self.timesteps / kwargs['tau']) else: timesteps = self.timesteps self.x_track = np.zeros(timesteps) self.reset_state() ...
python
def rollout(self, **kwargs): """Generate x for open loop movements. """ if kwargs.has_key('tau'): timesteps = int(self.timesteps / kwargs['tau']) else: timesteps = self.timesteps self.x_track = np.zeros(timesteps) self.reset_state() ...
[ "def", "rollout", "(", "self", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "has_key", "(", "'tau'", ")", ":", "timesteps", "=", "int", "(", "self", ".", "timesteps", "/", "kwargs", "[", "'tau'", "]", ")", "else", ":", "timesteps", "=", "sel...
Generate x for open loop movements.
[ "Generate", "x", "for", "open", "loop", "movements", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/cs.py#L48-L62
train
flowersteam/explauto
explauto/utils/utils.py
discrete_random_draw
def discrete_random_draw(data, nb=1): ''' Code from Steve Nguyen''' data = np.array(data) if not data.any(): data = np.ones_like(data) data = data/data.sum() xk = np.arange(len(data)) custm = stats.rv_discrete(name='custm', values=(xk, data)) return custm.rvs(size=nb)
python
def discrete_random_draw(data, nb=1): ''' Code from Steve Nguyen''' data = np.array(data) if not data.any(): data = np.ones_like(data) data = data/data.sum() xk = np.arange(len(data)) custm = stats.rv_discrete(name='custm', values=(xk, data)) return custm.rvs(size=nb)
[ "def", "discrete_random_draw", "(", "data", ",", "nb", "=", "1", ")", ":", "data", "=", "np", ".", "array", "(", "data", ")", "if", "not", "data", ".", "any", "(", ")", ":", "data", "=", "np", ".", "ones_like", "(", "data", ")", "data", "=", "d...
Code from Steve Nguyen
[ "Code", "from", "Steve", "Nguyen" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/utils/utils.py#L46-L54
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/optimize.py
OptimizedInverseModel.from_dataset
def from_dataset(cls, dataset, constraints = (), **kwargs): """Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default. """ fm = LWLRForwardModel(dataset.dim_x, dataset.dim_y, **kwargs) fm.dataset = dataset im = cls.fro...
python
def from_dataset(cls, dataset, constraints = (), **kwargs): """Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default. """ fm = LWLRForwardModel(dataset.dim_x, dataset.dim_y, **kwargs) fm.dataset = dataset im = cls.fro...
[ "def", "from_dataset", "(", "cls", ",", "dataset", ",", "constraints", "=", "(", ")", ",", "**", "kwargs", ")", ":", "fm", "=", "LWLRForwardModel", "(", "dataset", ".", "dim_x", ",", "dataset", ".", "dim_y", ",", "**", "kwargs", ")", "fm", ".", "data...
Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default.
[ "Construct", "a", "optimized", "inverse", "model", "from", "an", "existing", "dataset", ".", "A", "LWLR", "forward", "model", "is", "constructed", "by", "default", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/optimize.py#L12-L19
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/optimize.py
OptimizedInverseModel._setuplimits
def _setuplimits(self, constraints): """Setup the limits for every initialiser.""" self.constraints = tuple(constraints) assert len(self.constraints) == self.fmodel.dim_x self.goal = None
python
def _setuplimits(self, constraints): """Setup the limits for every initialiser.""" self.constraints = tuple(constraints) assert len(self.constraints) == self.fmodel.dim_x self.goal = None
[ "def", "_setuplimits", "(", "self", ",", "constraints", ")", ":", "self", ".", "constraints", "=", "tuple", "(", "constraints", ")", "assert", "len", "(", "self", ".", "constraints", ")", "==", "self", ".", "fmodel", ".", "dim_x", "self", ".", "goal", ...
Setup the limits for every initialiser.
[ "Setup", "the", "limits", "for", "every", "initialiser", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/optimize.py#L37-L41
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/optimize.py
OptimizedInverseModel._error
def _error(self, x): """Error function. Once self.y_desired has been defined, compute the error of input x using the forward model. """ y_pred = self.fmodel.predict_y(x) err_v = y_pred - self.goal error = sum(e*e for e in err_v) return error
python
def _error(self, x): """Error function. Once self.y_desired has been defined, compute the error of input x using the forward model. """ y_pred = self.fmodel.predict_y(x) err_v = y_pred - self.goal error = sum(e*e for e in err_v) return error
[ "def", "_error", "(", "self", ",", "x", ")", ":", "y_pred", "=", "self", ".", "fmodel", ".", "predict_y", "(", "x", ")", "err_v", "=", "y_pred", "-", "self", ".", "goal", "error", "=", "sum", "(", "e", "*", "e", "for", "e", "in", "err_v", ")", ...
Error function. Once self.y_desired has been defined, compute the error of input x using the forward model.
[ "Error", "function", ".", "Once", "self", ".", "y_desired", "has", "been", "defined", "compute", "the", "error", "of", "input", "x", "using", "the", "forward", "model", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/optimize.py#L46-L54
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/optimize.py
OptimizedInverseModel._error_dm
def _error_dm(self, m, dm, s): """Error function. Once self.goal has been defined, compute the error of input using the generalized forward model. """ pred = self.fmodel.predict_given_context(np.hstack((m, dm)), s, range(len(s))) err_v = pred - self.goal error = ...
python
def _error_dm(self, m, dm, s): """Error function. Once self.goal has been defined, compute the error of input using the generalized forward model. """ pred = self.fmodel.predict_given_context(np.hstack((m, dm)), s, range(len(s))) err_v = pred - self.goal error = ...
[ "def", "_error_dm", "(", "self", ",", "m", ",", "dm", ",", "s", ")", ":", "pred", "=", "self", ".", "fmodel", ".", "predict_given_context", "(", "np", ".", "hstack", "(", "(", "m", ",", "dm", ")", ")", ",", "s", ",", "range", "(", "len", "(", ...
Error function. Once self.goal has been defined, compute the error of input using the generalized forward model.
[ "Error", "function", ".", "Once", "self", ".", "goal", "has", "been", "defined", "compute", "the", "error", "of", "input", "using", "the", "generalized", "forward", "model", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/optimize.py#L56-L64
train
flowersteam/explauto
explauto/models/gaussian.py
Gaussian.generate
def generate(self, number=None): """Generates vectors from the Gaussian. @param number: optional, if given, generates more than one vector. @returns: generated vector(s), either as a one dimensional array (shape (d,)) if number is not set, or as a two dimensional array ...
python
def generate(self, number=None): """Generates vectors from the Gaussian. @param number: optional, if given, generates more than one vector. @returns: generated vector(s), either as a one dimensional array (shape (d,)) if number is not set, or as a two dimensional array ...
[ "def", "generate", "(", "self", ",", "number", "=", "None", ")", ":", "if", "number", "is", "None", ":", "return", "numpy", ".", "random", ".", "multivariate_normal", "(", "self", ".", "mu", ",", "self", ".", "sigma", ")", "else", ":", "return", "num...
Generates vectors from the Gaussian. @param number: optional, if given, generates more than one vector. @returns: generated vector(s), either as a one dimensional array (shape (d,)) if number is not set, or as a two dimensional array (shape (n, d)) if n is given as number param...
[ "Generates", "vectors", "from", "the", "Gaussian", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/gaussian.py#L31-L43
train
flowersteam/explauto
explauto/models/gaussian.py
Gaussian.log_normal
def log_normal(self, x): """ Returns the log density of probability of x or the one dimensional array of all log probabilities if many vectors are given. @param x : may be of (n,) shape """ d = self.mu.shape[0] xc = x - self.mu if len(x.shape) == 1: ...
python
def log_normal(self, x): """ Returns the log density of probability of x or the one dimensional array of all log probabilities if many vectors are given. @param x : may be of (n,) shape """ d = self.mu.shape[0] xc = x - self.mu if len(x.shape) == 1: ...
[ "def", "log_normal", "(", "self", ",", "x", ")", ":", "d", "=", "self", ".", "mu", ".", "shape", "[", "0", "]", "xc", "=", "x", "-", "self", ".", "mu", "if", "len", "(", "x", ".", "shape", ")", "==", "1", ":", "exp_term", "=", "numpy", ".",...
Returns the log density of probability of x or the one dimensional array of all log probabilities if many vectors are given. @param x : may be of (n,) shape
[ "Returns", "the", "log", "density", "of", "probability", "of", "x", "or", "the", "one", "dimensional", "array", "of", "all", "log", "probabilities", "if", "many", "vectors", "are", "given", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/gaussian.py#L53-L67
train
flowersteam/explauto
explauto/models/gaussian.py
Gaussian.cond_gaussian
def cond_gaussian(self, dims, v): """ Returns mean and variance of the conditional probability defined by a set of dimension and at a given vector. @param dims : set of dimension to which respect conditional probability is taken @param v : vector defining the positi...
python
def cond_gaussian(self, dims, v): """ Returns mean and variance of the conditional probability defined by a set of dimension and at a given vector. @param dims : set of dimension to which respect conditional probability is taken @param v : vector defining the positi...
[ "def", "cond_gaussian", "(", "self", ",", "dims", ",", "v", ")", ":", "(", "d", ",", "c", ",", "b", ",", "a", ")", "=", "numpy", ".", "split_matrix", "(", "self", ".", "sigma", ",", "dims", ")", "(", "mu2", ",", "mu1", ")", "=", "numpy", ".",...
Returns mean and variance of the conditional probability defined by a set of dimension and at a given vector. @param dims : set of dimension to which respect conditional probability is taken @param v : vector defining the position where the conditional probability is ta...
[ "Returns", "mean", "and", "variance", "of", "the", "conditional", "probability", "defined", "by", "a", "set", "of", "dimension", "and", "at", "a", "given", "vector", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/gaussian.py#L69-L85
train
flowersteam/explauto
explauto/environment/environment.py
Environment.from_configuration
def from_configuration(cls, env_name, config_name='default'): """ Environment factory from name and configuration strings. :param str env_name: the name string of the environment :param str config_name: the configuration string for env_name Environment name strings are available using...
python
def from_configuration(cls, env_name, config_name='default'): """ Environment factory from name and configuration strings. :param str env_name: the name string of the environment :param str config_name: the configuration string for env_name Environment name strings are available using...
[ "def", "from_configuration", "(", "cls", ",", "env_name", ",", "config_name", "=", "'default'", ")", ":", "env_cls", ",", "env_configs", ",", "_", "=", "environments", "[", "env_name", "]", "return", "env_cls", "(", "**", "env_configs", "[", "config_name", "...
Environment factory from name and configuration strings. :param str env_name: the name string of the environment :param str config_name: the configuration string for env_name Environment name strings are available using:: from explauto.environment import environments ...
[ "Environment", "factory", "from", "name", "and", "configuration", "strings", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/environment.py#L31-L66
train
flowersteam/explauto
explauto/environment/environment.py
Environment.update
def update(self, m_ag, reset=True, log=True): """ Computes sensorimotor values from motor orders. :param numpy.array m_ag: a motor command with shape (self.conf.m_ndims, ) or a set of n motor commands of shape (n, self.conf.m_ndims) :param bool log: emit the motor and sensory values for loggin...
python
def update(self, m_ag, reset=True, log=True): """ Computes sensorimotor values from motor orders. :param numpy.array m_ag: a motor command with shape (self.conf.m_ndims, ) or a set of n motor commands of shape (n, self.conf.m_ndims) :param bool log: emit the motor and sensory values for loggin...
[ "def", "update", "(", "self", ",", "m_ag", ",", "reset", "=", "True", ",", "log", "=", "True", ")", ":", "if", "reset", ":", "self", ".", "reset", "(", ")", "if", "len", "(", "array", "(", "m_ag", ")", ".", "shape", ")", "==", "1", ":", "s", ...
Computes sensorimotor values from motor orders. :param numpy.array m_ag: a motor command with shape (self.conf.m_ndims, ) or a set of n motor commands of shape (n, self.conf.m_ndims) :param bool log: emit the motor and sensory values for logging purpose (default: True). :returns: an array of ...
[ "Computes", "sensorimotor", "values", "from", "motor", "orders", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/environment.py#L78-L99
train
flowersteam/explauto
explauto/models/dataset.py
Databag.reset
def reset(self): """Reset the dataset to zero elements.""" self.data = [] self.size = 0 self.kdtree = None # KDTree self.nn_ready = False
python
def reset(self): """Reset the dataset to zero elements.""" self.data = [] self.size = 0 self.kdtree = None # KDTree self.nn_ready = False
[ "def", "reset", "(", "self", ")", ":", "self", ".", "data", "=", "[", "]", "self", ".", "size", "=", "0", "self", ".", "kdtree", "=", "None", "self", ".", "nn_ready", "=", "False" ]
Reset the dataset to zero elements.
[ "Reset", "the", "dataset", "to", "zero", "elements", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L32-L37
train
flowersteam/explauto
explauto/models/dataset.py
Databag._build_tree
def _build_tree(self): """Build the KDTree for the observed data """ if not self.nn_ready: self.kdtree = scipy.spatial.cKDTree(self.data) self.nn_ready = True
python
def _build_tree(self): """Build the KDTree for the observed data """ if not self.nn_ready: self.kdtree = scipy.spatial.cKDTree(self.data) self.nn_ready = True
[ "def", "_build_tree", "(", "self", ")", ":", "if", "not", "self", ".", "nn_ready", ":", "self", ".", "kdtree", "=", "scipy", ".", "spatial", ".", "cKDTree", "(", "self", ".", "data", ")", "self", ".", "nn_ready", "=", "True" ]
Build the KDTree for the observed data
[ "Build", "the", "KDTree", "for", "the", "observed", "data" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L73-L78
train
flowersteam/explauto
explauto/models/dataset.py
Dataset.from_data
def from_data(cls, data): """ Create a dataset from an array of data, infering the dimension from the datapoint """ if len(data) == 0: raise ValueError("data array is empty.") dim_x, dim_y = len(data[0][0]), len(data[0][1]) dataset = cls(dim_x, dim_y) for x, y in data...
python
def from_data(cls, data): """ Create a dataset from an array of data, infering the dimension from the datapoint """ if len(data) == 0: raise ValueError("data array is empty.") dim_x, dim_y = len(data[0][0]), len(data[0][1]) dataset = cls(dim_x, dim_y) for x, y in data...
[ "def", "from_data", "(", "cls", ",", "data", ")", ":", "if", "len", "(", "data", ")", "==", "0", ":", "raise", "ValueError", "(", "\"data array is empty.\"", ")", "dim_x", ",", "dim_y", "=", "len", "(", "data", "[", "0", "]", "[", "0", "]", ")", ...
Create a dataset from an array of data, infering the dimension from the datapoint
[ "Create", "a", "dataset", "from", "an", "array", "of", "data", "infering", "the", "dimension", "from", "the", "datapoint" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L88-L97
train
flowersteam/explauto
explauto/models/dataset.py
Dataset.from_xy
def from_xy(cls, x_array, y_array): """ Create a dataset from two arrays of data. :note: infering the dimensions for the first elements of each array. """ if len(x_array) == 0: raise ValueError("data array is empty.") dim_x, dim_y = len(x_array[0]), len(y_array[0...
python
def from_xy(cls, x_array, y_array): """ Create a dataset from two arrays of data. :note: infering the dimensions for the first elements of each array. """ if len(x_array) == 0: raise ValueError("data array is empty.") dim_x, dim_y = len(x_array[0]), len(y_array[0...
[ "def", "from_xy", "(", "cls", ",", "x_array", ",", "y_array", ")", ":", "if", "len", "(", "x_array", ")", "==", "0", ":", "raise", "ValueError", "(", "\"data array is empty.\"", ")", "dim_x", ",", "dim_y", "=", "len", "(", "x_array", "[", "0", "]", "...
Create a dataset from two arrays of data. :note: infering the dimensions for the first elements of each array.
[ "Create", "a", "dataset", "from", "two", "arrays", "of", "data", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L100-L112
train
flowersteam/explauto
explauto/models/dataset.py
Dataset.nn_x
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of x in the observed input data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ assert len(x) == self.dim_x k_x = min(k, self.size...
python
def nn_x(self, x, k=1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of x in the observed input data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ assert len(x) == self.dim_x k_x = min(k, self.size...
[ "def", "nn_x", "(", "self", ",", "x", ",", "k", "=", "1", ",", "radius", "=", "np", ".", "inf", ",", "eps", "=", "0.0", ",", "p", "=", "2", ")", ":", "assert", "len", "(", "x", ")", "==", "self", ".", "dim_x", "k_x", "=", "min", "(", "k",...
Find the k nearest neighbors of x in the observed input data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors.
[ "Find", "the", "k", "nearest", "neighbors", "of", "x", "in", "the", "observed", "input", "data" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/dataset.py#L204-L213
train
flowersteam/explauto
explauto/agent/agent.py
Agent.from_classes
def from_classes(cls, im_model_cls, im_model_config, expl_dims, sm_model_cls, sm_model_config, inf_dims, m_mins, m_maxs, s_mins, s_maxs, n_bootstrap=0, context_mode=None): """Initialize agent class :param class im_model_cls: a subclass of InterestedMod...
python
def from_classes(cls, im_model_cls, im_model_config, expl_dims, sm_model_cls, sm_model_config, inf_dims, m_mins, m_maxs, s_mins, s_maxs, n_bootstrap=0, context_mode=None): """Initialize agent class :param class im_model_cls: a subclass of InterestedMod...
[ "def", "from_classes", "(", "cls", ",", "im_model_cls", ",", "im_model_config", ",", "expl_dims", ",", "sm_model_cls", ",", "sm_model_config", ",", "inf_dims", ",", "m_mins", ",", "m_maxs", ",", "s_mins", ",", "s_maxs", ",", "n_bootstrap", "=", "0", ",", "co...
Initialize agent class :param class im_model_cls: a subclass of InterestedModel, as those registered in the interest_model package :param dict im_model_config: a configuration dict as those registered in the interest_model package :param list expl_dims: the sensorimotor dimensions where explo...
[ "Initialize", "agent", "class" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/agent/agent.py#L31-L59
train
flowersteam/explauto
explauto/agent/agent.py
Agent.choose
def choose(self, context_ms=None): """ Returns a point chosen by the interest model """ try: if self.context_mode is None: x = self.interest_model.sample() else: if self.context_mode["mode"] == 'mdmsds': if self.expl_dim...
python
def choose(self, context_ms=None): """ Returns a point chosen by the interest model """ try: if self.context_mode is None: x = self.interest_model.sample() else: if self.context_mode["mode"] == 'mdmsds': if self.expl_dim...
[ "def", "choose", "(", "self", ",", "context_ms", "=", "None", ")", ":", "try", ":", "if", "self", ".", "context_mode", "is", "None", ":", "x", "=", "self", ".", "interest_model", ".", "sample", "(", ")", "else", ":", "if", "self", ".", "context_mode"...
Returns a point chosen by the interest model
[ "Returns", "a", "point", "chosen", "by", "the", "interest", "model" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/agent/agent.py#L62-L84
train
flowersteam/explauto
explauto/agent/agent.py
Agent.infer
def infer(self, expl_dims, inf_dims, x): """ Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x. .. note:: This corresponds to a prediction if expl_dims=self.conf.m_dims and inf_dims=self.conf.s_dims and to inverse prediction if expl_dims=self.co...
python
def infer(self, expl_dims, inf_dims, x): """ Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x. .. note:: This corresponds to a prediction if expl_dims=self.conf.m_dims and inf_dims=self.conf.s_dims and to inverse prediction if expl_dims=self.co...
[ "def", "infer", "(", "self", ",", "expl_dims", ",", "inf_dims", ",", "x", ")", ":", "try", ":", "if", "self", ".", "n_bootstrap", ">", "0", ":", "self", ".", "n_bootstrap", "-=", "1", "raise", "ExplautoBootstrapError", "y", "=", "self", ".", "sensorimo...
Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x. .. note:: This corresponds to a prediction if expl_dims=self.conf.m_dims and inf_dims=self.conf.s_dims and to inverse prediction if expl_dims=self.conf.s_dims and inf_dims=self.conf.m_dims.
[ "Use", "the", "sensorimotor", "model", "to", "compute", "the", "expected", "value", "on", "inf_dims", "given", "that", "the", "value", "on", "expl_dims", "is", "x", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/agent/agent.py#L86-L101
train
flowersteam/explauto
explauto/environment/poppy/poppy_env.py
PoppyEnvironment.compute_motor_command
def compute_motor_command(self, m_ag): """ Compute the motor command by restricting it to the bounds. """ m_env = bounds_min_max(m_ag, self.conf.m_mins, self.conf.m_maxs) return m_env
python
def compute_motor_command(self, m_ag): """ Compute the motor command by restricting it to the bounds. """ m_env = bounds_min_max(m_ag, self.conf.m_mins, self.conf.m_maxs) return m_env
[ "def", "compute_motor_command", "(", "self", ",", "m_ag", ")", ":", "m_env", "=", "bounds_min_max", "(", "m_ag", ",", "self", ".", "conf", ".", "m_mins", ",", "self", ".", "conf", ".", "m_maxs", ")", "return", "m_env" ]
Compute the motor command by restricting it to the bounds.
[ "Compute", "the", "motor", "command", "by", "restricting", "it", "to", "the", "bounds", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/poppy/poppy_env.py#L42-L45
train
flowersteam/explauto
explauto/environment/poppy/poppy_env.py
PoppyEnvironment.compute_sensori_effect
def compute_sensori_effect(self, m_env): """ Move the robot motors and retrieve the tracked object position. """ pos = {m.name: pos for m, pos in zip(self.motors, m_env)} self.robot.goto_position(pos, self.move_duration, wait=True) # This allows to actually apply a motor command ...
python
def compute_sensori_effect(self, m_env): """ Move the robot motors and retrieve the tracked object position. """ pos = {m.name: pos for m, pos in zip(self.motors, m_env)} self.robot.goto_position(pos, self.move_duration, wait=True) # This allows to actually apply a motor command ...
[ "def", "compute_sensori_effect", "(", "self", ",", "m_env", ")", ":", "pos", "=", "{", "m", ".", "name", ":", "pos", "for", "m", ",", "pos", "in", "zip", "(", "self", ".", "motors", ",", "m_env", ")", "}", "self", ".", "robot", ".", "goto_position"...
Move the robot motors and retrieve the tracked object position.
[ "Move", "the", "robot", "motors", "and", "retrieve", "the", "tracked", "object", "position", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/poppy/poppy_env.py#L47-L55
train
flowersteam/explauto
explauto/sensorimotor_model/learner.py
Learner.infer_order
def infer_order(self, goal, **kwargs): """Infer an order in order to obtain an effect close to goal, given the observation data of the model. :arg goal: a goal vector compatible with self.Sfeats :rtype: same as goal (if list, tuple, or pandas.Series, else tuple) """ x ...
python
def infer_order(self, goal, **kwargs): """Infer an order in order to obtain an effect close to goal, given the observation data of the model. :arg goal: a goal vector compatible with self.Sfeats :rtype: same as goal (if list, tuple, or pandas.Series, else tuple) """ x ...
[ "def", "infer_order", "(", "self", ",", "goal", ",", "**", "kwargs", ")", ":", "x", "=", "self", ".", "imodel", ".", "infer_x", "(", "np", ".", "array", "(", "self", ".", "_pre_y", "(", "goal", ")", ")", ",", "**", "kwargs", ")", "[", "0", "]",...
Infer an order in order to obtain an effect close to goal, given the observation data of the model. :arg goal: a goal vector compatible with self.Sfeats :rtype: same as goal (if list, tuple, or pandas.Series, else tuple)
[ "Infer", "an", "order", "in", "order", "to", "obtain", "an", "effect", "close", "to", "goal", "given", "the", "observation", "data", "of", "the", "model", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/learner.py#L55-L63
train
flowersteam/explauto
explauto/sensorimotor_model/learner.py
Learner.predict_effect
def predict_effect(self, order, **kwargs): """Predict the effect of a goal. :arg order: an order vector compatible with self.Mfeats :rtype: same as order (if list, tuple, or pandas.Series, else tuple) """ y = self.imodel.fmodel.predict_y(np.array(self._pre_x(order)), **kwargs)...
python
def predict_effect(self, order, **kwargs): """Predict the effect of a goal. :arg order: an order vector compatible with self.Mfeats :rtype: same as order (if list, tuple, or pandas.Series, else tuple) """ y = self.imodel.fmodel.predict_y(np.array(self._pre_x(order)), **kwargs)...
[ "def", "predict_effect", "(", "self", ",", "order", ",", "**", "kwargs", ")", ":", "y", "=", "self", ".", "imodel", ".", "fmodel", ".", "predict_y", "(", "np", ".", "array", "(", "self", ".", "_pre_x", "(", "order", ")", ")", ",", "**", "kwargs", ...
Predict the effect of a goal. :arg order: an order vector compatible with self.Mfeats :rtype: same as order (if list, tuple, or pandas.Series, else tuple)
[ "Predict", "the", "effect", "of", "a", "goal", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/learner.py#L65-L72
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/sciopt.py
ScipyInverseModel._enforce_bounds
def _enforce_bounds(self, x): """"Enforce the bounds on x if only infinitesimal violations occurs""" assert len(x) == len(self.bounds) x_enforced = [] for x_i, (lb, ub) in zip(x, self.bounds): if x_i < lb: if x_i > lb - (ub-lb)/1e10: x_enfo...
python
def _enforce_bounds(self, x): """"Enforce the bounds on x if only infinitesimal violations occurs""" assert len(x) == len(self.bounds) x_enforced = [] for x_i, (lb, ub) in zip(x, self.bounds): if x_i < lb: if x_i > lb - (ub-lb)/1e10: x_enfo...
[ "def", "_enforce_bounds", "(", "self", ",", "x", ")", ":", "assert", "len", "(", "x", ")", "==", "len", "(", "self", ".", "bounds", ")", "x_enforced", "=", "[", "]", "for", "x_i", ",", "(", "lb", ",", "ub", ")", "in", "zip", "(", "x", ",", "s...
Enforce the bounds on x if only infinitesimal violations occurs
[ "Enforce", "the", "bounds", "on", "x", "if", "only", "infinitesimal", "violations", "occurs" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/sciopt.py#L67-L84
train
david-cortes/hpfrec
hpfrec/__init__.py
HPF.fit
def fit(self, counts_df, val_set=None): """ Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to ...
python
def fit(self, counts_df, val_set=None): """ Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to ...
[ "def", "fit", "(", "self", ",", "counts_df", ",", "val_set", "=", "None", ")", ":", "if", "self", ".", "stop_crit", "==", "'val-llk'", ":", "if", "val_set", "is", "None", ":", "raise", "ValueError", "(", "\"If 'stop_crit' is set to 'val-llk', must provide a vali...
Fit Hierarchical Poisson Model to sparse count data Fits a hierarchical Poisson model to count data using mean-field approximation with either full-batch coordinate-ascent or mini-batch stochastic coordinate-ascent. Note ---- DataFrames and arrays passed to '.fit' might be modified inplace - if this is a ...
[ "Fit", "Hierarchical", "Poisson", "Model", "to", "sparse", "count", "data" ]
cf0b18aa03e189f822b582d59c23f7862593289e
https://github.com/david-cortes/hpfrec/blob/cf0b18aa03e189f822b582d59c23f7862593289e/hpfrec/__init__.py#L344-L416
train
david-cortes/hpfrec
hpfrec/__init__.py
HPF.predict_factors
def predict_factors(self, counts_df, maxiter=10, ncores=1, random_seed=1, stop_thr=1e-3, return_all=False): """ Gets latent factors for a user given her item counts This is similar to obtaining topics for a document in LDA. Note ---- This function will NOT modify any of the item parameters. Note ----...
python
def predict_factors(self, counts_df, maxiter=10, ncores=1, random_seed=1, stop_thr=1e-3, return_all=False): """ Gets latent factors for a user given her item counts This is similar to obtaining topics for a document in LDA. Note ---- This function will NOT modify any of the item parameters. Note ----...
[ "def", "predict_factors", "(", "self", ",", "counts_df", ",", "maxiter", "=", "10", ",", "ncores", "=", "1", ",", "random_seed", "=", "1", ",", "stop_thr", "=", "1e-3", ",", "return_all", "=", "False", ")", ":", "ncores", ",", "random_seed", ",", "stop...
Gets latent factors for a user given her item counts This is similar to obtaining topics for a document in LDA. Note ---- This function will NOT modify any of the item parameters. Note ---- This function only works with one user at a time. Note ---- This function is prone to producing all NaNs v...
[ "Gets", "latent", "factors", "for", "a", "user", "given", "her", "item", "counts" ]
cf0b18aa03e189f822b582d59c23f7862593289e
https://github.com/david-cortes/hpfrec/blob/cf0b18aa03e189f822b582d59c23f7862593289e/hpfrec/__init__.py#L947-L1019
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/jacobian.py
JacobianInverseModel.infer_x
def infer_x(self, y_desired, **kwargs): """Provide an inversion of yq in the input space @param yq an array of float of length dim_y """ sigma = kwargs.get('sigma', self.sigma) k = kwargs.get('k', self.k) xq = self._guess_x(y_desired, k =...
python
def infer_x(self, y_desired, **kwargs): """Provide an inversion of yq in the input space @param yq an array of float of length dim_y """ sigma = kwargs.get('sigma', self.sigma) k = kwargs.get('k', self.k) xq = self._guess_x(y_desired, k =...
[ "def", "infer_x", "(", "self", ",", "y_desired", ",", "**", "kwargs", ")", ":", "sigma", "=", "kwargs", ".", "get", "(", "'sigma'", ",", "self", ".", "sigma", ")", "k", "=", "kwargs", ".", "get", "(", "'k'", ",", "self", ".", "k", ")", "xq", "=...
Provide an inversion of yq in the input space @param yq an array of float of length dim_y
[ "Provide", "an", "inversion", "of", "yq", "in", "the", "input", "space" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/jacobian.py#L19-L60
train
flowersteam/explauto
explauto/experiment/pool.py
ExperimentPool.from_settings_product
def from_settings_product(cls, environments, babblings, interest_models, sensorimotor_models, evaluate_at, testcases=None, same_testcases=False): """ Creates a ExperimentPool with the product of all the given settings. ...
python
def from_settings_product(cls, environments, babblings, interest_models, sensorimotor_models, evaluate_at, testcases=None, same_testcases=False): """ Creates a ExperimentPool with the product of all the given settings. ...
[ "def", "from_settings_product", "(", "cls", ",", "environments", ",", "babblings", ",", "interest_models", ",", "sensorimotor_models", ",", "evaluate_at", ",", "testcases", "=", "None", ",", "same_testcases", "=", "False", ")", ":", "l", "=", "itertools", ".", ...
Creates a ExperimentPool with the product of all the given settings. :param environments: e.g. [('simple_arm', 'default'), ('simple_arm', 'high_dimensional')] :type environments: list of (environment name, config name) :param babblings: e.g. ['motor', 'goal'] :type babli...
[ "Creates", "a", "ExperimentPool", "with", "the", "product", "of", "all", "the", "given", "settings", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/pool.py#L48-L73
train
flowersteam/explauto
explauto/environment/npendulum/npendulum.py
NPendulumEnvironment.compute_sensori_effect
def compute_sensori_effect(self, m): """ This function generates the end effector position at the end of the movement. .. note:: The duration of the movement is 1000*self.dt .. note:: To use basis functions rather than step functions, set :use_basis_functions: to 1 """ if self....
python
def compute_sensori_effect(self, m): """ This function generates the end effector position at the end of the movement. .. note:: The duration of the movement is 1000*self.dt .. note:: To use basis functions rather than step functions, set :use_basis_functions: to 1 """ if self....
[ "def", "compute_sensori_effect", "(", "self", ",", "m", ")", ":", "if", "self", ".", "use_basis_functions", ":", "func", "=", "simulation", ".", "step", "(", "m", ",", "1000", "*", "self", ".", "dt", ")", "else", ":", "traj", "=", "self", ".", "bf", ...
This function generates the end effector position at the end of the movement. .. note:: The duration of the movement is 1000*self.dt .. note:: To use basis functions rather than step functions, set :use_basis_functions: to 1
[ "This", "function", "generates", "the", "end", "effector", "position", "at", "the", "end", "of", "the", "movement", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/npendulum/npendulum.py#L33-L50
train
flowersteam/explauto
explauto/environment/npendulum/npendulum.py
NPendulumEnvironment.animate_pendulum
def animate_pendulum(self, m, path="anim_npendulum"): """This function generates few images at different instants in order to animate the pendulum. ..note:: this function destroys and creates the folder :anim_npendulum:. """ if os.path.exists(path): shutil.rmtree(path) ...
python
def animate_pendulum(self, m, path="anim_npendulum"): """This function generates few images at different instants in order to animate the pendulum. ..note:: this function destroys and creates the folder :anim_npendulum:. """ if os.path.exists(path): shutil.rmtree(path) ...
[ "def", "animate_pendulum", "(", "self", ",", "m", ",", "path", "=", "\"anim_npendulum\"", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "os", ".", "makedirs", "(", "path", ")", "...
This function generates few images at different instants in order to animate the pendulum. ..note:: this function destroys and creates the folder :anim_npendulum:.
[ "This", "function", "generates", "few", "images", "at", "different", "instants", "in", "order", "to", "animate", "the", "pendulum", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/npendulum/npendulum.py#L76-L90
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
_fileToMatrix
def _fileToMatrix(file_name): """rudimentary method to read in data from a file""" # TODO: np.loadtxt() might be an alternative # try: if 1 < 3: lres = [] for line in open(file_name, 'r').readlines(): if len(line) > 0 and line[0] not in ('%', '#'): lres.ap...
python
def _fileToMatrix(file_name): """rudimentary method to read in data from a file""" # TODO: np.loadtxt() might be an alternative # try: if 1 < 3: lres = [] for line in open(file_name, 'r').readlines(): if len(line) > 0 and line[0] not in ('%', '#'): lres.ap...
[ "def", "_fileToMatrix", "(", "file_name", ")", ":", "if", "1", "<", "3", ":", "lres", "=", "[", "]", "for", "line", "in", "open", "(", "file_name", ",", "'r'", ")", ".", "readlines", "(", ")", ":", "if", "len", "(", "line", ")", ">", "0", "and"...
rudimentary method to read in data from a file
[ "rudimentary", "method", "to", "read", "in", "data", "from", "a", "file" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L6827-L6841
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
pprint
def pprint(to_be_printed): """nicely formated print""" try: import pprint as pp # generate an instance PrettyPrinter # pp.PrettyPrinter().pprint(to_be_printed) pp.pprint(to_be_printed) except ImportError: if isinstance(to_be_printed, dict): print('{') ...
python
def pprint(to_be_printed): """nicely formated print""" try: import pprint as pp # generate an instance PrettyPrinter # pp.PrettyPrinter().pprint(to_be_printed) pp.pprint(to_be_printed) except ImportError: if isinstance(to_be_printed, dict): print('{') ...
[ "def", "pprint", "(", "to_be_printed", ")", ":", "try", ":", "import", "pprint", "as", "pp", "pp", ".", "pprint", "(", "to_be_printed", ")", "except", "ImportError", ":", "if", "isinstance", "(", "to_be_printed", ",", "dict", ")", ":", "print", "(", "'{'...
nicely formated print
[ "nicely", "formated", "print" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7863-L7881
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
felli
def felli(x): """unbound test function, needed to test multiprocessor""" return sum(1e6**(np.arange(len(x)) / (len(x) - 1)) * (np.array(x, copy=False))**2)
python
def felli(x): """unbound test function, needed to test multiprocessor""" return sum(1e6**(np.arange(len(x)) / (len(x) - 1)) * (np.array(x, copy=False))**2)
[ "def", "felli", "(", "x", ")", ":", "return", "sum", "(", "1e6", "**", "(", "np", ".", "arange", "(", "len", "(", "x", ")", ")", "/", "(", "len", "(", "x", ")", "-", "1", ")", ")", "*", "(", "np", ".", "array", "(", "x", ",", "copy", "=...
unbound test function, needed to test multiprocessor
[ "unbound", "test", "function", "needed", "to", "test", "multiprocessor" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8577-L8579
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BestSolution.update
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case ...
python
def update(self, arx, xarchive=None, arf=None, evals=None): """checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case ...
[ "def", "update", "(", "self", ",", "arx", ",", "xarchive", "=", "None", ",", "arf", "=", "None", ",", "evals", "=", "None", ")", ":", "if", "isinstance", "(", "arx", ",", "BestSolution", ")", ":", "if", "self", ".", "evalsall", "is", "None", ":", ...
checks for better solutions in list `arx`. Based on the smallest corresponding value in `arf`, alternatively, `update` may be called with a `BestSolution` instance like ``update(another_best_solution)`` in which case the better solution becomes the current best. `xarchive` is u...
[ "checks", "for", "better", "solutions", "in", "list", "arx", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L813-L851
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundaryHandlerBase.repair
def repair(self, x, copy_if_changed=True, copy_always=False): """projects infeasible values on the domain bound, might be overwritten by derived class """ if copy_always: x = array(x, copy=True) copy = False else: copy = copy_if_changed if self...
python
def repair(self, x, copy_if_changed=True, copy_always=False): """projects infeasible values on the domain bound, might be overwritten by derived class """ if copy_always: x = array(x, copy=True) copy = False else: copy = copy_if_changed if self...
[ "def", "repair", "(", "self", ",", "x", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ")", ":", "if", "copy_always", ":", "x", "=", "array", "(", "x", ",", "copy", "=", "True", ")", "copy", "=", "False", "else", ":", "copy"...
projects infeasible values on the domain bound, might be overwritten by derived class
[ "projects", "infeasible", "values", "on", "the", "domain", "bound", "might", "be", "overwritten", "by", "derived", "class" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L906-L926
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundaryHandlerBase.has_bounds
def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound in enumerate(bounds): if bound is not None: sign_ = 2 * ib - 1 for bound_i in bou...
python
def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound in enumerate(bounds): if bound is not None: sign_ = 2 * ib - 1 for bound_i in bou...
[ "def", "has_bounds", "(", "self", ")", ":", "bounds", "=", "self", ".", "bounds", "if", "bounds", "in", "(", "None", ",", "[", "None", ",", "None", "]", ")", ":", "return", "False", "for", "ib", ",", "bound", "in", "enumerate", "(", "bounds", ")", ...
return True, if any variable is bounded
[ "return", "True", "if", "any", "variable", "is", "bounded" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L954-L965
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundaryHandlerBase.is_in_bounds
def is_in_bounds(self, x): """not yet tested""" if self.bounds is None: return True for ib in [0, 1]: if self.bounds[ib] is None: continue for i in rglen(x): idx = min([i, len(self.bounds[ib]) - 1]) if self.bound...
python
def is_in_bounds(self, x): """not yet tested""" if self.bounds is None: return True for ib in [0, 1]: if self.bounds[ib] is None: continue for i in rglen(x): idx = min([i, len(self.bounds[ib]) - 1]) if self.bound...
[ "def", "is_in_bounds", "(", "self", ",", "x", ")", ":", "if", "self", ".", "bounds", "is", "None", ":", "return", "True", "for", "ib", "in", "[", "0", ",", "1", "]", ":", "if", "self", ".", "bounds", "[", "ib", "]", "is", "None", ":", "continue...
not yet tested
[ "not", "yet", "tested" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L967-L979
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundTransform.repair
def repair(self, x, copy_if_changed=True, copy_always=False): """transforms ``x`` into the bounded domain. ``copy_always`` option might disappear. """ copy = copy_if_changed if copy_always: x = array(x, copy=True) copy = False if self.bounds is N...
python
def repair(self, x, copy_if_changed=True, copy_always=False): """transforms ``x`` into the bounded domain. ``copy_always`` option might disappear. """ copy = copy_if_changed if copy_always: x = array(x, copy=True) copy = False if self.bounds is N...
[ "def", "repair", "(", "self", ",", "x", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ")", ":", "copy", "=", "copy_if_changed", "if", "copy_always", ":", "x", "=", "array", "(", "x", ",", "copy", "=", "True", ")", "copy", "="...
transforms ``x`` into the bounded domain. ``copy_always`` option might disappear.
[ "transforms", "x", "into", "the", "bounded", "domain", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1063-L1076
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundPenalty.repair
def repair(self, x, copy_if_changed=True, copy_always=False): """sets out-of-bounds components of ``x`` on the bounds. """ # TODO (old data): CPU(N,lam,iter=20,200,100): 3.3s of 8s for two bounds, 1.8s of 6.5s for one bound # remark: np.max([bounds[0], x]) is about 40 times slower than ...
python
def repair(self, x, copy_if_changed=True, copy_always=False): """sets out-of-bounds components of ``x`` on the bounds. """ # TODO (old data): CPU(N,lam,iter=20,200,100): 3.3s of 8s for two bounds, 1.8s of 6.5s for one bound # remark: np.max([bounds[0], x]) is about 40 times slower than ...
[ "def", "repair", "(", "self", ",", "x", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ")", ":", "copy", "=", "copy_if_changed", "if", "copy_always", ":", "x", "=", "array", "(", "x", ",", "copy", "=", "True", ")", "bounds", "...
sets out-of-bounds components of ``x`` on the bounds.
[ "sets", "out", "-", "of", "-", "bounds", "components", "of", "x", "on", "the", "bounds", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1137-L1167
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoundPenalty.update
def update(self, function_values, es): """updates the weights for computing a boundary penalty. Arguments --------- `function_values` all function values of recent population of solutions `es` `CMAEvolutionStrategy` object instance, in particular ...
python
def update(self, function_values, es): """updates the weights for computing a boundary penalty. Arguments --------- `function_values` all function values of recent population of solutions `es` `CMAEvolutionStrategy` object instance, in particular ...
[ "def", "update", "(", "self", ",", "function_values", ",", "es", ")", ":", "if", "self", ".", "bounds", "is", "None", "or", "(", "self", ".", "bounds", "[", "0", "]", "is", "None", "and", "self", ".", "bounds", "[", "1", "]", "is", "None", ")", ...
updates the weights for computing a boundary penalty. Arguments --------- `function_values` all function values of recent population of solutions `es` `CMAEvolutionStrategy` object instance, in particular mean and variances and the methods from the at...
[ "updates", "the", "weights", "for", "computing", "a", "boundary", "penalty", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1224-L1294
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoxConstraintsTransformationBase.initialize
def initialize(self): """initialize in base class""" self._lb = [b[0] for b in self.bounds] # can be done more efficiently? self._ub = [b[1] for b in self.bounds]
python
def initialize(self): """initialize in base class""" self._lb = [b[0] for b in self.bounds] # can be done more efficiently? self._ub = [b[1] for b in self.bounds]
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "_lb", "=", "[", "b", "[", "0", "]", "for", "b", "in", "self", ".", "bounds", "]", "self", ".", "_ub", "=", "[", "b", "[", "1", "]", "for", "b", "in", "self", ".", "bounds", "]" ]
initialize in base class
[ "initialize", "in", "base", "class" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1321-L1324
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoxConstraintsLinQuadTransformation.is_feasible_i
def is_feasible_i(self, x, i): """return True if value ``x`` is in the invertible domain of variable ``i`` """ lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] return lb - al < x < ub ...
python
def is_feasible_i(self, x, i): """return True if value ``x`` is in the invertible domain of variable ``i`` """ lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] return lb - al < x < ub ...
[ "def", "is_feasible_i", "(", "self", ",", "x", ",", "i", ")", ":", "lb", "=", "self", ".", "_lb", "[", "self", ".", "_index", "(", "i", ")", "]", "ub", "=", "self", ".", "_ub", "[", "self", ".", "_index", "(", "i", ")", "]", "al", "=", "sel...
return True if value ``x`` is in the invertible domain of variable ``i``
[ "return", "True", "if", "value", "x", "is", "in", "the", "invertible", "domain", "of", "variable", "i" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1513-L1522
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoxConstraintsLinQuadTransformation._transform_i
def _transform_i(self, x, i): """return transform of x in component i""" x = self._shift_or_mirror_into_invertible_i(x, i) lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if x < lb + al: ...
python
def _transform_i(self, x, i): """return transform of x in component i""" x = self._shift_or_mirror_into_invertible_i(x, i) lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if x < lb + al: ...
[ "def", "_transform_i", "(", "self", ",", "x", ",", "i", ")", ":", "x", "=", "self", ".", "_shift_or_mirror_into_invertible_i", "(", "x", ",", "i", ")", "lb", "=", "self", ".", "_lb", "[", "self", ".", "_index", "(", "i", ")", "]", "ub", "=", "sel...
return transform of x in component i
[ "return", "transform", "of", "x", "in", "component", "i" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1582-L1597
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
BoxConstraintsLinQuadTransformation._inverse_i
def _inverse_i(self, y, i): """return inverse of y in component i""" lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if 1 < 3: if not lb <= y <= ub: raise ValueError('argum...
python
def _inverse_i(self, y, i): """return inverse of y in component i""" lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if 1 < 3: if not lb <= y <= ub: raise ValueError('argum...
[ "def", "_inverse_i", "(", "self", ",", "y", ",", "i", ")", ":", "lb", "=", "self", ".", "_lb", "[", "self", ".", "_index", "(", "i", ")", "]", "ub", "=", "self", ".", "_ub", "[", "self", ".", "_index", "(", "i", ")", "]", "al", "=", "self",...
return inverse of y in component i
[ "return", "inverse", "of", "y", "in", "component", "i" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1598-L1612
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
GenoPheno.pheno
def pheno(self, x, into_bounds=None, copy=True, copy_always=False, archive=None, iteration=None): """maps the genotypic input argument into the phenotypic space, see help for class `GenoPheno` Details ------- If ``copy``, values from ``x`` are copied if changed und...
python
def pheno(self, x, into_bounds=None, copy=True, copy_always=False, archive=None, iteration=None): """maps the genotypic input argument into the phenotypic space, see help for class `GenoPheno` Details ------- If ``copy``, values from ``x`` are copied if changed und...
[ "def", "pheno", "(", "self", ",", "x", ",", "into_bounds", "=", "None", ",", "copy", "=", "True", ",", "copy_always", "=", "False", ",", "archive", "=", "None", ",", "iteration", "=", "None", ")", ":", "input_type", "=", "type", "(", "x", ")", "if"...
maps the genotypic input argument into the phenotypic space, see help for class `GenoPheno` Details ------- If ``copy``, values from ``x`` are copied if changed under the transformation.
[ "maps", "the", "genotypic", "input", "argument", "into", "the", "phenotypic", "space", "see", "help", "for", "class", "GenoPheno" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1753-L1806
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
GenoPheno.geno
def geno(self, y, from_bounds=None, copy_if_changed=True, copy_always=False, repair=None, archive=None): """maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to...
python
def geno(self, y, from_bounds=None, copy_if_changed=True, copy_always=False, repair=None, archive=None): """maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to...
[ "def", "geno", "(", "self", ",", "y", ",", "from_bounds", "=", "None", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ",", "repair", "=", "None", ",", "archive", "=", "None", ")", ":", "if", "from_bounds", "is", "None", ":", "...
maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to modify ``y``. The inverse of the user-defined transformation (if any) is only needed if external solutions are injected, it ...
[ "maps", "the", "phenotypic", "input", "argument", "into", "the", "genotypic", "space", "that", "is", "computes", "essentially", "the", "inverse", "of", "pheno", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1808-L1889
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
OOOptimizer.optimize
def optimize(self, objective_fct, iterations=None, min_iterations=1, args=(), verb_disp=None, logger=None, call_back=None): """find minimizer of `objective_fct`. CAVEAT: the return value for `optimize` has changed to ``self``. Arguments --------- `objectiv...
python
def optimize(self, objective_fct, iterations=None, min_iterations=1, args=(), verb_disp=None, logger=None, call_back=None): """find minimizer of `objective_fct`. CAVEAT: the return value for `optimize` has changed to ``self``. Arguments --------- `objectiv...
[ "def", "optimize", "(", "self", ",", "objective_fct", ",", "iterations", "=", "None", ",", "min_iterations", "=", "1", ",", "args", "=", "(", ")", ",", "verb_disp", "=", "None", ",", "logger", "=", "None", ",", "call_back", "=", "None", ")", ":", "as...
find minimizer of `objective_fct`. CAVEAT: the return value for `optimize` has changed to ``self``. Arguments --------- `objective_fct` function be to minimized `iterations` number of (maximal) iterations, while ``not self.stop()`` ...
[ "find", "minimizer", "of", "objective_fct", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L2010-L2106
train