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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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) return diffsigma
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) return diffsigma
[ "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
32,400
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.0 + np.log(f2) # epsilon factors computed from Eqs 21 to 23 with local ISM abundances epsC = 1.37 eps1 = 0.29 eps2 = 0.1 epstotal = np.where( Tp > self._Tth, epsC + (eps1 + eps2) * sigmaRpp * G / sigmainel, 0.0, ) if np.any(Tp < 1.0): # nuclear enhancement factor diverges towards Tp = Tth, fix Tp<1 to # eps(1.0) = 1.91 loE = np.where((Tp > self._Tth) * (Tp < 1.0)) epstotal[loE] = 1.9141 return epstotal
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.0 + np.log(f2) # epsilon factors computed from Eqs 21 to 23 with local ISM abundances epsC = 1.37 eps1 = 0.29 eps2 = 0.1 epstotal = np.where( Tp > self._Tth, epsC + (eps1 + eps2) * sigmaRpp * G / sigmainel, 0.0, ) if np.any(Tp < 1.0): # nuclear enhancement factor diverges towards Tp = Tth, fix Tp<1 to # eps(1.0) = 1.91 loE = np.where((Tp > self._Tth) * (Tp < 1.0)) epstotal[loE] = 1.9141 return epstotal
[ "def", "_nuclear_factor", "(", "self", ",", "Tp", ")", ":", "sigmaRpp", "=", "10", "*", "np", ".", "pi", "*", "1e-27", "sigmainel", "=", "self", ".", "_sigma_inel", "(", "Tp", ")", "sigmainel0", "=", "self", ".", "_sigma_inel", "(", "1e3", ")", "# at...
Compute nuclear enhancement factor
[ "Compute", "nuclear", "enhancement", "factor" ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1528-L1555
train
32,401
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 # Eq59 beta = (1.79 + 0.11 * L + 0.008 * L ** 2) ** -1 # Eq60 k = (0.801 + 0.049 * L + 0.014 * L ** 2) ** -1 # Eq61 xb = x ** beta F1 = B * (np.log(x) / x) * ((1 - xb) / (1 + k * xb * (1 - xb))) ** 4 F2 = ( 1.0 / np.log(x) - (4 * beta * xb) / (1 - xb) - (4 * k * beta * xb * (1 - 2 * xb)) / (1 + k * xb * (1 - xb)) ) return F1 * F2
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 # Eq59 beta = (1.79 + 0.11 * L + 0.008 * L ** 2) ** -1 # Eq60 k = (0.801 + 0.049 * L + 0.014 * L ** 2) ** -1 # Eq61 xb = x ** beta F1 = B * (np.log(x) / x) * ((1 - xb) / (1 + k * xb * (1 - xb))) ** 4 F2 = ( 1.0 / np.log(x) - (4 * beta * xb) / (1 - xb) - (4 * k * beta * xb * (1 - 2 * xb)) / (1 + k * xb * (1 - xb)) ) return F1 * F2
[ "def", "_Fgamma", "(", "self", ",", "x", ",", "Ep", ")", ":", "L", "=", "np", ".", "log", "(", "Ep", ")", "B", "=", "1.30", "+", "0.14", "*", "L", "+", "0.011", "*", "L", "**", "2", "# Eq59", "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
32,402
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 Inelastic cross-section for p-p interaction [1/cm2]. """ L = np.log(Ep) sigma = 34.3 + 1.88 * L + 0.25 * L ** 2 if Ep <= 0.1: Eth = 1.22e-3 sigma *= (1 - (Eth / Ep) ** 4) ** 2 * heaviside(Ep - Eth) return sigma * 1e-27
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 Inelastic cross-section for p-p interaction [1/cm2]. """ L = np.log(Ep) sigma = 34.3 + 1.88 * L + 0.25 * L ** 2 if Ep <= 0.1: Eth = 1.22e-3 sigma *= (1 - (Eth / Ep) ** 4) ** 2 * heaviside(Ep - Eth) return sigma * 1e-27
[ "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/cm2].
[ "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
32,403
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 ) except ZeroDivisionError: return np.nan
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 ) except ZeroDivisionError: return np.nan
[ "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
32,404
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 distributions (e.g. # Maxwellian) at ~500 GeV. Reverting to adaptative quadrature # from scipy.integrate import fixed_quad # result=c*fixed_quad(self._photon_integrand, 0., 1., args = [Egamma, # ], n = 40)[0] from scipy.integrate import quad Egamma = Egamma.to("TeV").value specpp = ( c.cgs.value * quad( self._photon_integrand, 0.0, 1.0, args=Egamma, epsrel=1e-3, epsabs=0, )[0] ) return specpp * u.Unit("1/(s TeV)")
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 distributions (e.g. # Maxwellian) at ~500 GeV. Reverting to adaptative quadrature # from scipy.integrate import fixed_quad # result=c*fixed_quad(self._photon_integrand, 0., 1., args = [Egamma, # ], n = 40)[0] from scipy.integrate import quad Egamma = Egamma.to("TeV").value specpp = ( c.cgs.value * quad( self._photon_integrand, 0.0, 1.0, args=Egamma, epsrel=1e-3, epsabs=0, )[0] ) return specpp * u.Unit("1/(s TeV)")
[ "def", "_calc_specpp_hiE", "(", "self", ",", "Egamma", ")", ":", "# 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 distributions (e.g.", "# Maxwellian) at ~500 GeV. Re...
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
32,405
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 * quad( self._delta_integrand, Epimin, np.inf, epsrel=1e-3, epsabs=0 )[0] ) return result * u.Unit("1/(s TeV)")
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 * quad( self._delta_integrand, Epimin, np.inf, epsrel=1e-3, epsabs=0 )[0] ) return result * u.Unit("1/(s TeV)")
[ "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
32,406
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 namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults to ``config.conf``. Returns: str: Fully qualified path (dir & filename) where we expect the config file. """ return os.path.join(appdirs.user_config_dir, file_name)
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 namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults to ``config.conf``. Returns: str: Fully qualified path (dir & filename) where we expect the config file. """ return os.path.join(appdirs.user_config_dir, file_name)
[ "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 to ``config.conf``. Returns: str: Fully qualified path (dir & filename) where we expect the config file.
[ "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
32,407
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`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config file. Defaults to ``DEFAULT_CONFIG_FILENAME``. Returns: SafeConfigParser: Instance written to file. """ path = get_config_path(appdirs, file_name) with open(path, 'w') as fobj: config_instance.write(fobj) return config_instance
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`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config file. Defaults to ``DEFAULT_CONFIG_FILENAME``. Returns: SafeConfigParser: Instance written to file. """ path = get_config_path(appdirs, file_name) with open(path, 'w') as fobj: config_instance.write(fobj) return config_instance
[ "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 file. Defaults to ``DEFAULT_CONFIG_FILENAME``. Returns: SafeConfigParser: Instance written to file.
[ "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
32,408
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 provided with the result of ``get_default_backend_config``. Args: appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config file. Defaults to ``DEFAULT_CONFIG_FILENAME``. fallback_config_instance (ConfigParser): Backend config that is to be used to populate the config file that is created if no pre-existing one can be found. Returns: SafeConfigParser: Config loaded from file, either from the the pre-existing config file or the one created with fallback values. """ if not fallback_config_instance: fallback_config_instance = backend_config_to_configparser( get_default_backend_config(appdirs) ) config = SafeConfigParser() path = get_config_path(appdirs, file_name) if not config.read(path): config = write_config_file( fallback_config_instance, appdirs=appdirs, file_name=file_name ) return config
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 provided with the result of ``get_default_backend_config``. Args: appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config file. Defaults to ``DEFAULT_CONFIG_FILENAME``. fallback_config_instance (ConfigParser): Backend config that is to be used to populate the config file that is created if no pre-existing one can be found. Returns: SafeConfigParser: Config loaded from file, either from the the pre-existing config file or the one created with fallback values. """ if not fallback_config_instance: fallback_config_instance = backend_config_to_configparser( get_default_backend_config(appdirs) ) config = SafeConfigParser() path = get_config_path(appdirs, file_name) if not config.read(path): config = write_config_file( fallback_config_instance, appdirs=appdirs, file_name=file_name ) return config
[ "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`` instance storing app/user specific path information. file_name (text_type, optional): Name of the config file. Defaults to ``DEFAULT_CONFIG_FILENAME``. fallback_config_instance (ConfigParser): Backend config that is to be used to populate the config file that is created if no pre-existing one can be found. Returns: SafeConfigParser: Config loaded from file, either from the the pre-existing config file or the one created with fallback values.
[ "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
32,409
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 particular config-store. """ return { 'store': 'sqlalchemy', 'day_start': datetime.time(5, 30, 0), 'fact_min_delta': 1, 'tmpfile_path': os.path.join(appdirs.user_data_dir, '{}.tmp'.format(appdirs.appname)), 'db_engine': 'sqlite', 'db_path': os.path.join(appdirs.user_data_dir, '{}.sqlite'.format(appdirs.appname)), }
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 particular config-store. """ return { 'store': 'sqlalchemy', 'day_start': datetime.time(5, 30, 0), 'fact_min_delta': 1, 'tmpfile_path': os.path.join(appdirs.user_data_dir, '{}.tmp'.format(appdirs.appname)), 'db_engine': 'sqlite', 'db_path': os.path.join(appdirs.user_data_dir, '{}.sqlite'.format(appdirs.appname)), }
[ "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
32,410
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 not provide *any* validation about mandatory values what so ever. """ def get_store(): return config.get('store') def get_day_start(): day_start = config.get('day_start') if day_start: day_start = day_start.strftime('%H:%M:%S') return day_start def get_fact_min_delta(): return text_type(config.get('fact_min_delta')) def get_tmpfile_path(): return text_type(config.get('tmpfile_path')) def get_db_engine(): return text_type(config.get('db_engine')) def get_db_path(): return text_type(config.get('db_path')) def get_db_host(): return text_type(config.get('db_host')) def get_db_port(): return text_type(config.get('db_port')) def get_db_name(): return text_type(config.get('db_name')) def get_db_user(): return text_type(config.get('db_user')) def get_db_password(): return text_type(config.get('db_password')) cp_instance = SafeConfigParser() cp_instance.add_section('Backend') cp_instance.set('Backend', 'store', get_store()) cp_instance.set('Backend', 'day_start', get_day_start()) cp_instance.set('Backend', 'fact_min_delta', get_fact_min_delta()) cp_instance.set('Backend', 'tmpfile_path', get_tmpfile_path()) cp_instance.set('Backend', 'db_engine', get_db_engine()) cp_instance.set('Backend', 'db_path', get_db_path()) cp_instance.set('Backend', 'db_host', get_db_host()) cp_instance.set('Backend', 'db_port', get_db_port()) cp_instance.set('Backend', 'db_name', get_db_name()) cp_instance.set('Backend', 'db_user', get_db_user()) cp_instance.set('Backend', 'db_password', get_db_password()) return cp_instance
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 not provide *any* validation about mandatory values what so ever. """ def get_store(): return config.get('store') def get_day_start(): day_start = config.get('day_start') if day_start: day_start = day_start.strftime('%H:%M:%S') return day_start def get_fact_min_delta(): return text_type(config.get('fact_min_delta')) def get_tmpfile_path(): return text_type(config.get('tmpfile_path')) def get_db_engine(): return text_type(config.get('db_engine')) def get_db_path(): return text_type(config.get('db_path')) def get_db_host(): return text_type(config.get('db_host')) def get_db_port(): return text_type(config.get('db_port')) def get_db_name(): return text_type(config.get('db_name')) def get_db_user(): return text_type(config.get('db_user')) def get_db_password(): return text_type(config.get('db_password')) cp_instance = SafeConfigParser() cp_instance.add_section('Backend') cp_instance.set('Backend', 'store', get_store()) cp_instance.set('Backend', 'day_start', get_day_start()) cp_instance.set('Backend', 'fact_min_delta', get_fact_min_delta()) cp_instance.set('Backend', 'tmpfile_path', get_tmpfile_path()) cp_instance.set('Backend', 'db_engine', get_db_engine()) cp_instance.set('Backend', 'db_path', get_db_path()) cp_instance.set('Backend', 'db_host', get_db_host()) cp_instance.set('Backend', 'db_port', get_db_port()) cp_instance.set('Backend', 'db_name', get_db_name()) cp_instance.set('Backend', 'db_user', get_db_user()) cp_instance.set('Backend', 'db_password', get_db_password()) return cp_instance
[ "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 so ever.
[ "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
32,411
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 in order to extract its config. If a key is not found in ``cp_instance`` the resulting dict will have ``None`` assigned to this dict key. """ def get_store(): # [TODO] # This should be deligated to a dedicated validation function! store = cp_instance.get('Backend', 'store') if store not in hamster_lib.REGISTERED_BACKENDS.keys(): raise ValueError(_("Unrecognized store option.")) return store def get_day_start(): try: day_start = datetime.datetime.strptime(cp_instance.get('Backend', 'day_start'), '%H:%M:%S').time() except ValueError: raise ValueError(_( "We encountered an error when parsing configs 'day_start'" " value! Aborting ..." )) return day_start def get_fact_min_delta(): return cp_instance.getint('Backend', 'fact_min_delta') def get_tmpfile_path(): return cp_instance.get('Backend', 'tmpfile_path') def get_db_engine(): return text_type(cp_instance.get('Backend', 'db_engine')) def get_db_path(): return text_type(cp_instance.get('Backend', 'db_path')) def get_db_host(): return text_type(cp_instance.get('Backend', 'db_host')) def get_db_port(): return cp_instance.getint('Backend', 'db_port') def get_db_name(): return text_type(cp_instance.get('Backend', 'db_name')) def get_db_user(): return text_type(cp_instance.get('Backend', 'db_user')) def get_db_password(): return text_type(cp_instance.get('Backend', 'db_password')) result = { 'store': get_store(), 'day_start': get_day_start(), 'fact_min_delta': get_fact_min_delta(), 'tmpfile_path': get_tmpfile_path(), 'db_engine': get_db_engine(), 'db_path': get_db_path(), 'db_host': get_db_host(), 'db_port': get_db_port(), 'db_name': get_db_name(), 'db_user': get_db_user(), 'db_password': get_db_password(), } return result
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 in order to extract its config. If a key is not found in ``cp_instance`` the resulting dict will have ``None`` assigned to this dict key. """ def get_store(): # [TODO] # This should be deligated to a dedicated validation function! store = cp_instance.get('Backend', 'store') if store not in hamster_lib.REGISTERED_BACKENDS.keys(): raise ValueError(_("Unrecognized store option.")) return store def get_day_start(): try: day_start = datetime.datetime.strptime(cp_instance.get('Backend', 'day_start'), '%H:%M:%S').time() except ValueError: raise ValueError(_( "We encountered an error when parsing configs 'day_start'" " value! Aborting ..." )) return day_start def get_fact_min_delta(): return cp_instance.getint('Backend', 'fact_min_delta') def get_tmpfile_path(): return cp_instance.get('Backend', 'tmpfile_path') def get_db_engine(): return text_type(cp_instance.get('Backend', 'db_engine')) def get_db_path(): return text_type(cp_instance.get('Backend', 'db_path')) def get_db_host(): return text_type(cp_instance.get('Backend', 'db_host')) def get_db_port(): return cp_instance.getint('Backend', 'db_port') def get_db_name(): return text_type(cp_instance.get('Backend', 'db_name')) def get_db_user(): return text_type(cp_instance.get('Backend', 'db_user')) def get_db_password(): return text_type(cp_instance.get('Backend', 'db_password')) result = { 'store': get_store(), 'day_start': get_day_start(), 'fact_min_delta': get_fact_min_delta(), 'tmpfile_path': get_tmpfile_path(), 'db_engine': get_db_engine(), 'db_path': get_db_path(), 'db_host': get_db_host(), 'db_port': get_db_port(), 'db_name': get_db_name(), 'db_user': get_db_user(), 'db_password': get_db_password(), } return result
[ "def", "configparser_to_backend_config", "(", "cp_instance", ")", ":", "def", "get_store", "(", ")", ":", "# [TODO]", "# This should be deligated to a dedicated validation function!", "store", "=", "cp_instance", ".", "get", "(", "'Backend'", ",", "'store'", ")", "if", ...
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 in ``cp_instance`` the resulting dict will have ``None`` assigned to this dict key.
[ "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
32,412
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
32,413
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 directory
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 directory
[ "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
32,414
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
32,415
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
32,416
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 for some reason our stored instance is no instance of ``hamster_lib.Fact``. """ from hamster_lib import Fact try: with open(filepath, 'rb') as fobj: fact = pickle.load(fobj) except IOError: fact = False else: if not isinstance(fact, Fact): raise TypeError(_( "Something went wrong. It seems our pickled file does not contain" " valid Fact instance. [Content: '{content}'; Type: {type}".format( content=fact, type=type(fact)) )) return fact
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 for some reason our stored instance is no instance of ``hamster_lib.Fact``. """ from hamster_lib import Fact try: with open(filepath, 'rb') as fobj: fact = pickle.load(fobj) except IOError: fact = False else: if not isinstance(fact, Fact): raise TypeError(_( "Something went wrong. It seems our pickled file does not contain" " valid Fact instance. [Content: '{content}'; Type: {type}".format( content=fact, type=type(fact)) )) return fact
[ "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 instance of ``hamster_lib.Fact``.
[ "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
32,417
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 everything in front of the (leftmost) '@'-symbol, if it was used. Args: string (str): The string to be parsed. Returns: tuple: (front, back) representing the substrings before and after the most left ``@`` symbol. If no such symbol was present at all, ``back=None``. Both substrings have been trimmed of any leading and trailing whitespace. Note: If our string contains multiple ``@`` symbols, all but the most left one will be treated as part of the regular ``back`` string. This allows for usage of the symbol in descriptions, categories and tags. Also note that *no tags are extracted* any tags included will be considered part of the ``category`` string. We are likely to remove this parsing function in ``0.14.0`` in favour of a regex based solution so we will not spend time on tags for now """ result = string.split('@', 1) length = len(result) if length == 1: front, back = result[0].strip(), None else: front, back = result front, back = front.strip(), back.strip() return (front, back) def comma_split(string): """ Split string at the most left comma. Args: string (str): String to be processed. At this stage this should look something like ``<Category> and <tags>, <Description> Returns tuple: (category_and_tags, description). Both substrings have their leading/trailing whitespace removed. ``category_and_tags`` may include >=0 tags indicated by a leading ``#``. As we have used the most left ``,`` to separate both substrings that means that categories and tags can not contain any ``,`` but the description text may contain as many as wished. """ result = string.split(',', 1) length = len(result) if length == 1: category, description = result[0].strip(), None else: category, description = tuple(result) category, description = category.strip(), description.strip() return (category.strip(), description) time_info, rest = time_helpers.extract_time_info(raw_fact) activity_name, back = at_split(rest) if back: category_name, description = comma_split(back) else: category_name, description = None, None return { 'timeinfo': time_info, 'category': category_name, 'activity': activity_name, 'description': description, }
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 everything in front of the (leftmost) '@'-symbol, if it was used. Args: string (str): The string to be parsed. Returns: tuple: (front, back) representing the substrings before and after the most left ``@`` symbol. If no such symbol was present at all, ``back=None``. Both substrings have been trimmed of any leading and trailing whitespace. Note: If our string contains multiple ``@`` symbols, all but the most left one will be treated as part of the regular ``back`` string. This allows for usage of the symbol in descriptions, categories and tags. Also note that *no tags are extracted* any tags included will be considered part of the ``category`` string. We are likely to remove this parsing function in ``0.14.0`` in favour of a regex based solution so we will not spend time on tags for now """ result = string.split('@', 1) length = len(result) if length == 1: front, back = result[0].strip(), None else: front, back = result front, back = front.strip(), back.strip() return (front, back) def comma_split(string): """ Split string at the most left comma. Args: string (str): String to be processed. At this stage this should look something like ``<Category> and <tags>, <Description> Returns tuple: (category_and_tags, description). Both substrings have their leading/trailing whitespace removed. ``category_and_tags`` may include >=0 tags indicated by a leading ``#``. As we have used the most left ``,`` to separate both substrings that means that categories and tags can not contain any ``,`` but the description text may contain as many as wished. """ result = string.split(',', 1) length = len(result) if length == 1: category, description = result[0].strip(), None else: category, description = tuple(result) category, description = category.strip(), description.strip() return (category.strip(), description) time_info, rest = time_helpers.extract_time_info(raw_fact) activity_name, back = at_split(rest) if back: category_name, description = comma_split(back) else: category_name, description = None, None return { 'timeinfo': time_info, 'category': category_name, 'activity': activity_name, 'description': description, }
[ "def", "parse_raw_fact", "(", "raw_fact", ")", ":", "def", "at_split", "(", "string", ")", ":", "\"\"\"\n Return everything in front of the (leftmost) '@'-symbol, if it was used.\n\n Args:\n string (str): The string to be parsed.\n\n Returns:\n tup...
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
32,418
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 provide the model function with the `modelfn` argument given that functions cannot be serialized in hdf5 files. Parameters ---------- filename : str Filename of the hdf5 containing the chain, lnprobability, and blob arrays in the group 'sampler' modelfn : function, optional Model function to be attached to the returned sampler Returns ------- result : class Container object with same properties as an `emcee.EnsembleSampler` resulting from a sampling run. This object can be passed onto `~naima.plot_fit`, `~naima.plot_chain`, and `~naima.plot_corner` for analysis as you would do with a `emcee.EnsembleSampler` instance. """ # initialize empty sampler class to return result = _result() result.modelfn = modelfn result.run_info = {} f = h5py.File(filename, "r") # chain and lnprobability result.chain = np.array(f["sampler/chain"]) result.lnprobability = np.array(f["sampler/lnprobability"]) # blobs result.blobs = [] shape = result.chain.shape[:2] blobs = [] blobrank = [] for i in range(100): # first read each of the blobs and convert to Quantities try: ds = f["sampler/blob{0}".format(i)] rank = np.ndim(ds[0]) blobrank.append(rank) if rank <= 1: blobs.append(u.Quantity(ds.value, unit=ds.attrs["unit"])) else: blob = [] for j in range(np.ndim(ds[0])): blob.append( u.Quantity( ds.value[:, j, :], unit=ds.attrs["unit{0}".format(j)], ) ) blobs.append(blob) except KeyError: break # Now organize in an awful list of lists of arrays for step in range(shape[1]): steplist = [] for walker in range(shape[0]): n = step * shape[0] + walker walkerblob = [] for j in range(len(blobs)): if blobrank[j] <= 1: walkerblob.append(blobs[j][n]) else: blob = [] for k in range(blobrank[j]): blob.append(blobs[j][k][n]) walkerblob.append(blob) steplist.append(walkerblob) result.blobs.append(steplist) # run info result.run_info = dict(f["sampler"].attrs) result.acceptance_fraction = f["sampler"].attrs["acceptance_fraction"] # labels result.labels = [] for i in range(result.chain.shape[2]): result.labels.append(f["sampler"].attrs["label{0}".format(i)]) # data data = Table(np.array(f["sampler/data"])) data.meta.update(f["sampler/data"].attrs) for col in data.colnames: if f["sampler/data"].attrs[col + "unit"] != "None": data[col].unit = f["sampler/data"].attrs[col + "unit"] result.data = QTable(data) return result
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 provide the model function with the `modelfn` argument given that functions cannot be serialized in hdf5 files. Parameters ---------- filename : str Filename of the hdf5 containing the chain, lnprobability, and blob arrays in the group 'sampler' modelfn : function, optional Model function to be attached to the returned sampler Returns ------- result : class Container object with same properties as an `emcee.EnsembleSampler` resulting from a sampling run. This object can be passed onto `~naima.plot_fit`, `~naima.plot_chain`, and `~naima.plot_corner` for analysis as you would do with a `emcee.EnsembleSampler` instance. """ # initialize empty sampler class to return result = _result() result.modelfn = modelfn result.run_info = {} f = h5py.File(filename, "r") # chain and lnprobability result.chain = np.array(f["sampler/chain"]) result.lnprobability = np.array(f["sampler/lnprobability"]) # blobs result.blobs = [] shape = result.chain.shape[:2] blobs = [] blobrank = [] for i in range(100): # first read each of the blobs and convert to Quantities try: ds = f["sampler/blob{0}".format(i)] rank = np.ndim(ds[0]) blobrank.append(rank) if rank <= 1: blobs.append(u.Quantity(ds.value, unit=ds.attrs["unit"])) else: blob = [] for j in range(np.ndim(ds[0])): blob.append( u.Quantity( ds.value[:, j, :], unit=ds.attrs["unit{0}".format(j)], ) ) blobs.append(blob) except KeyError: break # Now organize in an awful list of lists of arrays for step in range(shape[1]): steplist = [] for walker in range(shape[0]): n = step * shape[0] + walker walkerblob = [] for j in range(len(blobs)): if blobrank[j] <= 1: walkerblob.append(blobs[j][n]) else: blob = [] for k in range(blobrank[j]): blob.append(blobs[j][k][n]) walkerblob.append(blob) steplist.append(walkerblob) result.blobs.append(steplist) # run info result.run_info = dict(f["sampler"].attrs) result.acceptance_fraction = f["sampler"].attrs["acceptance_fraction"] # labels result.labels = [] for i in range(result.chain.shape[2]): result.labels.append(f["sampler"].attrs["label{0}".format(i)]) # data data = Table(np.array(f["sampler/data"])) data.meta.update(f["sampler/data"].attrs) for col in data.colnames: if f["sampler/data"].attrs[col + "unit"] != "None": data[col].unit = f["sampler/data"].attrs[col + "unit"] result.data = QTable(data) return result
[ "def", "read_run", "(", "filename", ",", "modelfn", "=", "None", ")", ":", "# initialize empty sampler class to return", "result", "=", "_result", "(", ")", "result", ".", "modelfn", "=", "modelfn", "result", ".", "run_info", "=", "{", "}", "f", "=", "h5py",...
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` argument given that functions cannot be serialized in hdf5 files. Parameters ---------- filename : str Filename of the hdf5 containing the chain, lnprobability, and blob arrays in the group 'sampler' modelfn : function, optional Model function to be attached to the returned sampler Returns ------- result : class Container object with same properties as an `emcee.EnsembleSampler` resulting from a sampling run. This object can be passed onto `~naima.plot_fit`, `~naima.plot_chain`, and `~naima.plot_corner` for analysis as you would do with a `emcee.EnsembleSampler` instance.
[ "Read", "chain", "from", "a", "hdf5", "saved", "with", "save_run", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/analysis.py#L530-L627
train
32,419
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"]) return IC.flux(data, distance=1.0 * u.kpc)
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"]) return IC.flux(data, distance=1.0 * u.kpc)
[ "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
32,420
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.ExponentialCutoffPowerLaw( ampl * 1e30 * u.Unit("1/eV"), ref * u.TeV, index, cutoff * u.TeV, beta=beta, ) return pdist
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.ExponentialCutoffPowerLaw( ampl * 1e30 * u.Unit("1/eV"), ref * u.TeV, index, cutoff * u.TeV, beta=beta, ) return pdist
[ "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
32,421
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. last_step : bool (optional) Whether to plot the last step of the chain or the complete chain (default). Returns ------- figure : `matplotlib.figure.Figure` Figure """ if p is None: npars = sampler.chain.shape[-1] for pp in six.moves.range(npars): _plot_chain_func(sampler, pp, **kwargs) fig = None else: fig = _plot_chain_func(sampler, p, **kwargs) return fig
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. last_step : bool (optional) Whether to plot the last step of the chain or the complete chain (default). Returns ------- figure : `matplotlib.figure.Figure` Figure """ if p is None: npars = sampler.chain.shape[-1] for pp in six.moves.range(npars): _plot_chain_func(sampler, pp, **kwargs) fig = None else: fig = _plot_chain_func(sampler, p, **kwargs) return fig
[ "def", "plot_chain", "(", "sampler", ",", "p", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "p", "is", "None", ":", "npars", "=", "sampler", ".", "chain", ".", "shape", "[", "-", "1", "]", "for", "pp", "in", "six", ".", "moves", ".", ...
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 to plot the last step of the chain or the complete chain (default). Returns ------- figure : `matplotlib.figure.Figure` Figure
[ "Generate", "a", "diagnostic", "plot", "of", "the", "sampler", "chains", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L34-L60
train
32,422
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, model = _process_blob(sampler, modelidx, last_step=last_step) else: # prepare bogus data for calculation e_range = validate_array( "e_range", u.Quantity(e_range), physical_type="energy" ) e_unit = e_range.unit energy = ( np.logspace( np.log10(e_range[0].value), np.log10(e_range[1].value), e_npoints, ) * e_unit ) data = { "energy": energy, "flux": np.zeros(energy.shape) * sampler.data["flux"].unit, } # init pool and select parameters chain = sampler.chain[-1] if last_step else sampler.flatchain pars = chain[np.random.randint(len(chain), size=n_samples)] blobs = [] p = Pool(threads) modelouts = p.map(partial(sampler.modelfn, data=data), pars) p.close() p.terminate() for modelout in modelouts: if isinstance(modelout, np.ndarray): blobs.append([modelout]) else: blobs.append(modelout) modelx, model = _process_blob( blobs, modelidx=modelidx, energy=data["energy"] ) return modelx, model
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, model = _process_blob(sampler, modelidx, last_step=last_step) else: # prepare bogus data for calculation e_range = validate_array( "e_range", u.Quantity(e_range), physical_type="energy" ) e_unit = e_range.unit energy = ( np.logspace( np.log10(e_range[0].value), np.log10(e_range[1].value), e_npoints, ) * e_unit ) data = { "energy": energy, "flux": np.zeros(energy.shape) * sampler.data["flux"].unit, } # init pool and select parameters chain = sampler.chain[-1] if last_step else sampler.flatchain pars = chain[np.random.randint(len(chain), size=n_samples)] blobs = [] p = Pool(threads) modelouts = p.map(partial(sampler.modelfn, data=data), pars) p.close() p.terminate() for modelout in modelouts: if isinstance(modelout, np.ndarray): blobs.append([modelout]) else: blobs.append(modelout) modelx, model = _process_blob( blobs, modelidx=modelidx, energy=data["energy"] ) return modelx, model
[ "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
32,423
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( "e_range", u.Quantity(e_range), physical_type="energy" ) e_unit = e_range.unit energy = ( np.logspace( np.log10(e_range[0].value), np.log10(e_range[1].value), e_npoints, ) * e_unit ) data = { "energy": energy, "flux": np.zeros(energy.shape) * sampler.data["flux"].unit, } modelout = sampler.modelfn(MLp, data) if isinstance(modelout, np.ndarray): blob = modelout else: blob = modelout[modelidx] if isinstance(blob, u.Quantity): modelx = data["energy"].copy() model_ML = blob.copy() elif len(blob) == 2: modelx = blob[0].copy() model_ML = blob[1].copy() else: raise TypeError("Model {0} has wrong blob format".format(modelidx)) ML_model = (modelx, model_ML) return ML, MLp, MLerr, ML_model
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( "e_range", u.Quantity(e_range), physical_type="energy" ) e_unit = e_range.unit energy = ( np.logspace( np.log10(e_range[0].value), np.log10(e_range[1].value), e_npoints, ) * e_unit ) data = { "energy": energy, "flux": np.zeros(energy.shape) * sampler.data["flux"].unit, } modelout = sampler.modelfn(MLp, data) if isinstance(modelout, np.ndarray): blob = modelout else: blob = modelout[modelidx] if isinstance(blob, u.Quantity): modelx = data["energy"].copy() model_ML = blob.copy() elif len(blob) == 2: modelx = blob[0].copy() model_ML = blob[1].copy() else: raise TypeError("Model {0} has wrong blob format".format(modelidx)) ML_model = (modelx, model_ML) return ML, MLp, MLerr, ML_model
[ "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
32,424
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_model[0].to(e_unit).value, (ML_model[1] * sedf).to(f_unit).value, color="k", lw=2, alpha=0.8, )
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_model[0].to(e_unit).value, (ML_model[1] * sedf).to(f_unit).value, color="k", lw=2, alpha=0.8, )
[ "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
32,425
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. 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 units of the observed spectrum will be used. confs : list, optional List of confidence levels (in sigma) to use for generating the confidence intervals. Default is `[3,1,0.5]` e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False). """ confs.sort(reverse=True) modelx, CI = _calc_CI( sampler, modelidx=modelidx, confs=confs, e_range=e_range, e_npoints=e_npoints, last_step=last_step, threads=threads, ) # pick first confidence interval curve for units f_unit, sedf = sed_conversion(modelx, CI[0][0].unit, sed) for (ymin, ymax), conf in zip(CI, confs): color = np.log(conf) / np.log(20) + 0.4 ax.fill_between( modelx.to(e_unit).value, (ymax * sedf).to(f_unit).value, (ymin * sedf).to(f_unit).value, lw=0.001, color=(color,) * 3, alpha=0.6, zorder=-10, ) _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed) if label is not None: ax.set_ylabel( "{0} [{1}]".format(label, f_unit.to_string("latex_inline")) )
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. 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 units of the observed spectrum will be used. confs : list, optional List of confidence levels (in sigma) to use for generating the confidence intervals. Default is `[3,1,0.5]` e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False). """ confs.sort(reverse=True) modelx, CI = _calc_CI( sampler, modelidx=modelidx, confs=confs, e_range=e_range, e_npoints=e_npoints, last_step=last_step, threads=threads, ) # pick first confidence interval curve for units f_unit, sedf = sed_conversion(modelx, CI[0][0].unit, sed) for (ymin, ymax), conf in zip(CI, confs): color = np.log(conf) / np.log(20) + 0.4 ax.fill_between( modelx.to(e_unit).value, (ymax * sedf).to(f_unit).value, (ymin * sedf).to(f_unit).value, lw=0.001, color=(color,) * 3, alpha=0.6, zorder=-10, ) _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed) if label is not None: ax.set_ylabel( "{0} [{1}]".format(label, f_unit.to_string("latex_inline")) )
[ "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 units of the observed spectrum will be used. confs : list, optional List of confidence levels (in sigma) to use for generating the confidence intervals. Default is `[3,1,0.5]` e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False).
[ "Plot", "confidence", "interval", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L553-L625
train
32,426
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` 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 units of the observed spectrum will be used. n_samples : int, optional Number of samples to plot. Default is 100. e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_range : list of `~astropy.units.Quantity`, length 2, optional Limits in energy for the computation of the model samples and ML model. Note that setting this parameter will mean that the samples for the model are recomputed and depending on the model speed might be quite slow. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False). """ modelx, model = _read_or_calc_samples( sampler, modelidx, last_step=last_step, e_range=e_range, e_npoints=e_npoints, threads=threads, ) # pick first model sample for units f_unit, sedf = sed_conversion(modelx, model[0].unit, sed) sample_alpha = min(5.0 / n_samples, 0.5) for my in model[np.random.randint(len(model), size=n_samples)]: ax.loglog( modelx.to(e_unit).value, (my * sedf).to(f_unit).value, color=(0.1,) * 3, alpha=sample_alpha, lw=1.0, ) _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed) if label is not None: ax.set_ylabel( "{0} [{1}]".format(label, f_unit.to_string("latex_inline")) )
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` 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 units of the observed spectrum will be used. n_samples : int, optional Number of samples to plot. Default is 100. e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_range : list of `~astropy.units.Quantity`, length 2, optional Limits in energy for the computation of the model samples and ML model. Note that setting this parameter will mean that the samples for the model are recomputed and depending on the model speed might be quite slow. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False). """ modelx, model = _read_or_calc_samples( sampler, modelidx, last_step=last_step, e_range=e_range, e_npoints=e_npoints, threads=threads, ) # pick first model sample for units f_unit, sedf = sed_conversion(modelx, model[0].unit, sed) sample_alpha = min(5.0 / n_samples, 0.5) for my in model[np.random.randint(len(model), size=n_samples)]: ax.loglog( modelx.to(e_unit).value, (my * sedf).to(f_unit).value, color=(0.1,) * 3, alpha=sample_alpha, lw=1.0, ) _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed) if label is not None: ax.set_ylabel( "{0} [{1}]".format(label, f_unit.to_string("latex_inline")) )
[ "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 spectrum. If `None`, the units of the observed spectrum will be used. n_samples : int, optional Number of samples to plot. Default is 100. e_unit : :class:`~astropy.units.Unit` or str parseable to unit Unit in which to plot energy axis. e_range : list of `~astropy.units.Quantity`, length 2, optional Limits in energy for the computation of the model samples and ML model. Note that setting this parameter will mean that the samples for the model are recomputed and depending on the model speed might be quite slow. e_npoints : int, optional How many points to compute for the model samples and ML model if `e_range` is set. threads : int, optional How many parallel processing threads to use when computing the samples. Defaults to the number of available cores. last_step : bool, optional Whether to only use the positions in the final step of the run (True, default) or the whole chain (False).
[ "Plot", "a", "number", "of", "samples", "from", "the", "sampler", "chain", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L628-L700
train
32,427
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 hasattr(sampler, "blobs"): blob = sampler.blobs[index[1]][index[0]][modelidx] if isinstance(blob, u.Quantity): modelx = sampler.data["energy"].copy() model_ML = blob.copy() elif len(blob) == 2: modelx = blob[0].copy() model_ML = blob[1].copy() else: raise TypeError("Model {0} has wrong blob format".format(modelidx)) elif modelidx is not None and hasattr(sampler, "modelfn"): blob = _process_blob( [sampler.modelfn(MLp, sampler.data)], modelidx, energy=sampler.data["energy"], ) modelx, model_ML = blob[0], blob[1][0] else: modelx, model_ML = None, None MLerr = [] for dist in sampler.flatchain.T: hilo = np.percentile(dist, [16.0, 84.0]) MLerr.append((hilo[1] - hilo[0]) / 2.0) ML = sampler.lnprobability[index] return ML, MLp, MLerr, (modelx, model_ML)
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 hasattr(sampler, "blobs"): blob = sampler.blobs[index[1]][index[0]][modelidx] if isinstance(blob, u.Quantity): modelx = sampler.data["energy"].copy() model_ML = blob.copy() elif len(blob) == 2: modelx = blob[0].copy() model_ML = blob[1].copy() else: raise TypeError("Model {0} has wrong blob format".format(modelidx)) elif modelidx is not None and hasattr(sampler, "modelfn"): blob = _process_blob( [sampler.modelfn(MLp, sampler.data)], modelidx, energy=sampler.data["energy"], ) modelx, model_ML = blob[0], blob[1][0] else: modelx, model_ML = None, None MLerr = [] for dist in sampler.flatchain.T: hilo = np.percentile(dist, [16.0, 84.0]) MLerr.append((hilo[1] - hilo[0]) / 2.0) ML = sampler.lnprobability[index] return ML, MLp, MLerr, (modelx, model_ML)
[ "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
32,428
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 stored chain. blobidx : int, optional Metadata blob index to plot. label : str, optional Label for the value distribution. Labels for the fit plot can be passed as ``xlabel`` and ``ylabel`` and will be passed to `plot_fit`. Returns ------- figure : `matplotlib.pyplot.Figure` `matplotlib` figure instance containing the plot. """ modelx, model = _process_blob(sampler, blobidx, last_step) if label is None: label = "Model output {0}".format(blobidx) if modelx is None: # Blob is scalar, plot distribution f = plot_distribution(model, label, figure=figure) else: f = plot_fit( sampler, modelidx=blobidx, last_step=last_step, label=label, figure=figure, **kwargs ) return f
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 stored chain. blobidx : int, optional Metadata blob index to plot. label : str, optional Label for the value distribution. Labels for the fit plot can be passed as ``xlabel`` and ``ylabel`` and will be passed to `plot_fit`. Returns ------- figure : `matplotlib.pyplot.Figure` `matplotlib` figure instance containing the plot. """ modelx, model = _process_blob(sampler, blobidx, last_step) if label is None: label = "Model output {0}".format(blobidx) if modelx is None: # Blob is scalar, plot distribution f = plot_distribution(model, label, figure=figure) else: f = plot_fit( sampler, modelidx=blobidx, last_step=last_step, label=label, figure=figure, **kwargs ) return f
[ "def", "plot_blob", "(", "sampler", ",", "blobidx", "=", "0", ",", "label", "=", "None", ",", "last_step", "=", "False", ",", "figure", "=", "None", ",", "*", "*", "kwargs", ")", ":", "modelx", ",", "model", "=", "_process_blob", "(", "sampler", ",",...
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 Label for the value distribution. Labels for the fit plot can be passed as ``xlabel`` and ``ylabel`` and will be passed to `plot_fit`. Returns ------- figure : `matplotlib.pyplot.Figure` `matplotlib` figure instance containing the plot.
[ "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
32,429
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, capsize=0 ) from distutils.version import LooseVersion import matplotlib mpl_version = LooseVersion(matplotlib.__version__) if mpl_version >= LooseVersion("1.4.0"): ax.errorbar( x, y, yerr=height_fraction * y, ls="", uplims=True, color=color, elinewidth=elinewidth, capsize=capsize, zorder=10, ) else: ax.errorbar( x, (1 - height_fraction) * y, yerr=height_fraction * y, ls="", lolims=True, color=color, elinewidth=elinewidth, capsize=capsize, zorder=10, )
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, capsize=0 ) from distutils.version import LooseVersion import matplotlib mpl_version = LooseVersion(matplotlib.__version__) if mpl_version >= LooseVersion("1.4.0"): ax.errorbar( x, y, yerr=height_fraction * y, ls="", uplims=True, color=color, elinewidth=elinewidth, capsize=capsize, zorder=10, ) else: ax.errorbar( x, (1 - height_fraction) * y, yerr=height_fraction * y, ls="", lolims=True, color=color, elinewidth=elinewidth, capsize=capsize, zorder=10, )
[ "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
32,430
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 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, optional Label for the ``x`` axis of the plot. ylabel : str, optional Label for the ``y`` axis of the plot. sed : bool, optional Whether to plot SED or differential spectrum. figure : `matplotlib.figure.Figure`, optional `matplotlib` figure to plot on. If omitted a new one will be generated. e_unit : `astropy.unit.Unit`, optional Units for energy axis. Defaults to those of the data. ulim_opts : dict Options for upper-limit plotting. Available options are capsize (arrow width) and height_fraction (arrow length in fraction of flux value). errorbar_opts : dict Addtional options to pass to `matplotlib.plt.errorbar` for plotting the spectral flux points. """ import matplotlib.pyplot as plt try: data = validate_data_table(input_data) except TypeError as exc: if hasattr(input_data, "data"): data = input_data.data elif isinstance(input_data, dict) and "energy" in input_data.keys(): data = input_data else: log.warning( "input_data format unknown, no plotting data! " "Data loading exception: {}".format(exc) ) raise if figure is None: f = plt.figure() else: f = figure if len(f.axes) > 0: ax1 = f.axes[0] else: ax1 = f.add_subplot(111) # try to get units from previous plot in figure try: old_e_unit = u.Unit(ax1.get_xlabel().split("[")[-1].split("]")[0]) except ValueError: old_e_unit = u.Unit("") if e_unit is None and old_e_unit.physical_type == "energy": e_unit = old_e_unit elif e_unit is None: e_unit = data["energy"].unit _plot_data_to_ax( data, ax1, e_unit=e_unit, sed=sed, ylabel=ylabel, ulim_opts=ulim_opts, errorbar_opts=errorbar_opts, ) if xlabel is not None: ax1.set_xlabel(xlabel) elif xlabel is None and ax1.get_xlabel() == "": ax1.set_xlabel( r"$\mathrm{Energy}$" + " [{0}]".format(e_unit.to_string("latex_inline")) ) ax1.autoscale() return f
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 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, optional Label for the ``x`` axis of the plot. ylabel : str, optional Label for the ``y`` axis of the plot. sed : bool, optional Whether to plot SED or differential spectrum. figure : `matplotlib.figure.Figure`, optional `matplotlib` figure to plot on. If omitted a new one will be generated. e_unit : `astropy.unit.Unit`, optional Units for energy axis. Defaults to those of the data. ulim_opts : dict Options for upper-limit plotting. Available options are capsize (arrow width) and height_fraction (arrow length in fraction of flux value). errorbar_opts : dict Addtional options to pass to `matplotlib.plt.errorbar` for plotting the spectral flux points. """ import matplotlib.pyplot as plt try: data = validate_data_table(input_data) except TypeError as exc: if hasattr(input_data, "data"): data = input_data.data elif isinstance(input_data, dict) and "energy" in input_data.keys(): data = input_data else: log.warning( "input_data format unknown, no plotting data! " "Data loading exception: {}".format(exc) ) raise if figure is None: f = plt.figure() else: f = figure if len(f.axes) > 0: ax1 = f.axes[0] else: ax1 = f.add_subplot(111) # try to get units from previous plot in figure try: old_e_unit = u.Unit(ax1.get_xlabel().split("[")[-1].split("]")[0]) except ValueError: old_e_unit = u.Unit("") if e_unit is None and old_e_unit.physical_type == "energy": e_unit = old_e_unit elif e_unit is None: e_unit = data["energy"].unit _plot_data_to_ax( data, ax1, e_unit=e_unit, sed=sed, ylabel=ylabel, ulim_opts=ulim_opts, errorbar_opts=errorbar_opts, ) if xlabel is not None: ax1.set_xlabel(xlabel) elif xlabel is None and ax1.get_xlabel() == "": ax1.set_xlabel( r"$\mathrm{Energy}$" + " [{0}]".format(e_unit.to_string("latex_inline")) ) ax1.autoscale() return f
[ "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, optional Label for the ``x`` axis of the plot. ylabel : str, optional Label for the ``y`` axis of the plot. sed : bool, optional Whether to plot SED or differential spectrum. figure : `matplotlib.figure.Figure`, optional `matplotlib` figure to plot on. If omitted a new one will be generated. e_unit : `astropy.unit.Unit`, optional Units for energy axis. Defaults to those of the data. ulim_opts : dict Options for upper-limit plotting. Available options are capsize (arrow width) and height_fraction (arrow length in fraction of flux value). errorbar_opts : dict Addtional options to pass to `matplotlib.plt.errorbar` for plotting the spectral flux points.
[ "Plot", "spectral", "data", "." ]
d6a6781d73bf58fd8269e8b0e3b70be22723cd5b
https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/plot.py#L1282-L1376
train
32,431
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 isinstance(samples[0], u.Quantity): unit = samples[0].unit else: unit = "" if isinstance(std, u.Quantity): std = std.value dist_props = "{label} distribution properties:\n \ $-$ median: ${median}$ {unit}, std: ${std}$ {unit}\n \ $-$ Median with uncertainties based on \n \ the 16th and 84th percentiles ($\sim$1$\sigma$):\n\ {label} = {value_error} {unit}".format( label=label, median=_latex_float(quantiles[50]), std=_latex_float(std), value_error=_latex_value_error( quantiles[50], quantiles[50] - quantiles[16], quantiles[84] - quantiles[50], ), unit=unit, ) if figure is None: f = plt.figure() else: f = figure ax = f.add_subplot(111) f.subplots_adjust(bottom=0.40, top=0.93, left=0.06, right=0.95) f.text(0.2, 0.27, dist_props, ha="left", va="top") histnbins = min(max(25, int(len(samples) / 100.0)), 100) xlabel = "" if label is None else label if isinstance(samples, u.Quantity): samples_nounit = samples.value else: samples_nounit = samples n, x, _ = ax.hist( samples_nounit, histnbins, histtype="stepfilled", color=color_cycle[0], lw=0, density=True, ) kde = stats.kde.gaussian_kde(samples_nounit) ax.plot(x, kde(x), color="k", label="KDE") ax.axvline( quantiles[50], ls="--", color="k", alpha=0.5, lw=2, label="50% quantile", ) ax.axvspan( quantiles[16], quantiles[84], color=(0.5,) * 3, alpha=0.25, label="68% CI", lw=0, ) # ax.legend() for l in ax.get_xticklabels(): l.set_rotation(45) # [l.set_rotation(45) for l in ax.get_yticklabels()] if unit != "": xlabel += " [{0}]".format(unit) ax.set_xlabel(xlabel) ax.set_title("posterior distribution of {0}".format(label)) ax.set_ylim(top=n.max() * 1.05) return f
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 isinstance(samples[0], u.Quantity): unit = samples[0].unit else: unit = "" if isinstance(std, u.Quantity): std = std.value dist_props = "{label} distribution properties:\n \ $-$ median: ${median}$ {unit}, std: ${std}$ {unit}\n \ $-$ Median with uncertainties based on \n \ the 16th and 84th percentiles ($\sim$1$\sigma$):\n\ {label} = {value_error} {unit}".format( label=label, median=_latex_float(quantiles[50]), std=_latex_float(std), value_error=_latex_value_error( quantiles[50], quantiles[50] - quantiles[16], quantiles[84] - quantiles[50], ), unit=unit, ) if figure is None: f = plt.figure() else: f = figure ax = f.add_subplot(111) f.subplots_adjust(bottom=0.40, top=0.93, left=0.06, right=0.95) f.text(0.2, 0.27, dist_props, ha="left", va="top") histnbins = min(max(25, int(len(samples) / 100.0)), 100) xlabel = "" if label is None else label if isinstance(samples, u.Quantity): samples_nounit = samples.value else: samples_nounit = samples n, x, _ = ax.hist( samples_nounit, histnbins, histtype="stepfilled", color=color_cycle[0], lw=0, density=True, ) kde = stats.kde.gaussian_kde(samples_nounit) ax.plot(x, kde(x), color="k", label="KDE") ax.axvline( quantiles[50], ls="--", color="k", alpha=0.5, lw=2, label="50% quantile", ) ax.axvspan( quantiles[16], quantiles[84], color=(0.5,) * 3, alpha=0.25, label="68% CI", lw=0, ) # ax.legend() for l in ax.get_xticklabels(): l.set_rotation(45) # [l.set_rotation(45) for l in ax.get_yticklabels()] if unit != "": xlabel += " [{0}]".format(unit) ax.set_xlabel(xlabel) ax.set_title("posterior distribution of {0}".format(label)) ax.set_ylim(top=n.max() * 1.05) return f
[ "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
32,432
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`, found at https://github.com/corner/corner.py. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a stored chain. show_ML : bool, optional Whether to show the maximum likelihood parameter vector as a cross on the 2D histograms. """ import matplotlib.pyplot as plt oldlw = plt.rcParams["lines.linewidth"] plt.rcParams["lines.linewidth"] = 0.7 try: from corner import corner if show_ML: _, MLp, _, _ = find_ML(sampler, 0) else: MLp = None corner_opts = { "labels": sampler.labels, "truths": MLp, "quantiles": [0.16, 0.5, 0.84], "verbose": False, "truth_color": color_cycle[0], } corner_opts.update(kwargs) f = corner(sampler.flatchain, **corner_opts) except ImportError: log.warning( "The corner package is not installed;" " corner plot not available" ) f = None plt.rcParams["lines.linewidth"] = oldlw return f
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`, found at https://github.com/corner/corner.py. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a stored chain. show_ML : bool, optional Whether to show the maximum likelihood parameter vector as a cross on the 2D histograms. """ import matplotlib.pyplot as plt oldlw = plt.rcParams["lines.linewidth"] plt.rcParams["lines.linewidth"] = 0.7 try: from corner import corner if show_ML: _, MLp, _, _ = find_ML(sampler, 0) else: MLp = None corner_opts = { "labels": sampler.labels, "truths": MLp, "quantiles": [0.16, 0.5, 0.84], "verbose": False, "truth_color": color_cycle[0], } corner_opts.update(kwargs) f = corner(sampler.flatchain, **corner_opts) except ImportError: log.warning( "The corner package is not installed;" " corner plot not available" ) f = None plt.rcParams["lines.linewidth"] = oldlw return f
[ "def", "plot_corner", "(", "sampler", ",", "show_ML", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "oldlw", "=", "plt", ".", "rcParams", "[", "\"lines.linewidth\"", "]", "plt", ".", "rcParams", "[", ...
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. Parameters ---------- sampler : `emcee.EnsembleSampler` Sampler with a stored chain. show_ML : bool, optional Whether to show the maximum likelihood parameter vector as a cross on the 2D histograms.
[ "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
32,433
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) _, index = self.dataset.nn_dims(x, c, range(self.dim_x), list(np.array(c_dims) + self.dim_x), k=1) return self.dataset.get_y(index[0])
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) _, index = self.dataset.nn_dims(x, c, range(self.dim_x), list(np.array(c_dims) + self.dim_x), k=1) return self.dataset.get_y(index[0])
[ "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
32,434
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 """ if isinstance(x, np.ndarray): return np.ones(x.shape) return 1
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 """ if isinstance(x, np.ndarray): return np.ones(x.shape) return 1
[ "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
32,435
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(.) """ assert len(xq) == self.dataset.dim_x sigma_sq = self.sigma_sq if sigma is None else sigma*sigma k = k or self.k dists, index = self.dataset.nn_x(xq, k=k) w = self._weights(dists, index, sigma_sq) Xq = np.array(np.append([1.0], xq), ndmin = 2) X = np.array([self.dataset.get_x_padded(i) for i in index]) Y = np.array([self.dataset.get_y(i) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) self.mat = np.dot(B, np.dot(W, Y)) Yq = np.dot(Xq, self.mat) return Yq.ravel()
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(.) """ assert len(xq) == self.dataset.dim_x sigma_sq = self.sigma_sq if sigma is None else sigma*sigma k = k or self.k dists, index = self.dataset.nn_x(xq, k=k) w = self._weights(dists, index, sigma_sq) Xq = np.array(np.append([1.0], xq), ndmin = 2) X = np.array([self.dataset.get_x_padded(i) for i in index]) Y = np.array([self.dataset.get_y(i) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) self.mat = np.dot(B, np.dot(W, Y)) Yq = np.dot(Xq, self.mat) return Yq.ravel()
[ "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
32,436
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._weights(.) """ assert len(q) == len(dims_x) + len(dims_y) sigma_sq = self.sigma_sq if sigma is None else sigma*sigma k = k or self.k dists, index = self.dataset.nn_dims(q[:len(dims_x)], q[len(dims_x):], dims_x, dims_y, k=k) w = self._weights(dists, index, sigma_sq) Xq = np.array(np.append([1.0], q), ndmin = 2) X = np.array([np.append([1.0], self.dataset.get_dims(i, dims_x=dims_x, dims_y=dims_y)) for i in index]) Y = np.array([self.dataset.get_dims(i, dims=dims_out) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) self.mat = np.dot(B, np.dot(W, Y)) Yq = np.dot(Xq, self.mat) return Yq.ravel()
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._weights(.) """ assert len(q) == len(dims_x) + len(dims_y) sigma_sq = self.sigma_sq if sigma is None else sigma*sigma k = k or self.k dists, index = self.dataset.nn_dims(q[:len(dims_x)], q[len(dims_x):], dims_x, dims_y, k=k) w = self._weights(dists, index, sigma_sq) Xq = np.array(np.append([1.0], q), ndmin = 2) X = np.array([np.append([1.0], self.dataset.get_dims(i, dims_x=dims_x, dims_y=dims_y)) for i in index]) Y = np.array([self.dataset.get_dims(i, dims=dims_out) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) self.mat = np.dot(B, np.dot(W, Y)) Yq = np.dot(Xq, self.mat) return Yq.ravel()
[ "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
32,437
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 plotted for that topic. :param int t: time indexes to be plotted :param dict kwargs_plot: argument to be passed to matplotlib's plot function, e.g. the style of the plotted points 'or' :param bool ms_limits: if set to True, automatically set axes boundaries to the sensorimotor boundaries (default: True) """ plot_specs = {'marker': 'o', 'linestyle': 'None'} plot_specs.update(kwargs_plot) # t_bound = float('inf') # if t is None: # for topic, _ in topic_dims: # t_bound = min(t_bound, self.counts[topic]) # t = range(t_bound) # data = self.pack(topic_dims, t) data = self.data_t(topic_dims, t) ax.plot(*(data.T), **plot_specs) if ms_limits: ax.axis(self.axes_limits(topic_dims))
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 plotted for that topic. :param int t: time indexes to be plotted :param dict kwargs_plot: argument to be passed to matplotlib's plot function, e.g. the style of the plotted points 'or' :param bool ms_limits: if set to True, automatically set axes boundaries to the sensorimotor boundaries (default: True) """ plot_specs = {'marker': 'o', 'linestyle': 'None'} plot_specs.update(kwargs_plot) # t_bound = float('inf') # if t is None: # for topic, _ in topic_dims: # t_bound = min(t_bound, self.counts[topic]) # t = range(t_bound) # data = self.pack(topic_dims, t) data = self.data_t(topic_dims, t) ax.plot(*(data.T), **plot_specs) if ms_limits: ax.axis(self.axes_limits(topic_dims))
[ "def", "scatter_plot", "(", "self", ",", "ax", ",", "topic_dims", ",", "t", "=", "None", ",", "ms_limits", "=", "True", ",", "*", "*", "kwargs_plot", ")", ":", "plot_specs", "=", "{", "'marker'", ":", "'o'", ",", "'linestyle'", ":", "'None'", "}", "p...
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 dict kwargs_plot: argument to be passed to matplotlib's plot function, e.g. the style of the plotted points 'or' :param bool ms_limits: if set to True, automatically set axes boundaries to the sensorimotor boundaries (default: True)
[ "2D", "or", "3D", "scatter", "plot", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/experiment/log.py#L67-L93
train
32,438
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
32,439
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
32,440
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.pt2leaf(x)
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.pt2leaf(x)
[ "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
32,441
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 = ((self.split_value - self.bounds_x[0,self.split_dim]) / (self.bounds_x[1,self.split_dim] - self.bounds_x[0,self.split_dim])) if split_ratio > np.random.random(): return self.lower.sample(sampling_mode=['random']) else: return self.greater.sample(sampling_mode=['random']) else: # Choose a leaf randomly return np.random.choice(self.get_leaves()).sample_bounds()
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 = ((self.split_value - self.bounds_x[0,self.split_dim]) / (self.bounds_x[1,self.split_dim] - self.bounds_x[0,self.split_dim])) if split_ratio > np.random.random(): return self.lower.sample(sampling_mode=['random']) else: return self.greater.sample(sampling_mode=['random']) else: # Choose a leaf randomly return np.random.choice(self.get_leaves()).sample_bounds()
[ "def", "sample_random", "(", "self", ")", ":", "if", "self", ".", "sampling_mode", "[", "'volume'", "]", ":", "# Choose a leaf weighted by volume, randomly", "if", "self", ".", "leafnode", ":", "return", "self", ".", "sample_bounds", "(", ")", "else", ":", "sp...
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
32,442
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 = max(lp, gp) if self.sampling_mode['multiscale']: tp = self.progress if tp > maxp: return self.sample_bounds() if gp == maxp: sampling_mode = self.sampling_mode sampling_mode['mode'] = 'greedy' return self.greater.sample(sampling_mode=sampling_mode) else: sampling_mode = self.sampling_mode sampling_mode['mode'] = 'greedy' return self.lower.sample(sampling_mode=sampling_mode)
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 = max(lp, gp) if self.sampling_mode['multiscale']: tp = self.progress if tp > maxp: return self.sample_bounds() if gp == maxp: sampling_mode = self.sampling_mode sampling_mode['mode'] = 'greedy' return self.greater.sample(sampling_mode=sampling_mode) else: sampling_mode = self.sampling_mode sampling_mode['mode'] = 'greedy' return self.lower.sample(sampling_mode=sampling_mode)
[ "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
32,443
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
32,444
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:] return abs(np.cov(zip(range(len(idxs)), self.get_data_c()[idxs]), rowvar=0)[0, 1]) elif self.progress_measure == 'abs_deriv': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] return np.abs(np.mean(np.diff(self.get_data_c()[idxs], axis=0))) elif self.progress_measure == 'abs_deriv_smooth': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] v = self.get_data_c()[idxs] n = len(v) comp_beg = np.mean(v[:int(float(n)/2.)]) comp_end = np.mean(v[int(float(n)/2.):]) return np.abs(comp_end - comp_beg) else: raise NotImplementedError(self.progress_measure)
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:] return abs(np.cov(zip(range(len(idxs)), self.get_data_c()[idxs]), rowvar=0)[0, 1]) elif self.progress_measure == 'abs_deriv': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] return np.abs(np.mean(np.diff(self.get_data_c()[idxs], axis=0))) elif self.progress_measure == 'abs_deriv_smooth': if len(idxs) <= 1: return 0 else: idxs = sorted(idxs)[- self.progress_win_size:] v = self.get_data_c()[idxs] n = len(v) comp_beg = np.mean(v[:int(float(n)/2.)]) comp_end = np.mean(v[int(float(n)/2.):]) return np.abs(comp_end - comp_beg) else: raise NotImplementedError(self.progress_measure)
[ "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
32,445
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_inter, f_leaf), self.greater.fold_up(f_inter, f_leaf))
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_inter, f_leaf), self.greater.fold_up(f_inter, f_leaf))
[ "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
32,446
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 points (m,s) explored during the optimisation self.pointsList.append((m,s)) return self.dist_array(S)
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 points (m,s) explored during the optimisation self.pointsList.append((m,s)) return self.dist_array(S)
[ "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
32,447
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
32,448
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
32,449
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
32,450
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_at: raise ValueError('Set n_iter or define evaluate_at.') n_iter = self.eval_at[-1] + 1 self._running.set() if bg: self._t = threading.Thread(target=lambda: self._run(n_iter)) self._t.start() else: self._run(n_iter)
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_at: raise ValueError('Set n_iter or define evaluate_at.') n_iter = self.eval_at[-1] + 1 self._running.set() if bg: self._t = threading.Thread(target=lambda: self._run(n_iter)) self._t.start() else: self._run(n_iter)
[ "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
32,451
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 self.log.eval_at = eval_at if mode is None: if self.context_mode is None or (self.context_mode.has_key('choose_m') and self.context_mode['choose_m']): mode = 'inverse' else: mode = self.context_mode["mode"] self.evaluation = Evaluation(self.ag, self.env, testcases, mode=mode) for test in testcases: self.log.add('testcases', test)
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 self.log.eval_at = eval_at if mode is None: if self.context_mode is None or (self.context_mode.has_key('choose_m') and self.context_mode['choose_m']): mode = 'inverse' else: mode = self.context_mode["mode"] self.evaluation = Evaluation(self.ag, self.env, testcases, mode=mode) for test in testcases: self.log.add('testcases', test)
[ "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
32,452
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() for t in range(timesteps): self.x_track[t] = self.x self.step(**kwargs) return self.x_track
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() for t in range(timesteps): self.x_track[t] = self.x self.step(**kwargs) return self.x_track
[ "def", "rollout", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "has_key", "(", "'tau'", ")", ":", "timesteps", "=", "int", "(", "self", ".", "timesteps", "/", "kwargs", "[", "'tau'", "]", ")", "else", ":", "timesteps", "=", ...
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
32,453
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
32,454
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.from_forward(fm, constraints = constraints, **kwargs) return im
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.from_forward(fm, constraints = constraints, **kwargs) return im
[ "def", "from_dataset", "(", "cls", ",", "dataset", ",", "constraints", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "fm", "=", "LWLRForwardModel", "(", "dataset", ".", "dim_x", ",", "dataset", ".", "dim_y", ",", "*", "*", "kwargs", ")", "fm", ...
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
32,455
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
32,456
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
32,457
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 = sum(e*e for e in err_v) return 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 = sum(e*e for e in err_v) return 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
32,458
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 (shape (n, d)) if n is given as number parameter. """ if number is None: return numpy.random.multivariate_normal(self.mu, self.sigma) else: return numpy.random.multivariate_normal(self.mu, self.sigma, number)
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 (shape (n, d)) if n is given as number parameter. """ if number is None: return numpy.random.multivariate_normal(self.mu, self.sigma) else: return numpy.random.multivariate_normal(self.mu, self.sigma, number)
[ "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 parameter.
[ "Generates", "vectors", "from", "the", "Gaussian", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/gaussian.py#L31-L43
train
32,459
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: exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(self.inv, xc))) else: exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(xc, self.inv)), axis=1) return -.5 * (d * numpy.log(2 * numpy.pi) + numpy.log(self.det) + exp_term)
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: exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(self.inv, xc))) else: exp_term = numpy.sum(numpy.multiply(xc, numpy.dot(xc, self.inv)), axis=1) return -.5 * (d * numpy.log(2 * numpy.pi) + numpy.log(self.det) + exp_term)
[ "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
32,460
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 position where the conditional probability is taken. v shape is defined by the size of the set of dims. """ (d, c, b, a) = numpy.split_matrix(self.sigma, dims) (mu2, mu1) = numpy.split_vector(self.mu, dims) d_inv = numpy.linalg.inv(d) mu = mu1 + numpy.dot(numpy.dot(b, d_inv), v - mu2) sigma = a - numpy.dot(b, numpy.dot(d_inv, c)) return Gaussian(mu, sigma)
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 position where the conditional probability is taken. v shape is defined by the size of the set of dims. """ (d, c, b, a) = numpy.split_matrix(self.sigma, dims) (mu2, mu1) = numpy.split_vector(self.mu, dims) d_inv = numpy.linalg.inv(d) mu = mu1 + numpy.dot(numpy.dot(b, d_inv), v - mu2) sigma = a - numpy.dot(b, numpy.dot(d_inv, c)) return Gaussian(mu, sigma)
[ "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 taken. v shape is defined by the size of the set of dims.
[ "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
32,461
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:: from explauto.environment import environments print environments.keys() This will return the available environment names, something like:: '['npendulum', 'pendulum', 'simple_arm']' Once you have choose an environment, e.g. 'simple_arm', corresponding available configurations are available using:: env_cls, env_configs, _ = environments['simple_arm'] print env_configs.keys() This will return the available configuration names for the 'simple_arm' environment, something like:: '['mid_dimensional', 'default', 'high_dim_high_s_range', 'low_dimensional', 'high_dimensional']' Once you have choose a configuration, for example the 'mid_dimensional' one, you can contruct the environment using:: from explauto import Environment my_environment = Environment.from_configuration('simple_arm', 'mid_dimensional') Or, in an equivalent manner:: my_environment = env_cls(**env_configs['mid_dimensional']) """ env_cls, env_configs, _ = environments[env_name] return env_cls(**env_configs[config_name])
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:: from explauto.environment import environments print environments.keys() This will return the available environment names, something like:: '['npendulum', 'pendulum', 'simple_arm']' Once you have choose an environment, e.g. 'simple_arm', corresponding available configurations are available using:: env_cls, env_configs, _ = environments['simple_arm'] print env_configs.keys() This will return the available configuration names for the 'simple_arm' environment, something like:: '['mid_dimensional', 'default', 'high_dim_high_s_range', 'low_dimensional', 'high_dimensional']' Once you have choose a configuration, for example the 'mid_dimensional' one, you can contruct the environment using:: from explauto import Environment my_environment = Environment.from_configuration('simple_arm', 'mid_dimensional') Or, in an equivalent manner:: my_environment = env_cls(**env_configs['mid_dimensional']) """ env_cls, env_configs, _ = environments[env_name] return env_cls(**env_configs[config_name])
[ "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 print environments.keys() This will return the available environment names, something like:: '['npendulum', 'pendulum', 'simple_arm']' Once you have choose an environment, e.g. 'simple_arm', corresponding available configurations are available using:: env_cls, env_configs, _ = environments['simple_arm'] print env_configs.keys() This will return the available configuration names for the 'simple_arm' environment, something like:: '['mid_dimensional', 'default', 'high_dim_high_s_range', 'low_dimensional', 'high_dimensional']' Once you have choose a configuration, for example the 'mid_dimensional' one, you can contruct the environment using:: from explauto import Environment my_environment = Environment.from_configuration('simple_arm', 'mid_dimensional') Or, in an equivalent manner:: my_environment = env_cls(**env_configs['mid_dimensional'])
[ "Environment", "factory", "from", "name", "and", "configuration", "strings", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/environment.py#L31-L66
train
32,462
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 logging purpose (default: True). :returns: an array of shape (self.conf.ndims, ) or (n, self.conf.ndims) according to the shape of the m_ag parameter, containing the motor values (which can be different from m_ag, e.g. bounded according to self.conf.m_bounds) and the corresponding sensory values. .. note:: self.conf.ndims = self.conf.m_ndims + self.conf.s_ndims is the dimensionality of the sensorimotor space (dim of the motor space + dim of the sensory space). """ if reset: self.reset() if len(array(m_ag).shape) == 1: s = self.one_update(m_ag, log) else: s = [] for m in m_ag: s.append(self.one_update(m, log)) s = array(s) return s
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 logging purpose (default: True). :returns: an array of shape (self.conf.ndims, ) or (n, self.conf.ndims) according to the shape of the m_ag parameter, containing the motor values (which can be different from m_ag, e.g. bounded according to self.conf.m_bounds) and the corresponding sensory values. .. note:: self.conf.ndims = self.conf.m_ndims + self.conf.s_ndims is the dimensionality of the sensorimotor space (dim of the motor space + dim of the sensory space). """ if reset: self.reset() if len(array(m_ag).shape) == 1: s = self.one_update(m_ag, log) else: s = [] for m in m_ag: s.append(self.one_update(m, log)) s = array(s) return s
[ "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 shape (self.conf.ndims, ) or (n, self.conf.ndims) according to the shape of the m_ag parameter, containing the motor values (which can be different from m_ag, e.g. bounded according to self.conf.m_bounds) and the corresponding sensory values. .. note:: self.conf.ndims = self.conf.m_ndims + self.conf.s_ndims is the dimensionality of the sensorimotor space (dim of the motor space + dim of the sensory space).
[ "Computes", "sensorimotor", "values", "from", "motor", "orders", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/environment/environment.py#L78-L99
train
32,463
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", "# KDTree", "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
32,464
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
32,465
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: assert len(x) == dim_x and len(y) == dim_y dataset.add_xy(x, y) return dataset
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: assert len(x) == dim_x and len(y) == dim_y dataset.add_xy(x, y) return dataset
[ "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
32,466
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]) dataset = cls(dim_x, dim_y) for x, y in zip(x_array, y_array): assert len(x) == dim_x and len(y) == dim_y dataset.add_xy(x, y) return dataset
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]) dataset = cls(dim_x, dim_y) for x, y in zip(x_array, y_array): assert len(x) == dim_x and len(y) == dim_y dataset.add_xy(x, y) return dataset
[ "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
32,467
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) # Because linear models requires x vector to be extended to [1.0]+x # to accomodate a constant, we store them that way. return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)
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) # Because linear models requires x vector to be extended to [1.0]+x # to accomodate a constant, we store them that way. return self._nn(DATA_X, x, k=k_x, radius=radius, eps=eps, p=p)
[ "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
32,468
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 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 exploration is driven in the interest model :param list inf_dims: the output sensorimotor dimensions of the sensorimotor model (input being expl_dims) :param class sm_model_cls: a subclass of SensorimotorModel, as those registered in the sensorimotor_model package :param dict sensorimotor_model_config: a configuration dict as those registered in the sensorimotor_model package :param list m_mins, m_maxs, s_mins, s_max: lower and upper bounds of motor and sensory values on each dimension """ conf = make_configuration(m_mins, m_maxs, s_mins, s_maxs) sm_model = sm_model_cls(conf, **sm_model_config) im_model = im_model_cls(conf, expl_dims, **im_model_config) return cls(conf, sm_model, im_model, n_bootstrap, context_mode)
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 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 exploration is driven in the interest model :param list inf_dims: the output sensorimotor dimensions of the sensorimotor model (input being expl_dims) :param class sm_model_cls: a subclass of SensorimotorModel, as those registered in the sensorimotor_model package :param dict sensorimotor_model_config: a configuration dict as those registered in the sensorimotor_model package :param list m_mins, m_maxs, s_mins, s_max: lower and upper bounds of motor and sensory values on each dimension """ conf = make_configuration(m_mins, m_maxs, s_mins, s_maxs) sm_model = sm_model_cls(conf, **sm_model_config) im_model = im_model_cls(conf, expl_dims, **im_model_config) return cls(conf, sm_model, im_model, n_bootstrap, context_mode)
[ "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 exploration is driven in the interest model :param list inf_dims: the output sensorimotor dimensions of the sensorimotor model (input being expl_dims) :param class sm_model_cls: a subclass of SensorimotorModel, as those registered in the sensorimotor_model package :param dict sensorimotor_model_config: a configuration dict as those registered in the sensorimotor_model package :param list m_mins, m_maxs, s_mins, s_max: lower and upper bounds of motor and sensory values on each dimension
[ "Initialize", "agent", "class" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/agent/agent.py#L31-L59
train
32,469
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_dims == self.conf.s_dims: x = np.hstack((context_ms[self.conf.m_ndims//2:], self.interest_model.sample_given_context(context_ms[self.conf.m_ndims//2:], range(self.conf.s_ndims//2)))) else: if self.context_mode['choose_m']: x = self.interest_model.sample() else: x = np.hstack((context_ms[:self.conf.m_ndims//2], self.interest_model.sample_given_context(context_ms[:self.conf.m_ndims//2], range(self.conf.m_ndims//2)))) elif self.context_mode["mode"] == 'mcs': x = np.hstack((context_ms, self.interest_model.sample_given_context(context_ms, range(self.context_mode["context_n_dims"])))) except ExplautoBootstrapError: logger.warning('Interest model not bootstrapped yet') x = rand_bounds(self.conf.bounds[:, self.expl_dims]).flatten() if self.context_mode is not None: x = x[list(set(self.expl_dims) - set(self.context_mode['context_dims']))] return x
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_dims == self.conf.s_dims: x = np.hstack((context_ms[self.conf.m_ndims//2:], self.interest_model.sample_given_context(context_ms[self.conf.m_ndims//2:], range(self.conf.s_ndims//2)))) else: if self.context_mode['choose_m']: x = self.interest_model.sample() else: x = np.hstack((context_ms[:self.conf.m_ndims//2], self.interest_model.sample_given_context(context_ms[:self.conf.m_ndims//2], range(self.conf.m_ndims//2)))) elif self.context_mode["mode"] == 'mcs': x = np.hstack((context_ms, self.interest_model.sample_given_context(context_ms, range(self.context_mode["context_n_dims"])))) except ExplautoBootstrapError: logger.warning('Interest model not bootstrapped yet') x = rand_bounds(self.conf.bounds[:, self.expl_dims]).flatten() if self.context_mode is not None: x = x[list(set(self.expl_dims) - set(self.context_mode['context_dims']))] return x
[ "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
32,470
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.conf.s_dims and inf_dims=self.conf.m_dims. """ try: if self.n_bootstrap > 0: self.n_bootstrap -= 1 raise ExplautoBootstrapError y = self.sensorimotor_model.infer(expl_dims, inf_dims, x.flatten()) except ExplautoBootstrapError: logger.warning('Sensorimotor model not bootstrapped yet') y = rand_bounds(self.conf.bounds[:, inf_dims]).flatten() return y
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.conf.s_dims and inf_dims=self.conf.m_dims. """ try: if self.n_bootstrap > 0: self.n_bootstrap -= 1 raise ExplautoBootstrapError y = self.sensorimotor_model.infer(expl_dims, inf_dims, x.flatten()) except ExplautoBootstrapError: logger.warning('Sensorimotor model not bootstrapped yet') y = rand_bounds(self.conf.bounds[:, inf_dims]).flatten() return y
[ "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
32,471
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
32,472
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 # Without having a tracker if self.tracker is not None: return self.tracker.get_object_position(self.tracked_obj)
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 # Without having a tracker if self.tracker is not None: return self.tracker.get_object_position(self.tracked_obj)
[ "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
32,473
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 = self.imodel.infer_x(np.array(self._pre_y(goal)), **kwargs)[0] return self._post_x(x, goal)
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 = self.imodel.infer_x(np.array(self._pre_y(goal)), **kwargs)[0] return self._post_x(x, goal)
[ "def", "infer_order", "(", "self", ",", "goal", ",", "*", "*", "kwargs", ")", ":", "x", "=", "self", ".", "imodel", ".", "infer_x", "(", "np", ".", "array", "(", "self", ".", "_pre_y", "(", "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)
[ "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
32,474
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) return self._post_y(y, order)
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) return self._post_y(y, order)
[ "def", "predict_effect", "(", "self", ",", "order", ",", "*", "*", "kwargs", ")", ":", "y", "=", "self", ".", "imodel", ".", "fmodel", ".", "predict_y", "(", "np", ".", "array", "(", "self", ".", "_pre_x", "(", "order", ")", ")", ",", "*", "*", ...
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
32,475
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_enforced.append(lb) else: x_enforced.append(x_i) elif x_i > ub: if x_i < ub + (ub-lb)/1e10: x_enforced.append(ub) else: x_enforced.append(x_i) else: x_enforced.append(x_i) return np.array(x_enforced)
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_enforced.append(lb) else: x_enforced.append(x_i) elif x_i > ub: if x_i < ub + (ub-lb)/1e10: x_enforced.append(ub) else: x_enforced.append(x_i) else: x_enforced.append(x_i) return np.array(x_enforced)
[ "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
32,476
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 '.fit' might be modified inplace - if this is a problem you'll need to pass a copy to them, e.g. 'counts_df=counts_df.copy()'. Note ---- Forcibly terminating the procedure should still keep the last calculated shape and rate parameter values, but is not recommended. If you need to make predictions on a forced-terminated object, set the attribute 'is_fitted' to 'True'. Note ---- Fitting in mini-batches is more prone to numerical instability and compared to full-batch variational inference, it is more likely that all your parameters will turn to NaNs (which means the optimization procedure failed). Parameters ---------- counts_df : pandas data frame (nobs, 3) or coo_matrix Input data with one row per non-zero observation, consisting of triplets ('UserId', 'ItemId', 'Count'). Must containin columns 'UserId', 'ItemId', and 'Count'. Combinations of users and items not present are implicitly assumed to be zero by the model. Can also pass a sparse coo_matrix, in which case 'reindex' will be forced to 'False'. val_set : pandas data frame (nobs, 3) Validation set on which to monitor log-likelihood. Same format as counts_df. Returns ------- self : obj Copy of this object """ ## a basic check if self.stop_crit == 'val-llk': if val_set is None: raise ValueError("If 'stop_crit' is set to 'val-llk', must provide a validation set.") ## running each sub-process if self.verbose: self._print_st_msg() self._process_data(counts_df) if self.verbose: self._print_data_info() if (val_set is not None) and (self.stop_crit!='diff-norm') and (self.stop_crit!='train-llk'): self._process_valset(val_set) else: self.val_set = None self._cast_before_fit() self._fit() ## after terminating optimization if self.keep_data: if self.users_per_batch == 0: self._store_metadata() else: self._st_ix_user = self._st_ix_user[:-1] if self.produce_dicts and self.reindex: self.user_dict_ = {self.user_mapping_[i]:i for i in range(self.user_mapping_.shape[0])} self.item_dict_ = {self.item_mapping_[i]:i for i in range(self.item_mapping_.shape[0])} self.is_fitted = True del self.input_df del self.val_set return self
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 '.fit' might be modified inplace - if this is a problem you'll need to pass a copy to them, e.g. 'counts_df=counts_df.copy()'. Note ---- Forcibly terminating the procedure should still keep the last calculated shape and rate parameter values, but is not recommended. If you need to make predictions on a forced-terminated object, set the attribute 'is_fitted' to 'True'. Note ---- Fitting in mini-batches is more prone to numerical instability and compared to full-batch variational inference, it is more likely that all your parameters will turn to NaNs (which means the optimization procedure failed). Parameters ---------- counts_df : pandas data frame (nobs, 3) or coo_matrix Input data with one row per non-zero observation, consisting of triplets ('UserId', 'ItemId', 'Count'). Must containin columns 'UserId', 'ItemId', and 'Count'. Combinations of users and items not present are implicitly assumed to be zero by the model. Can also pass a sparse coo_matrix, in which case 'reindex' will be forced to 'False'. val_set : pandas data frame (nobs, 3) Validation set on which to monitor log-likelihood. Same format as counts_df. Returns ------- self : obj Copy of this object """ ## a basic check if self.stop_crit == 'val-llk': if val_set is None: raise ValueError("If 'stop_crit' is set to 'val-llk', must provide a validation set.") ## running each sub-process if self.verbose: self._print_st_msg() self._process_data(counts_df) if self.verbose: self._print_data_info() if (val_set is not None) and (self.stop_crit!='diff-norm') and (self.stop_crit!='train-llk'): self._process_valset(val_set) else: self.val_set = None self._cast_before_fit() self._fit() ## after terminating optimization if self.keep_data: if self.users_per_batch == 0: self._store_metadata() else: self._st_ix_user = self._st_ix_user[:-1] if self.produce_dicts and self.reindex: self.user_dict_ = {self.user_mapping_[i]:i for i in range(self.user_mapping_.shape[0])} self.item_dict_ = {self.item_mapping_[i]:i for i in range(self.item_mapping_.shape[0])} self.is_fitted = True del self.input_df del self.val_set return self
[ "def", "fit", "(", "self", ",", "counts_df", ",", "val_set", "=", "None", ")", ":", "## a basic check", "if", "self", ".", "stop_crit", "==", "'val-llk'", ":", "if", "val_set", "is", "None", ":", "raise", "ValueError", "(", "\"If 'stop_crit' is set to 'val-llk...
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 problem you'll need to pass a copy to them, e.g. 'counts_df=counts_df.copy()'. Note ---- Forcibly terminating the procedure should still keep the last calculated shape and rate parameter values, but is not recommended. If you need to make predictions on a forced-terminated object, set the attribute 'is_fitted' to 'True'. Note ---- Fitting in mini-batches is more prone to numerical instability and compared to full-batch variational inference, it is more likely that all your parameters will turn to NaNs (which means the optimization procedure failed). Parameters ---------- counts_df : pandas data frame (nobs, 3) or coo_matrix Input data with one row per non-zero observation, consisting of triplets ('UserId', 'ItemId', 'Count'). Must containin columns 'UserId', 'ItemId', and 'Count'. Combinations of users and items not present are implicitly assumed to be zero by the model. Can also pass a sparse coo_matrix, in which case 'reindex' will be forced to 'False'. val_set : pandas data frame (nobs, 3) Validation set on which to monitor log-likelihood. Same format as counts_df. Returns ------- self : obj Copy of this object
[ "Fit", "Hierarchical", "Poisson", "Model", "to", "sparse", "count", "data" ]
cf0b18aa03e189f822b582d59c23f7862593289e
https://github.com/david-cortes/hpfrec/blob/cf0b18aa03e189f822b582d59c23f7862593289e/hpfrec/__init__.py#L344-L416
train
32,477
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 ---- This function only works with one user at a time. Note ---- This function is prone to producing all NaNs values. Parameters ---------- counts_df : DataFrame or array (nsamples, 2) Data Frame with columns 'ItemId' and 'Count', indicating the non-zero item counts for a user for whom it's desired to obtain latent factors. maxiter : int Maximum number of iterations to run. ncores : int Number of threads/cores to use. With data for only one user, it's unlikely that using multiple threads would give a significant speed-up, and it might even end up making the function slower due to the overhead. If passing -1, it will determine the maximum number of cores in the system and use that. random_seed : int Random seed used to initialize parameters. stop_thr : float If the l2-norm of the difference between values of Theta_{u} between interations is less than this, it will stop. Smaller values of 'k' should require smaller thresholds. return_all : bool Whether to return also the intermediate calculations (Gamma_shp, Gamma_rte). When passing True here, the output will be a tuple containing (Theta, Gamma_shp, Gamma_rte, Phi) Returns ------- latent_factors : array (k,) Calculated latent factors for the user, given the input data """ ncores, random_seed, stop_thr, maxiter = self._check_input_predict_factors(ncores, random_seed, stop_thr, maxiter) ## processing the data counts_df = self._process_data_single(counts_df) ## calculating the latent factors Theta = np.empty(self.k, dtype='float32') temp = cython_loops.calc_user_factors( self.a, self.a_prime, self.b_prime, self.c, self.c_prime, self.d_prime, counts_df.Count.values, counts_df.ItemId.values, Theta, self.Beta, self.Lambda_shp, self.Lambda_rte, cython_loops.cast_ind_type(counts_df.shape[0]), cython_loops.cast_ind_type(self.k), cython_loops.cast_int(int(maxiter)), cython_loops.cast_int(ncores), cython_loops.cast_int(int(random_seed)), cython_loops.cast_float(stop_thr), cython_loops.cast_int(bool(return_all)) ) if np.isnan(Theta).sum() > 0: raise ValueError("NaNs encountered in the result. Failed to produce latent factors.") if return_all: return (Theta, temp[0], temp[1], temp[2]) else: return Theta
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 ---- This function only works with one user at a time. Note ---- This function is prone to producing all NaNs values. Parameters ---------- counts_df : DataFrame or array (nsamples, 2) Data Frame with columns 'ItemId' and 'Count', indicating the non-zero item counts for a user for whom it's desired to obtain latent factors. maxiter : int Maximum number of iterations to run. ncores : int Number of threads/cores to use. With data for only one user, it's unlikely that using multiple threads would give a significant speed-up, and it might even end up making the function slower due to the overhead. If passing -1, it will determine the maximum number of cores in the system and use that. random_seed : int Random seed used to initialize parameters. stop_thr : float If the l2-norm of the difference between values of Theta_{u} between interations is less than this, it will stop. Smaller values of 'k' should require smaller thresholds. return_all : bool Whether to return also the intermediate calculations (Gamma_shp, Gamma_rte). When passing True here, the output will be a tuple containing (Theta, Gamma_shp, Gamma_rte, Phi) Returns ------- latent_factors : array (k,) Calculated latent factors for the user, given the input data """ ncores, random_seed, stop_thr, maxiter = self._check_input_predict_factors(ncores, random_seed, stop_thr, maxiter) ## processing the data counts_df = self._process_data_single(counts_df) ## calculating the latent factors Theta = np.empty(self.k, dtype='float32') temp = cython_loops.calc_user_factors( self.a, self.a_prime, self.b_prime, self.c, self.c_prime, self.d_prime, counts_df.Count.values, counts_df.ItemId.values, Theta, self.Beta, self.Lambda_shp, self.Lambda_rte, cython_loops.cast_ind_type(counts_df.shape[0]), cython_loops.cast_ind_type(self.k), cython_loops.cast_int(int(maxiter)), cython_loops.cast_int(ncores), cython_loops.cast_int(int(random_seed)), cython_loops.cast_float(stop_thr), cython_loops.cast_int(bool(return_all)) ) if np.isnan(Theta).sum() > 0: raise ValueError("NaNs encountered in the result. Failed to produce latent factors.") if return_all: return (Theta, temp[0], temp[1], temp[2]) else: return Theta
[ "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 values. Parameters ---------- counts_df : DataFrame or array (nsamples, 2) Data Frame with columns 'ItemId' and 'Count', indicating the non-zero item counts for a user for whom it's desired to obtain latent factors. maxiter : int Maximum number of iterations to run. ncores : int Number of threads/cores to use. With data for only one user, it's unlikely that using multiple threads would give a significant speed-up, and it might even end up making the function slower due to the overhead. If passing -1, it will determine the maximum number of cores in the system and use that. random_seed : int Random seed used to initialize parameters. stop_thr : float If the l2-norm of the difference between values of Theta_{u} between interations is less than this, it will stop. Smaller values of 'k' should require smaller thresholds. return_all : bool Whether to return also the intermediate calculations (Gamma_shp, Gamma_rte). When passing True here, the output will be a tuple containing (Theta, Gamma_shp, Gamma_rte, Phi) Returns ------- latent_factors : array (k,) Calculated latent factors for the user, given the input data
[ "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
32,478
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 = k, sigma = sigma, **kwargs)[0] dists, index = self.fmodel.dataset.nn_x(xq, k = k) w = self.fmodel._weights(dists, sigma*sigma) X = np.array([self.fmodel.dataset.get_x_padded(i) for i in index]) Y = np.array([self.fmodel.dataset.get_y(i) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) M = np.dot(B, np.dot(W, Y)) _, idx = self.fmodel.dataset.nn_y(y_desired, k=1) ynn = self.fmodel.dataset.get_y(idx[0]) eps = 0.00001 J = np.zeros((len(xq),len(y_desired)), dtype = np.float64) for i in range(len(xq)): xi = np.array(xq, dtype = np.float64) xi[i] = xi[i] + eps yi = np.dot(np.append(1.0, xi), M).ravel() J[i] = (yi - ynn) / eps J = np.transpose(J) Jinv = np.linalg.pinv(J) x = np.dot(Jinv, y_desired - ynn) return [x]
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 = k, sigma = sigma, **kwargs)[0] dists, index = self.fmodel.dataset.nn_x(xq, k = k) w = self.fmodel._weights(dists, sigma*sigma) X = np.array([self.fmodel.dataset.get_x_padded(i) for i in index]) Y = np.array([self.fmodel.dataset.get_y(i) for i in index]) W = np.diag(w) WX = np.dot(W, X) WXT = WX.T B = np.dot(np.linalg.pinv(np.dot(WXT, WX)),WXT) M = np.dot(B, np.dot(W, Y)) _, idx = self.fmodel.dataset.nn_y(y_desired, k=1) ynn = self.fmodel.dataset.get_y(idx[0]) eps = 0.00001 J = np.zeros((len(xq),len(y_desired)), dtype = np.float64) for i in range(len(xq)): xi = np.array(xq, dtype = np.float64) xi[i] = xi[i] + eps yi = np.dot(np.append(1.0, xi), M).ravel() J[i] = (yi - ynn) / eps J = np.transpose(J) Jinv = np.linalg.pinv(J) x = np.dot(Jinv, y_desired - ynn) return [x]
[ "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
32,479
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. :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 bablings: list of babbling modes :param interest_models: e.g. [('random', 'default')] :type interest_models: list of (interest model name, config name) :param sensorimotor_models: e.g. [('non_parametric', 'default')] :type sensorimotor_models: list of (sensorimotor model name, config name) :param evaluate_at: indices defining when to evaluate :type evaluate_at: list of int :param bool same_testcases: whether to use the same testcases for all experiments """ l = itertools.product(environments, babblings, interest_models, sensorimotor_models) settings = [make_settings(env, bab, im, sm, env_conf, im_conf, sm_conf) for ((env, env_conf), bab, (im, im_conf), (sm, sm_conf)) in l] return cls(settings, evaluate_at, testcases, same_testcases)
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. :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 bablings: list of babbling modes :param interest_models: e.g. [('random', 'default')] :type interest_models: list of (interest model name, config name) :param sensorimotor_models: e.g. [('non_parametric', 'default')] :type sensorimotor_models: list of (sensorimotor model name, config name) :param evaluate_at: indices defining when to evaluate :type evaluate_at: list of int :param bool same_testcases: whether to use the same testcases for all experiments """ l = itertools.product(environments, babblings, interest_models, sensorimotor_models) settings = [make_settings(env, bab, im, sm, env_conf, im_conf, sm_conf) for ((env, env_conf), bab, (im, im_conf), (sm, sm_conf)) in l] return cls(settings, evaluate_at, testcases, same_testcases)
[ "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 bablings: list of babbling modes :param interest_models: e.g. [('random', 'default')] :type interest_models: list of (interest model name, config name) :param sensorimotor_models: e.g. [('non_parametric', 'default')] :type sensorimotor_models: list of (sensorimotor model name, config name) :param evaluate_at: indices defining when to evaluate :type evaluate_at: list of int :param bool same_testcases: whether to use the same testcases for all experiments
[ "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
32,480
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.use_basis_functions: func = simulation.step(m, 1000*self.dt) else: traj = self.bf.trajectory(m).flatten() func = lambda t: traj[int(1000*self.dt * t)] states = simulation.simulate(self.n, self.x0, self.dt, func) last_state_cartesian = simulation.cartesian(self.n, states[-1]) end_effector_pos = array([last_state_cartesian[self.n], last_state_cartesian[2*self.n]]) end_effector_pos += self.noise * random.randn(len(end_effector_pos)) return end_effector_pos
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.use_basis_functions: func = simulation.step(m, 1000*self.dt) else: traj = self.bf.trajectory(m).flatten() func = lambda t: traj[int(1000*self.dt * t)] states = simulation.simulate(self.n, self.x0, self.dt, func) last_state_cartesian = simulation.cartesian(self.n, states[-1]) end_effector_pos = array([last_state_cartesian[self.n], last_state_cartesian[2*self.n]]) end_effector_pos += self.noise * random.randn(len(end_effector_pos)) return end_effector_pos
[ "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
32,481
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) os.makedirs(path) for t in range(0, 1000, 32): ax = axes() self.plot_npendulum(ax, m, t) savefig(os.path.join(path, "{}.png".format(t))) clf()
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) os.makedirs(path) for t in range(0, 1000, 32): ax = axes() self.plot_npendulum(ax, m, t) savefig(os.path.join(path, "{}.png".format(t))) clf()
[ "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
32,482
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.append(list(map(float, line.split()))) res = lres while res != [] and res[0] == []: # remove further leading empty lines del res[0] return res # except: print('could not read file ' + file_name)
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.append(list(map(float, line.split()))) res = lres while res != [] and res[0] == []: # remove further leading empty lines del res[0] return res # except: print('could not read file ' + file_name)
[ "def", "_fileToMatrix", "(", "file_name", ")", ":", "# TODO: np.loadtxt() might be an alternative", "# try:", "if", "1", "<", "3", ":", "lres", "=", "[", "]", "for", "line", "in", "open", "(", "file_name", ",", "'r'", ")", ".", "readlines", "(", ")", "...
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
32,483
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('{') for k, v in to_be_printed.items(): print("'" + k + "'" if isinstance(k, basestring) else k, ': ', "'" + v + "'" if isinstance(k, basestring) else v, sep="") print('}') else: print('could not import pprint module, appling regular print') print(to_be_printed)
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('{') for k, v in to_be_printed.items(): print("'" + k + "'" if isinstance(k, basestring) else k, ': ', "'" + v + "'" if isinstance(k, basestring) else v, sep="") print('}') else: print('could not import pprint module, appling regular print') print(to_be_printed)
[ "def", "pprint", "(", "to_be_printed", ")", ":", "try", ":", "import", "pprint", "as", "pp", "# generate an instance PrettyPrinter", "# pp.PrettyPrinter().pprint(to_be_printed)", "pp", ".", "pprint", "(", "to_be_printed", ")", "except", "ImportError", ":", "if", "isin...
nicely formated print
[ "nicely", "formated", "print" ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7863-L7881
train
32,484
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
32,485
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 the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
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 the better solution becomes the current best. `xarchive` is used to retrieve the genotype of a solution. """ if isinstance(arx, BestSolution): if self.evalsall is None: self.evalsall = arx.evalsall elif arx.evalsall is not None: self.evalsall = max((self.evalsall, arx.evalsall)) if arx.f is not None and arx.f < np.inf: self.update([arx.x], xarchive, [arx.f], arx.evals) return self assert arf is not None # find failsave minimum minidx = np.nanargmin(arf) if minidx is np.nan: return minarf = arf[minidx] # minarf = reduce(lambda x, y: y if y and y is not np.nan # and y < x else x, arf, np.inf) if minarf < np.inf and (minarf < self.f or self.f is None): self.x, self.f = arx[minidx], arf[minidx] if xarchive is not None and xarchive.get(self.x) is not None: self.x_geno = xarchive[self.x].get('geno') else: self.x_geno = None self.evals = None if not evals else evals - len(arf) + minidx + 1 self.evalsall = evals elif evals: self.evalsall = evals self.last.x = arx[minidx] self.last.f = minarf
[ "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 used to retrieve the genotype of a solution.
[ "checks", "for", "better", "solutions", "in", "list", "arx", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L813-L851
train
32,486
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.bounds is None: return x 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.bounds[ib][idx] is not None and \ (-1)**ib * x[i] < (-1)**ib * self.bounds[ib][idx]: if copy: x = array(x, copy=True) copy = False x[i] = self.bounds[ib][idx]
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.bounds is None: return x 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.bounds[ib][idx] is not None and \ (-1)**ib * x[i] < (-1)**ib * self.bounds[ib][idx]: if copy: x = array(x, copy=True) copy = False x[i] = self.bounds[ib][idx]
[ "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
32,487
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 bound: if bound_i is not None and sign_ * bound_i < np.inf: return True return False
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 bound: if bound_i is not None and sign_ * bound_i < np.inf: return True return False
[ "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
32,488
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.bounds[ib][idx] is not None and \ (-1)**ib * x[i] < (-1)**ib * self.bounds[ib][idx]: return False return True
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.bounds[ib][idx] is not None and \ (-1)**ib * x[i] < (-1)**ib * self.bounds[ib][idx]: return False return True
[ "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
32,489
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 None or (self.bounds[0] is None and self.bounds[1] is None): return x return self.bounds_tf(x, copy)
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 None or (self.bounds[0] is None and self.bounds[1] is None): return x return self.bounds_tf(x, copy)
[ "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
32,490
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 max((bounds[0], x)) copy = copy_if_changed if copy_always: x = array(x, copy=True) bounds = self.bounds if bounds not in (None, [None, None], (None, None)): # solely for effiency x = array(x, copy=True) if copy and not copy_always else x if bounds[0] is not None: if isscalar(bounds[0]): for i in rglen(x): x[i] = max((bounds[0], x[i])) else: for i in rglen(x): j = min([i, len(bounds[0]) - 1]) if bounds[0][j] is not None: x[i] = max((bounds[0][j], x[i])) if bounds[1] is not None: if isscalar(bounds[1]): for i in rglen(x): x[i] = min((bounds[1], x[i])) else: for i in rglen(x): j = min((i, len(bounds[1]) - 1)) if bounds[1][j] is not None: x[i] = min((bounds[1][j], x[i])) return x
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 max((bounds[0], x)) copy = copy_if_changed if copy_always: x = array(x, copy=True) bounds = self.bounds if bounds not in (None, [None, None], (None, None)): # solely for effiency x = array(x, copy=True) if copy and not copy_always else x if bounds[0] is not None: if isscalar(bounds[0]): for i in rglen(x): x[i] = max((bounds[0], x[i])) else: for i in rglen(x): j = min([i, len(bounds[0]) - 1]) if bounds[0][j] is not None: x[i] = max((bounds[0][j], x[i])) if bounds[1] is not None: if isscalar(bounds[1]): for i in rglen(x): x[i] = min((bounds[1], x[i])) else: for i in rglen(x): j = min((i, len(bounds[1]) - 1)) if bounds[1][j] is not None: x[i] = min((bounds[1][j], x[i])) return x
[ "def", "repair", "(", "self", ",", "x", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ")", ":", "# 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 slowe...
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
32,491
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 mean and variances and the methods from the attribute `gp` of type `GenoPheno` are used. """ if self.bounds is None or (self.bounds[0] is None and self.bounds[1] is None): return self N = es.N # ## prepare # compute varis = sigma**2 * C_ii varis = es.sigma**2 * array(N * [es.C] if isscalar(es.C) else (# scalar case es.C if isscalar(es.C[0]) else # diagonal matrix case [es.C[i][i] for i in xrange(N)])) # full matrix case # relative violation in geno-space dmean = (es.mean - es.gp.geno(self.repair(es.gp.pheno(es.mean)))) / varis**0.5 # ## Store/update a history of delta fitness value fvals = sorted(function_values) l = 1 + len(fvals) val = fvals[3 * l // 4] - fvals[l // 4] # exact interquartile range apart interpolation val = val / np.mean(varis) # new: val is normalized with sigma of the same iteration # insert val in history if isfinite(val) and val > 0: self.hist.insert(0, val) elif val == inf and len(self.hist) > 1: self.hist.insert(0, max(self.hist)) else: pass # ignore 0 or nan values if len(self.hist) > 20 + (3 * N) / es.popsize: self.hist.pop() # ## prepare dfit = np.median(self.hist) # median interquartile range damp = min(1, es.sp.mueff / 10. / N) # ## set/update weights # Throw initialization error if len(self.hist) == 0: raise _Error('wrongful initialization, no feasible solution sampled. ' + 'Reasons can be mistakenly set bounds (lower bound not smaller than upper bound) or a too large initial sigma0 or... ' + 'See description of argument func in help(cma.fmin) or an example handling infeasible solutions in help(cma.CMAEvolutionStrategy). ') # initialize weights if dmean.any() and (not self.weights_initialized or es.countiter == 2): # TODO self.gamma = array(N * [2 * dfit]) ## BUGBUGzzzz: N should be phenotypic (bounds are in phenotype), but is genotypic self.weights_initialized = True # update weights gamma if self.weights_initialized: edist = array(abs(dmean) - 3 * max(1, N**0.5 / es.sp.mueff)) if 1 < 3: # this is better, around a factor of two # increase single weights possibly with a faster rate than they can decrease # value unit of edst is std dev, 3==random walk of 9 steps self.gamma *= exp((edist > 0) * np.tanh(edist / 3) / 2.)**damp # decrease all weights up to the same level to avoid single extremely small weights # use a constant factor for pseudo-keeping invariance self.gamma[self.gamma > 5 * dfit] *= exp(-1. / 3)**damp # self.gamma[idx] *= exp(5*dfit/self.gamma[idx] - 1)**(damp/3) es.more_to_write += list(self.gamma) if self.weights_initialized else N * [1.0] # ## return penalty # es.more_to_write = self.gamma if not isscalar(self.gamma) else N*[1] return self
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 mean and variances and the methods from the attribute `gp` of type `GenoPheno` are used. """ if self.bounds is None or (self.bounds[0] is None and self.bounds[1] is None): return self N = es.N # ## prepare # compute varis = sigma**2 * C_ii varis = es.sigma**2 * array(N * [es.C] if isscalar(es.C) else (# scalar case es.C if isscalar(es.C[0]) else # diagonal matrix case [es.C[i][i] for i in xrange(N)])) # full matrix case # relative violation in geno-space dmean = (es.mean - es.gp.geno(self.repair(es.gp.pheno(es.mean)))) / varis**0.5 # ## Store/update a history of delta fitness value fvals = sorted(function_values) l = 1 + len(fvals) val = fvals[3 * l // 4] - fvals[l // 4] # exact interquartile range apart interpolation val = val / np.mean(varis) # new: val is normalized with sigma of the same iteration # insert val in history if isfinite(val) and val > 0: self.hist.insert(0, val) elif val == inf and len(self.hist) > 1: self.hist.insert(0, max(self.hist)) else: pass # ignore 0 or nan values if len(self.hist) > 20 + (3 * N) / es.popsize: self.hist.pop() # ## prepare dfit = np.median(self.hist) # median interquartile range damp = min(1, es.sp.mueff / 10. / N) # ## set/update weights # Throw initialization error if len(self.hist) == 0: raise _Error('wrongful initialization, no feasible solution sampled. ' + 'Reasons can be mistakenly set bounds (lower bound not smaller than upper bound) or a too large initial sigma0 or... ' + 'See description of argument func in help(cma.fmin) or an example handling infeasible solutions in help(cma.CMAEvolutionStrategy). ') # initialize weights if dmean.any() and (not self.weights_initialized or es.countiter == 2): # TODO self.gamma = array(N * [2 * dfit]) ## BUGBUGzzzz: N should be phenotypic (bounds are in phenotype), but is genotypic self.weights_initialized = True # update weights gamma if self.weights_initialized: edist = array(abs(dmean) - 3 * max(1, N**0.5 / es.sp.mueff)) if 1 < 3: # this is better, around a factor of two # increase single weights possibly with a faster rate than they can decrease # value unit of edst is std dev, 3==random walk of 9 steps self.gamma *= exp((edist > 0) * np.tanh(edist / 3) / 2.)**damp # decrease all weights up to the same level to avoid single extremely small weights # use a constant factor for pseudo-keeping invariance self.gamma[self.gamma > 5 * dfit] *= exp(-1. / 3)**damp # self.gamma[idx] *= exp(5*dfit/self.gamma[idx] - 1)**(damp/3) es.more_to_write += list(self.gamma) if self.weights_initialized else N * [1.0] # ## return penalty # es.more_to_write = self.gamma if not isscalar(self.gamma) else N*[1] return self
[ "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 attribute `gp` of type `GenoPheno` are used.
[ "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
32,492
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", "]", "# can be done more efficiently?", "self", ".", "_ub", "=", "[", "b", "[", "1", "]", "for", "b", "in", "se...
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
32,493
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 + au
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 + au
[ "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
32,494
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: return lb + (x - (lb - al))**2 / 4 / al elif x < ub - au: return x elif x < ub + 3 * au: return ub - (x - (ub + au))**2 / 4 / au else: assert False # shift removes this case return ub + au - (x - (ub + au))
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: return lb + (x - (lb - al))**2 / 4 / al elif x < ub - au: return x elif x < ub + 3 * au: return ub - (x - (ub + au))**2 / 4 / au else: assert False # shift removes this case return ub + au - (x - (ub + au))
[ "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
32,495
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('argument of inverse must be within the given bounds') if y < lb + al: return (lb - al) + 2 * (al * (y - lb))**0.5 elif y < ub - au: return y else: return (ub + au) - 2 * (au * (ub - y))**0.5
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('argument of inverse must be within the given bounds') if y < lb + al: return (lb - al) + 2 * (al * (y - lb))**0.5 elif y < ub - au: return y else: return (ub + au) - 2 * (au * (ub - y))**0.5
[ "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
32,496
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 under the transformation. """ # TODO: copy_always seems superfluous, as it could be done in the calling code input_type = type(x) if into_bounds is None: into_bounds = (lambda x, copy=False: x if not copy else array(x, copy=copy)) if copy_always and not copy: raise ValueError('arguments copy_always=' + str(copy_always) + ' and copy=' + str(copy) + ' have inconsistent values') if copy_always: x = array(x, copy=True) copy = False if self.isidentity: y = into_bounds(x) # was into_bounds(x, False) before (bug before v0.96.22) else: if self.fixed_values is None: y = array(x, copy=copy) # make a copy, in case else: # expand with fixed values y = list(x) # is a copy for i in sorted(self.fixed_values.keys()): y.insert(i, self.fixed_values[i]) y = array(y, copy=False) copy = False if self.scales is not 1: # just for efficiency y *= self.scales if self.typical_x is not 0: y += self.typical_x if self.tf_pheno is not None: y = array(self.tf_pheno(y), copy=False) y = into_bounds(y, copy) # copy is False if self.fixed_values is not None: for i, k in list(self.fixed_values.items()): y[i] = k if input_type is np.ndarray: y = array(y, copy=False) if archive is not None: archive.insert(y, geno=x, iteration=iteration) return y
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 under the transformation. """ # TODO: copy_always seems superfluous, as it could be done in the calling code input_type = type(x) if into_bounds is None: into_bounds = (lambda x, copy=False: x if not copy else array(x, copy=copy)) if copy_always and not copy: raise ValueError('arguments copy_always=' + str(copy_always) + ' and copy=' + str(copy) + ' have inconsistent values') if copy_always: x = array(x, copy=True) copy = False if self.isidentity: y = into_bounds(x) # was into_bounds(x, False) before (bug before v0.96.22) else: if self.fixed_values is None: y = array(x, copy=copy) # make a copy, in case else: # expand with fixed values y = list(x) # is a copy for i in sorted(self.fixed_values.keys()): y.insert(i, self.fixed_values[i]) y = array(y, copy=False) copy = False if self.scales is not 1: # just for efficiency y *= self.scales if self.typical_x is not 0: y += self.typical_x if self.tf_pheno is not None: y = array(self.tf_pheno(y), copy=False) y = into_bounds(y, copy) # copy is False if self.fixed_values is not None: for i, k in list(self.fixed_values.items()): y[i] = k if input_type is np.ndarray: y = array(y, copy=False) if archive is not None: archive.insert(y, geno=x, iteration=iteration) return y
[ "def", "pheno", "(", "self", ",", "x", ",", "into_bounds", "=", "None", ",", "copy", "=", "True", ",", "copy_always", "=", "False", ",", "archive", "=", "None", ",", "iteration", "=", "None", ")", ":", "# TODO: copy_always seems superfluous, as it could be don...
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
32,497
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 modify ``y``. The inverse of the user-defined transformation (if any) is only needed if external solutions are injected, it is not applied to the initial solution x0. Details ======= ``geno`` searches first in ``archive`` for the genotype of ``y`` and returns the found value, typically unrepaired. Otherwise, first ``from_bounds`` is applied, to revert a projection into the bound domain (if necessary) and ``pheno`` is reverted. ``repair`` is applied last, and is usually the method ``CMAEvolutionStrategy.repair_genotype`` that limits the Mahalanobis norm of ``geno(y) - mean``. """ if from_bounds is None: from_bounds = lambda x, copy=False: x # not change, no copy if archive is not None: try: x = archive[y]['geno'] except (KeyError, TypeError): x = None if x is not None: if archive[y]['iteration'] < archive.last_iteration \ and repair is not None: x = repair(x, copy_if_changed=copy_always) return x input_type = type(y) x = y if copy_always: x = array(y, copy=True) copy = False else: copy = copy_if_changed x = from_bounds(x, copy) if self.isidentity: if repair is not None: x = repair(x, copy) return x if copy: # could be improved? x = array(x, copy=True) copy = False # user-defined transformation if self.tf_geno is not None: x = array(self.tf_geno(x), copy=False) elif self.tf_pheno is not None: raise ValueError('t1 of options transformation was not defined but is needed as being the inverse of t0') # affine-linear transformation: shift and scaling if self.typical_x is not 0: x -= self.typical_x if self.scales is not 1: # just for efficiency x /= self.scales # kick out fixed_values if self.fixed_values is not None: # keeping the transformed values does not help much # therefore it is omitted if 1 < 3: keys = sorted(self.fixed_values.keys()) x = array([x[i] for i in xrange(len(x)) if i not in keys], copy=False) # repair injected solutions if repair is not None: x = repair(x, copy) if input_type is np.ndarray: x = array(x, copy=False) return x
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 modify ``y``. The inverse of the user-defined transformation (if any) is only needed if external solutions are injected, it is not applied to the initial solution x0. Details ======= ``geno`` searches first in ``archive`` for the genotype of ``y`` and returns the found value, typically unrepaired. Otherwise, first ``from_bounds`` is applied, to revert a projection into the bound domain (if necessary) and ``pheno`` is reverted. ``repair`` is applied last, and is usually the method ``CMAEvolutionStrategy.repair_genotype`` that limits the Mahalanobis norm of ``geno(y) - mean``. """ if from_bounds is None: from_bounds = lambda x, copy=False: x # not change, no copy if archive is not None: try: x = archive[y]['geno'] except (KeyError, TypeError): x = None if x is not None: if archive[y]['iteration'] < archive.last_iteration \ and repair is not None: x = repair(x, copy_if_changed=copy_always) return x input_type = type(y) x = y if copy_always: x = array(y, copy=True) copy = False else: copy = copy_if_changed x = from_bounds(x, copy) if self.isidentity: if repair is not None: x = repair(x, copy) return x if copy: # could be improved? x = array(x, copy=True) copy = False # user-defined transformation if self.tf_geno is not None: x = array(self.tf_geno(x), copy=False) elif self.tf_pheno is not None: raise ValueError('t1 of options transformation was not defined but is needed as being the inverse of t0') # affine-linear transformation: shift and scaling if self.typical_x is not 0: x -= self.typical_x if self.scales is not 1: # just for efficiency x /= self.scales # kick out fixed_values if self.fixed_values is not None: # keeping the transformed values does not help much # therefore it is omitted if 1 < 3: keys = sorted(self.fixed_values.keys()) x = array([x[i] for i in xrange(len(x)) if i not in keys], copy=False) # repair injected solutions if repair is not None: x = repair(x, copy) if input_type is np.ndarray: x = array(x, copy=False) return x
[ "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 is not applied to the initial solution x0. Details ======= ``geno`` searches first in ``archive`` for the genotype of ``y`` and returns the found value, typically unrepaired. Otherwise, first ``from_bounds`` is applied, to revert a projection into the bound domain (if necessary) and ``pheno`` is reverted. ``repair`` is applied last, and is usually the method ``CMAEvolutionStrategy.repair_genotype`` that limits the Mahalanobis norm of ``geno(y) - mean``.
[ "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
32,498
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 --------- `objective_fct` function be to minimized `iterations` number of (maximal) iterations, while ``not self.stop()`` `min_iterations` minimal number of iterations, even if ``not self.stop()`` `args` arguments passed to `objective_fct` `verb_disp` print to screen every `verb_disp` iteration, if ``None`` the value from ``self.logger`` is "inherited", if available. ``logger`` a `BaseDataLogger` instance, which must be compatible with the type of ``self``. ``call_back`` call back function called like ``call_back(self)`` or a list of call back functions. ``return self``, that is, the `OOOptimizer` instance. Example ------- >>> import cma >>> es = cma.CMAEvolutionStrategy(7 * [0.1], 0.5 ... ).optimize(cma.fcts.rosen, verb_disp=100) (4_w,9)-CMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=630721393) Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec 1 9 3.163954777181882e+01 1.0e+00 4.12e-01 4e-01 4e-01 0:0.0 2 18 3.299006223906629e+01 1.0e+00 3.60e-01 3e-01 4e-01 0:0.0 3 27 1.389129389866704e+01 1.1e+00 3.18e-01 3e-01 3e-01 0:0.0 100 900 2.494847340045985e+00 8.6e+00 5.03e-02 2e-02 5e-02 0:0.3 200 1800 3.428234862999135e-01 1.7e+01 3.77e-02 6e-03 3e-02 0:0.5 300 2700 3.216640032470860e-04 5.6e+01 6.62e-03 4e-04 9e-03 0:0.8 400 3600 6.155215286199821e-12 6.6e+01 7.44e-06 1e-07 4e-06 0:1.1 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 ('termination by', {'tolfun': 1e-11}) ('best f-value =', 1.1189867885201275e-14) ('solution =', array([ 1. , 1. , 1. , 0.99999999, 0.99999998, 0.99999996, 0.99999992])) >>> print(es.result()[0]) array([ 1. 1. 1. 0.99999999 0.99999998 0.99999996 0.99999992]) """ assert iterations is None or min_iterations <= iterations if not hasattr(self, 'logger'): self.logger = logger logger = self.logger = logger or self.logger if not isinstance(call_back, list): call_back = [call_back] citer = 0 while not self.stop() or citer < min_iterations: if iterations is not None and citer >= iterations: return self.result() citer += 1 X = self.ask() # deliver candidate solutions fitvals = [objective_fct(x, *args) for x in X] self.tell(X, fitvals) # all the work is done here self.disp(verb_disp) for f in call_back: f is None or f(self) logger.add(self) if logger else None # signal logger that we left the loop # TODO: this is very ugly, because it assumes modulo keyword # argument *and* modulo attribute to be available try: logger.add(self, modulo=bool(logger.modulo)) if logger else None except TypeError: print(' suppressing the final call of the logger in ' + 'OOOptimizer.optimize (modulo keyword parameter not ' + 'available)') except AttributeError: print(' suppressing the final call of the logger in ' + 'OOOptimizer.optimize (modulo attribute not ' + 'available)') if verb_disp: self.disp(1) if verb_disp in (1, True): print('termination by', self.stop()) print('best f-value =', self.result()[1]) print('solution =', self.result()[0]) return self
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 --------- `objective_fct` function be to minimized `iterations` number of (maximal) iterations, while ``not self.stop()`` `min_iterations` minimal number of iterations, even if ``not self.stop()`` `args` arguments passed to `objective_fct` `verb_disp` print to screen every `verb_disp` iteration, if ``None`` the value from ``self.logger`` is "inherited", if available. ``logger`` a `BaseDataLogger` instance, which must be compatible with the type of ``self``. ``call_back`` call back function called like ``call_back(self)`` or a list of call back functions. ``return self``, that is, the `OOOptimizer` instance. Example ------- >>> import cma >>> es = cma.CMAEvolutionStrategy(7 * [0.1], 0.5 ... ).optimize(cma.fcts.rosen, verb_disp=100) (4_w,9)-CMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=630721393) Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec 1 9 3.163954777181882e+01 1.0e+00 4.12e-01 4e-01 4e-01 0:0.0 2 18 3.299006223906629e+01 1.0e+00 3.60e-01 3e-01 4e-01 0:0.0 3 27 1.389129389866704e+01 1.1e+00 3.18e-01 3e-01 3e-01 0:0.0 100 900 2.494847340045985e+00 8.6e+00 5.03e-02 2e-02 5e-02 0:0.3 200 1800 3.428234862999135e-01 1.7e+01 3.77e-02 6e-03 3e-02 0:0.5 300 2700 3.216640032470860e-04 5.6e+01 6.62e-03 4e-04 9e-03 0:0.8 400 3600 6.155215286199821e-12 6.6e+01 7.44e-06 1e-07 4e-06 0:1.1 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 ('termination by', {'tolfun': 1e-11}) ('best f-value =', 1.1189867885201275e-14) ('solution =', array([ 1. , 1. , 1. , 0.99999999, 0.99999998, 0.99999996, 0.99999992])) >>> print(es.result()[0]) array([ 1. 1. 1. 0.99999999 0.99999998 0.99999996 0.99999992]) """ assert iterations is None or min_iterations <= iterations if not hasattr(self, 'logger'): self.logger = logger logger = self.logger = logger or self.logger if not isinstance(call_back, list): call_back = [call_back] citer = 0 while not self.stop() or citer < min_iterations: if iterations is not None and citer >= iterations: return self.result() citer += 1 X = self.ask() # deliver candidate solutions fitvals = [objective_fct(x, *args) for x in X] self.tell(X, fitvals) # all the work is done here self.disp(verb_disp) for f in call_back: f is None or f(self) logger.add(self) if logger else None # signal logger that we left the loop # TODO: this is very ugly, because it assumes modulo keyword # argument *and* modulo attribute to be available try: logger.add(self, modulo=bool(logger.modulo)) if logger else None except TypeError: print(' suppressing the final call of the logger in ' + 'OOOptimizer.optimize (modulo keyword parameter not ' + 'available)') except AttributeError: print(' suppressing the final call of the logger in ' + 'OOOptimizer.optimize (modulo attribute not ' + 'available)') if verb_disp: self.disp(1) if verb_disp in (1, True): print('termination by', self.stop()) print('best f-value =', self.result()[1]) print('solution =', self.result()[0]) return self
[ "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()`` `min_iterations` minimal number of iterations, even if ``not self.stop()`` `args` arguments passed to `objective_fct` `verb_disp` print to screen every `verb_disp` iteration, if ``None`` the value from ``self.logger`` is "inherited", if available. ``logger`` a `BaseDataLogger` instance, which must be compatible with the type of ``self``. ``call_back`` call back function called like ``call_back(self)`` or a list of call back functions. ``return self``, that is, the `OOOptimizer` instance. Example ------- >>> import cma >>> es = cma.CMAEvolutionStrategy(7 * [0.1], 0.5 ... ).optimize(cma.fcts.rosen, verb_disp=100) (4_w,9)-CMA-ES (mu_w=2.8,w_1=49%) in dimension 7 (seed=630721393) Iterat #Fevals function value axis ratio sigma minstd maxstd min:sec 1 9 3.163954777181882e+01 1.0e+00 4.12e-01 4e-01 4e-01 0:0.0 2 18 3.299006223906629e+01 1.0e+00 3.60e-01 3e-01 4e-01 0:0.0 3 27 1.389129389866704e+01 1.1e+00 3.18e-01 3e-01 3e-01 0:0.0 100 900 2.494847340045985e+00 8.6e+00 5.03e-02 2e-02 5e-02 0:0.3 200 1800 3.428234862999135e-01 1.7e+01 3.77e-02 6e-03 3e-02 0:0.5 300 2700 3.216640032470860e-04 5.6e+01 6.62e-03 4e-04 9e-03 0:0.8 400 3600 6.155215286199821e-12 6.6e+01 7.44e-06 1e-07 4e-06 0:1.1 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 438 3942 1.187372505161762e-14 6.0e+01 3.27e-07 4e-09 9e-08 0:1.2 ('termination by', {'tolfun': 1e-11}) ('best f-value =', 1.1189867885201275e-14) ('solution =', array([ 1. , 1. , 1. , 0.99999999, 0.99999998, 0.99999996, 0.99999992])) >>> print(es.result()[0]) array([ 1. 1. 1. 0.99999999 0.99999998 0.99999996 0.99999992])
[ "find", "minimizer", "of", "objective_fct", "." ]
cf0f81ecb9f6412f7276a95bd27359000e1e26b6
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L2010-L2106
train
32,499