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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
JelteF/PyLaTeX | pylatex/figure.py | Figure.add_plot | def add_plot(self, *args, extension='pdf', **kwargs):
"""Add the current Matplotlib plot to the figure.
The plot that gets added is the one that would normally be shown when
using ``plt.show()``.
Args
----
args:
Arguments passed to plt.savefig for displaying the plot.
extension : str
extension of image file indicating figure file type
kwargs:
Keyword arguments passed to plt.savefig for displaying the plot. In
case these contain ``width`` or ``placement``, they will be used
for the same purpose as in the add_image command. Namely the width
and placement of the generated plot in the LaTeX document.
"""
add_image_kwargs = {}
for key in ('width', 'placement'):
if key in kwargs:
add_image_kwargs[key] = kwargs.pop(key)
filename = self._save_plot(*args, extension=extension, **kwargs)
self.add_image(filename, **add_image_kwargs) | python | def add_plot(self, *args, extension='pdf', **kwargs):
"""Add the current Matplotlib plot to the figure.
The plot that gets added is the one that would normally be shown when
using ``plt.show()``.
Args
----
args:
Arguments passed to plt.savefig for displaying the plot.
extension : str
extension of image file indicating figure file type
kwargs:
Keyword arguments passed to plt.savefig for displaying the plot. In
case these contain ``width`` or ``placement``, they will be used
for the same purpose as in the add_image command. Namely the width
and placement of the generated plot in the LaTeX document.
"""
add_image_kwargs = {}
for key in ('width', 'placement'):
if key in kwargs:
add_image_kwargs[key] = kwargs.pop(key)
filename = self._save_plot(*args, extension=extension, **kwargs)
self.add_image(filename, **add_image_kwargs) | [
"def",
"add_plot",
"(",
"self",
",",
"*",
"args",
",",
"extension",
"=",
"'pdf'",
",",
"*",
"*",
"kwargs",
")",
":",
"add_image_kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"(",
"'width'",
",",
"'placement'",
")",
":",
"if",
"key",
"in",
"kwargs",
"... | Add the current Matplotlib plot to the figure.
The plot that gets added is the one that would normally be shown when
using ``plt.show()``.
Args
----
args:
Arguments passed to plt.savefig for displaying the plot.
extension : str
extension of image file indicating figure file type
kwargs:
Keyword arguments passed to plt.savefig for displaying the plot. In
case these contain ``width`` or ``placement``, they will be used
for the same purpose as in the add_image command. Namely the width
and placement of the generated plot in the LaTeX document. | [
"Add",
"the",
"current",
"Matplotlib",
"plot",
"to",
"the",
"figure",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L64-L91 | train | 223,000 |
JelteF/PyLaTeX | pylatex/figure.py | SubFigure.add_image | def add_image(self, filename, *, width=NoEscape(r'\linewidth'),
placement=None):
"""Add an image to the subfigure.
Args
----
filename: str
Filename of the image.
width: str
Width of the image in LaTeX terms.
placement: str
Placement of the figure, `None` is also accepted.
"""
super().add_image(filename, width=width, placement=placement) | python | def add_image(self, filename, *, width=NoEscape(r'\linewidth'),
placement=None):
"""Add an image to the subfigure.
Args
----
filename: str
Filename of the image.
width: str
Width of the image in LaTeX terms.
placement: str
Placement of the figure, `None` is also accepted.
"""
super().add_image(filename, width=width, placement=placement) | [
"def",
"add_image",
"(",
"self",
",",
"filename",
",",
"*",
",",
"width",
"=",
"NoEscape",
"(",
"r'\\linewidth'",
")",
",",
"placement",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"add_image",
"(",
"filename",
",",
"width",
"=",
"width",
",",
"pl... | Add an image to the subfigure.
Args
----
filename: str
Filename of the image.
width: str
Width of the image in LaTeX terms.
placement: str
Placement of the figure, `None` is also accepted. | [
"Add",
"an",
"image",
"to",
"the",
"subfigure",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L119-L133 | train | 223,001 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject.escape | def escape(self):
"""Determine whether or not to escape content of this class.
This defaults to `True` for most classes.
"""
if self._escape is not None:
return self._escape
if self._default_escape is not None:
return self._default_escape
return True | python | def escape(self):
"""Determine whether or not to escape content of this class.
This defaults to `True` for most classes.
"""
if self._escape is not None:
return self._escape
if self._default_escape is not None:
return self._default_escape
return True | [
"def",
"escape",
"(",
"self",
")",
":",
"if",
"self",
".",
"_escape",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_escape",
"if",
"self",
".",
"_default_escape",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_default_escape",
"return",
"True"
] | Determine whether or not to escape content of this class.
This defaults to `True` for most classes. | [
"Determine",
"whether",
"or",
"not",
"to",
"escape",
"content",
"of",
"this",
"class",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L58-L67 | train | 223,002 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject._repr_values | def _repr_values(self):
"""Return values that are to be shown in repr string."""
def getattr_better(obj, field):
try:
return getattr(obj, field)
except AttributeError as e:
try:
return getattr(obj, '_' + field)
except AttributeError:
raise e
return (getattr_better(self, attr) for attr in self._repr_attributes) | python | def _repr_values(self):
"""Return values that are to be shown in repr string."""
def getattr_better(obj, field):
try:
return getattr(obj, field)
except AttributeError as e:
try:
return getattr(obj, '_' + field)
except AttributeError:
raise e
return (getattr_better(self, attr) for attr in self._repr_attributes) | [
"def",
"_repr_values",
"(",
"self",
")",
":",
"def",
"getattr_better",
"(",
"obj",
",",
"field",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"obj",
",",
"field",
")",
"except",
"AttributeError",
"as",
"e",
":",
"try",
":",
"return",
"getattr",
"(",... | Return values that are to be shown in repr string. | [
"Return",
"values",
"that",
"are",
"to",
"be",
"shown",
"in",
"repr",
"string",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L98-L109 | train | 223,003 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject._repr_attributes | def _repr_attributes(self):
"""Return attributes that should be part of the repr string."""
if self._repr_attributes_override is None:
# Default to init arguments
attrs = getfullargspec(self.__init__).args[1:]
mapping = self._repr_attributes_mapping
if mapping:
attrs = [mapping[a] if a in mapping else a for a in attrs]
return attrs
return self._repr_attributes_override | python | def _repr_attributes(self):
"""Return attributes that should be part of the repr string."""
if self._repr_attributes_override is None:
# Default to init arguments
attrs = getfullargspec(self.__init__).args[1:]
mapping = self._repr_attributes_mapping
if mapping:
attrs = [mapping[a] if a in mapping else a for a in attrs]
return attrs
return self._repr_attributes_override | [
"def",
"_repr_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_repr_attributes_override",
"is",
"None",
":",
"# Default to init arguments",
"attrs",
"=",
"getfullargspec",
"(",
"self",
".",
"__init__",
")",
".",
"args",
"[",
"1",
":",
"]",
"mapping",
... | Return attributes that should be part of the repr string. | [
"Return",
"attributes",
"that",
"should",
"be",
"part",
"of",
"the",
"repr",
"string",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L112-L122 | train | 223,004 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject.latex_name | def latex_name(self):
"""Return the name of the class used in LaTeX.
It can be `None` when the class doesn't have a name.
"""
star = ('*' if self._star_latex_name else '')
if self._latex_name is not None:
return self._latex_name + star
return self.__class__.__name__.lower() + star | python | def latex_name(self):
"""Return the name of the class used in LaTeX.
It can be `None` when the class doesn't have a name.
"""
star = ('*' if self._star_latex_name else '')
if self._latex_name is not None:
return self._latex_name + star
return self.__class__.__name__.lower() + star | [
"def",
"latex_name",
"(",
"self",
")",
":",
"star",
"=",
"(",
"'*'",
"if",
"self",
".",
"_star_latex_name",
"else",
"''",
")",
"if",
"self",
".",
"_latex_name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_latex_name",
"+",
"star",
"return",
"sel... | Return the name of the class used in LaTeX.
It can be `None` when the class doesn't have a name. | [
"Return",
"the",
"name",
"of",
"the",
"class",
"used",
"in",
"LaTeX",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L125-L133 | train | 223,005 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject.generate_tex | def generate_tex(self, filepath):
"""Generate a .tex file.
Args
----
filepath: str
The name of the file (without .tex)
"""
with open(filepath + '.tex', 'w', encoding='utf-8') as newf:
self.dump(newf) | python | def generate_tex(self, filepath):
"""Generate a .tex file.
Args
----
filepath: str
The name of the file (without .tex)
"""
with open(filepath + '.tex', 'w', encoding='utf-8') as newf:
self.dump(newf) | [
"def",
"generate_tex",
"(",
"self",
",",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
"+",
"'.tex'",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"newf",
":",
"self",
".",
"dump",
"(",
"newf",
")"
] | Generate a .tex file.
Args
----
filepath: str
The name of the file (without .tex) | [
"Generate",
"a",
".",
"tex",
"file",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L159-L169 | train | 223,006 |
JelteF/PyLaTeX | pylatex/base_classes/latex_object.py | LatexObject.dumps_as_content | def dumps_as_content(self):
"""Create a string representation of the object as content.
This is currently only used to add new lines before and after the
output of the dumps function. These can be added or removed by changing
the `begin_paragraph`, `end_paragraph` and `separate_paragraph`
attributes of the class.
"""
string = self.dumps()
if self.separate_paragraph or self.begin_paragraph:
string = '\n\n' + string.lstrip('\n')
if self.separate_paragraph or self.end_paragraph:
string = string.rstrip('\n') + '\n\n'
return string | python | def dumps_as_content(self):
"""Create a string representation of the object as content.
This is currently only used to add new lines before and after the
output of the dumps function. These can be added or removed by changing
the `begin_paragraph`, `end_paragraph` and `separate_paragraph`
attributes of the class.
"""
string = self.dumps()
if self.separate_paragraph or self.begin_paragraph:
string = '\n\n' + string.lstrip('\n')
if self.separate_paragraph or self.end_paragraph:
string = string.rstrip('\n') + '\n\n'
return string | [
"def",
"dumps_as_content",
"(",
"self",
")",
":",
"string",
"=",
"self",
".",
"dumps",
"(",
")",
"if",
"self",
".",
"separate_paragraph",
"or",
"self",
".",
"begin_paragraph",
":",
"string",
"=",
"'\\n\\n'",
"+",
"string",
".",
"lstrip",
"(",
"'\\n'",
")... | Create a string representation of the object as content.
This is currently only used to add new lines before and after the
output of the dumps function. These can be added or removed by changing
the `begin_paragraph`, `end_paragraph` and `separate_paragraph`
attributes of the class. | [
"Create",
"a",
"string",
"representation",
"of",
"the",
"object",
"as",
"content",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/latex_object.py#L193-L210 | train | 223,007 |
JelteF/PyLaTeX | pylatex/document.py | Document._propagate_packages | def _propagate_packages(self):
r"""Propogate packages.
Make sure that all the packages included in the previous containers
are part of the full list of packages.
"""
super()._propagate_packages()
for item in (self.preamble):
if isinstance(item, LatexObject):
if isinstance(item, Container):
item._propagate_packages()
for p in item.packages:
self.packages.add(p) | python | def _propagate_packages(self):
r"""Propogate packages.
Make sure that all the packages included in the previous containers
are part of the full list of packages.
"""
super()._propagate_packages()
for item in (self.preamble):
if isinstance(item, LatexObject):
if isinstance(item, Container):
item._propagate_packages()
for p in item.packages:
self.packages.add(p) | [
"def",
"_propagate_packages",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"_propagate_packages",
"(",
")",
"for",
"item",
"in",
"(",
"self",
".",
"preamble",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"LatexObject",
")",
":",
"if",
"isinstance",
... | r"""Propogate packages.
Make sure that all the packages included in the previous containers
are part of the full list of packages. | [
"r",
"Propogate",
"packages",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L129-L143 | train | 223,008 |
JelteF/PyLaTeX | pylatex/document.py | Document.dumps | def dumps(self):
"""Represent the document as a string in LaTeX syntax.
Returns
-------
str
"""
head = self.documentclass.dumps() + '%\n'
head += self.dumps_packages() + '%\n'
head += dumps_list(self.variables) + '%\n'
head += dumps_list(self.preamble) + '%\n'
return head + '%\n' + super().dumps() | python | def dumps(self):
"""Represent the document as a string in LaTeX syntax.
Returns
-------
str
"""
head = self.documentclass.dumps() + '%\n'
head += self.dumps_packages() + '%\n'
head += dumps_list(self.variables) + '%\n'
head += dumps_list(self.preamble) + '%\n'
return head + '%\n' + super().dumps() | [
"def",
"dumps",
"(",
"self",
")",
":",
"head",
"=",
"self",
".",
"documentclass",
".",
"dumps",
"(",
")",
"+",
"'%\\n'",
"head",
"+=",
"self",
".",
"dumps_packages",
"(",
")",
"+",
"'%\\n'",
"head",
"+=",
"dumps_list",
"(",
"self",
".",
"variables",
... | Represent the document as a string in LaTeX syntax.
Returns
-------
str | [
"Represent",
"the",
"document",
"as",
"a",
"string",
"in",
"LaTeX",
"syntax",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L145-L158 | train | 223,009 |
JelteF/PyLaTeX | pylatex/document.py | Document.generate_pdf | def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True,
compiler=None, compiler_args=None, silent=True):
"""Generate a pdf file from the document.
Args
----
filepath: str
The name of the file (without .pdf), if it is `None` the
``default_filepath`` attribute will be used.
clean: bool
Whether non-pdf files created that are created during compilation
should be removed.
clean_tex: bool
Also remove the generated tex file.
compiler: `str` or `None`
The name of the LaTeX compiler to use. If it is None, PyLaTeX will
choose a fitting one on its own. Starting with ``latexmk`` and then
``pdflatex``.
compiler_args: `list` or `None`
Extra arguments that should be passed to the LaTeX compiler. If
this is None it defaults to an empty list.
silent: bool
Whether to hide compiler output
"""
if compiler_args is None:
compiler_args = []
filepath = self._select_filepath(filepath)
filepath = os.path.join('.', filepath)
cur_dir = os.getcwd()
dest_dir = os.path.dirname(filepath)
basename = os.path.basename(filepath)
if basename == '':
basename = 'default_basename'
os.chdir(dest_dir)
self.generate_tex(basename)
if compiler is not None:
compilers = ((compiler, []),)
else:
latexmk_args = ['--pdf']
compilers = (
('latexmk', latexmk_args),
('pdflatex', [])
)
main_arguments = ['--interaction=nonstopmode', basename + '.tex']
os_error = None
for compiler, arguments in compilers:
command = [compiler] + arguments + compiler_args + main_arguments
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
os_error = e
if os_error.errno == errno.ENOENT:
# If compiler does not exist, try next in the list
continue
raise
except subprocess.CalledProcessError as e:
# For all other errors print the output and raise the error
print(e.output.decode())
raise
else:
if not silent:
print(output.decode())
if clean:
try:
# Try latexmk cleaning first
subprocess.check_output(['latexmk', '-c', basename],
stderr=subprocess.STDOUT)
except (OSError, IOError, subprocess.CalledProcessError) as e:
# Otherwise just remove some file extensions.
extensions = ['aux', 'log', 'out', 'fls',
'fdb_latexmk']
for ext in extensions:
try:
os.remove(basename + '.' + ext)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
if e.errno != errno.ENOENT:
raise
rm_temp_dir()
if clean_tex:
os.remove(basename + '.tex') # Remove generated tex file
# Compilation has finished, so no further compilers have to be
# tried
break
else:
# Notify user that none of the compilers worked.
raise(CompilerError(
'No LaTex compiler was found\n' +
'Either specify a LaTex compiler ' +
'or make sure you have latexmk or pdfLaTex installed.'
))
os.chdir(cur_dir) | python | def generate_pdf(self, filepath=None, *, clean=True, clean_tex=True,
compiler=None, compiler_args=None, silent=True):
"""Generate a pdf file from the document.
Args
----
filepath: str
The name of the file (without .pdf), if it is `None` the
``default_filepath`` attribute will be used.
clean: bool
Whether non-pdf files created that are created during compilation
should be removed.
clean_tex: bool
Also remove the generated tex file.
compiler: `str` or `None`
The name of the LaTeX compiler to use. If it is None, PyLaTeX will
choose a fitting one on its own. Starting with ``latexmk`` and then
``pdflatex``.
compiler_args: `list` or `None`
Extra arguments that should be passed to the LaTeX compiler. If
this is None it defaults to an empty list.
silent: bool
Whether to hide compiler output
"""
if compiler_args is None:
compiler_args = []
filepath = self._select_filepath(filepath)
filepath = os.path.join('.', filepath)
cur_dir = os.getcwd()
dest_dir = os.path.dirname(filepath)
basename = os.path.basename(filepath)
if basename == '':
basename = 'default_basename'
os.chdir(dest_dir)
self.generate_tex(basename)
if compiler is not None:
compilers = ((compiler, []),)
else:
latexmk_args = ['--pdf']
compilers = (
('latexmk', latexmk_args),
('pdflatex', [])
)
main_arguments = ['--interaction=nonstopmode', basename + '.tex']
os_error = None
for compiler, arguments in compilers:
command = [compiler] + arguments + compiler_args + main_arguments
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
os_error = e
if os_error.errno == errno.ENOENT:
# If compiler does not exist, try next in the list
continue
raise
except subprocess.CalledProcessError as e:
# For all other errors print the output and raise the error
print(e.output.decode())
raise
else:
if not silent:
print(output.decode())
if clean:
try:
# Try latexmk cleaning first
subprocess.check_output(['latexmk', '-c', basename],
stderr=subprocess.STDOUT)
except (OSError, IOError, subprocess.CalledProcessError) as e:
# Otherwise just remove some file extensions.
extensions = ['aux', 'log', 'out', 'fls',
'fdb_latexmk']
for ext in extensions:
try:
os.remove(basename + '.' + ext)
except (OSError, IOError) as e:
# Use FileNotFoundError when python 2 is dropped
if e.errno != errno.ENOENT:
raise
rm_temp_dir()
if clean_tex:
os.remove(basename + '.tex') # Remove generated tex file
# Compilation has finished, so no further compilers have to be
# tried
break
else:
# Notify user that none of the compilers worked.
raise(CompilerError(
'No LaTex compiler was found\n' +
'Either specify a LaTex compiler ' +
'or make sure you have latexmk or pdfLaTex installed.'
))
os.chdir(cur_dir) | [
"def",
"generate_pdf",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"*",
",",
"clean",
"=",
"True",
",",
"clean_tex",
"=",
"True",
",",
"compiler",
"=",
"None",
",",
"compiler_args",
"=",
"None",
",",
"silent",
"=",
"True",
")",
":",
"if",
"compil... | Generate a pdf file from the document.
Args
----
filepath: str
The name of the file (without .pdf), if it is `None` the
``default_filepath`` attribute will be used.
clean: bool
Whether non-pdf files created that are created during compilation
should be removed.
clean_tex: bool
Also remove the generated tex file.
compiler: `str` or `None`
The name of the LaTeX compiler to use. If it is None, PyLaTeX will
choose a fitting one on its own. Starting with ``latexmk`` and then
``pdflatex``.
compiler_args: `list` or `None`
Extra arguments that should be passed to the LaTeX compiler. If
this is None it defaults to an empty list.
silent: bool
Whether to hide compiler output | [
"Generate",
"a",
"pdf",
"file",
"from",
"the",
"document",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L172-L284 | train | 223,010 |
JelteF/PyLaTeX | pylatex/document.py | Document._select_filepath | def _select_filepath(self, filepath):
"""Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath
"""
if filepath is None:
return self.default_filepath
else:
if os.path.basename(filepath) == '':
filepath = os.path.join(filepath, os.path.basename(
self.default_filepath))
return filepath | python | def _select_filepath(self, filepath):
"""Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath
"""
if filepath is None:
return self.default_filepath
else:
if os.path.basename(filepath) == '':
filepath = os.path.join(filepath, os.path.basename(
self.default_filepath))
return filepath | [
"def",
"_select_filepath",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"filepath",
"is",
"None",
":",
"return",
"self",
".",
"default_filepath",
"else",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"==",
"''",
":",
"filepath",
... | Make a choice between ``filepath`` and ``self.default_filepath``.
Args
----
filepath: str
the filepath to be compared with ``self.default_filepath``
Returns
-------
str
The selected filepath | [
"Make",
"a",
"choice",
"between",
"filepath",
"and",
"self",
".",
"default_filepath",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L286-L306 | train | 223,011 |
JelteF/PyLaTeX | pylatex/document.py | Document.add_color | def add_color(self, name, model, description):
r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color
"""
if self.color is False:
self.packages.append(Package("color"))
self.color = True
self.preamble.append(Command("definecolor", arguments=[name,
model,
description])) | python | def add_color(self, name, model, description):
r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color
"""
if self.color is False:
self.packages.append(Package("color"))
self.color = True
self.preamble.append(Command("definecolor", arguments=[name,
model,
description])) | [
"def",
"add_color",
"(",
"self",
",",
"name",
",",
"model",
",",
"description",
")",
":",
"if",
"self",
".",
"color",
"is",
"False",
":",
"self",
".",
"packages",
".",
"append",
"(",
"Package",
"(",
"\"color\"",
")",
")",
"self",
".",
"color",
"=",
... | r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color | [
"r",
"Add",
"a",
"color",
"that",
"can",
"be",
"used",
"throughout",
"the",
"document",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L330-L349 | train | 223,012 |
JelteF/PyLaTeX | pylatex/document.py | Document.change_length | def change_length(self, parameter, value):
r"""Change the length of a certain parameter to a certain value.
Args
----
parameter: str
The name of the parameter to change the length for
value: str
The value to set the parameter to
"""
self.preamble.append(UnsafeCommand('setlength',
arguments=[parameter, value])) | python | def change_length(self, parameter, value):
r"""Change the length of a certain parameter to a certain value.
Args
----
parameter: str
The name of the parameter to change the length for
value: str
The value to set the parameter to
"""
self.preamble.append(UnsafeCommand('setlength',
arguments=[parameter, value])) | [
"def",
"change_length",
"(",
"self",
",",
"parameter",
",",
"value",
")",
":",
"self",
".",
"preamble",
".",
"append",
"(",
"UnsafeCommand",
"(",
"'setlength'",
",",
"arguments",
"=",
"[",
"parameter",
",",
"value",
"]",
")",
")"
] | r"""Change the length of a certain parameter to a certain value.
Args
----
parameter: str
The name of the parameter to change the length for
value: str
The value to set the parameter to | [
"r",
"Change",
"the",
"length",
"of",
"a",
"certain",
"parameter",
"to",
"a",
"certain",
"value",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L351-L363 | train | 223,013 |
JelteF/PyLaTeX | pylatex/document.py | Document.set_variable | def set_variable(self, name, value):
r"""Add a variable which can be used inside the document.
Variables are defined before the preamble. If a variable with that name
has already been set, the new value will override it for future uses.
This is done by appending ``\renewcommand`` to the document.
Args
----
name: str
The name to set for the variable
value: str
The value to set for the variable
"""
name_arg = "\\" + name
variable_exists = False
for variable in self.variables:
if name_arg == variable.arguments._positional_args[0]:
variable_exists = True
break
if variable_exists:
renew = Command(command="renewcommand",
arguments=[NoEscape(name_arg), value])
self.append(renew)
else:
new = Command(command="newcommand",
arguments=[NoEscape(name_arg), value])
self.variables.append(new) | python | def set_variable(self, name, value):
r"""Add a variable which can be used inside the document.
Variables are defined before the preamble. If a variable with that name
has already been set, the new value will override it for future uses.
This is done by appending ``\renewcommand`` to the document.
Args
----
name: str
The name to set for the variable
value: str
The value to set for the variable
"""
name_arg = "\\" + name
variable_exists = False
for variable in self.variables:
if name_arg == variable.arguments._positional_args[0]:
variable_exists = True
break
if variable_exists:
renew = Command(command="renewcommand",
arguments=[NoEscape(name_arg), value])
self.append(renew)
else:
new = Command(command="newcommand",
arguments=[NoEscape(name_arg), value])
self.variables.append(new) | [
"def",
"set_variable",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name_arg",
"=",
"\"\\\\\"",
"+",
"name",
"variable_exists",
"=",
"False",
"for",
"variable",
"in",
"self",
".",
"variables",
":",
"if",
"name_arg",
"==",
"variable",
".",
"arguments"... | r"""Add a variable which can be used inside the document.
Variables are defined before the preamble. If a variable with that name
has already been set, the new value will override it for future uses.
This is done by appending ``\renewcommand`` to the document.
Args
----
name: str
The name to set for the variable
value: str
The value to set for the variable | [
"r",
"Add",
"a",
"variable",
"which",
"can",
"be",
"used",
"inside",
"the",
"document",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/document.py#L365-L395 | train | 223,014 |
JelteF/PyLaTeX | pylatex/config.py | Version1.change | def change(self, **kwargs):
"""Override some attributes of the config in a specific context.
A simple usage example::
with pylatex.config.active.change(indent=False):
# Do stuff where indent should be False
...
Args
----
kwargs:
Key value pairs of the default attributes that should be overridden
"""
old_attrs = {}
for k, v in kwargs.items():
old_attrs[k] = getattr(self, k, v)
setattr(self, k, v)
yield self # allows with ... as ...
for k, v in old_attrs.items():
setattr(self, k, v) | python | def change(self, **kwargs):
"""Override some attributes of the config in a specific context.
A simple usage example::
with pylatex.config.active.change(indent=False):
# Do stuff where indent should be False
...
Args
----
kwargs:
Key value pairs of the default attributes that should be overridden
"""
old_attrs = {}
for k, v in kwargs.items():
old_attrs[k] = getattr(self, k, v)
setattr(self, k, v)
yield self # allows with ... as ...
for k, v in old_attrs.items():
setattr(self, k, v) | [
"def",
"change",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"old_attrs",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"old_attrs",
"[",
"k",
"]",
"=",
"getattr",
"(",
"self",
",",
"k",
",",
"v",
")",
... | Override some attributes of the config in a specific context.
A simple usage example::
with pylatex.config.active.change(indent=False):
# Do stuff where indent should be False
...
Args
----
kwargs:
Key value pairs of the default attributes that should be overridden | [
"Override",
"some",
"attributes",
"of",
"the",
"config",
"in",
"a",
"specific",
"context",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/config.py#L63-L87 | train | 223,015 |
JelteF/PyLaTeX | pylatex/base_classes/command.py | CommandBase.__key | def __key(self):
"""Return a hashable key, representing the command.
Returns
-------
tuple
"""
return (self.latex_name, self.arguments, self.options,
self.extra_arguments) | python | def __key(self):
"""Return a hashable key, representing the command.
Returns
-------
tuple
"""
return (self.latex_name, self.arguments, self.options,
self.extra_arguments) | [
"def",
"__key",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"latex_name",
",",
"self",
".",
"arguments",
",",
"self",
".",
"options",
",",
"self",
".",
"extra_arguments",
")"
] | Return a hashable key, representing the command.
Returns
-------
tuple | [
"Return",
"a",
"hashable",
"key",
"representing",
"the",
"command",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L65-L74 | train | 223,016 |
JelteF/PyLaTeX | pylatex/base_classes/command.py | CommandBase.dumps | def dumps(self):
"""Represent the command as a string in LaTeX syntax.
Returns
-------
str
The LaTeX formatted command
"""
options = self.options.dumps()
arguments = self.arguments.dumps()
if self.extra_arguments is None:
return r'\{command}{options}{arguments}'\
.format(command=self.latex_name, options=options,
arguments=arguments)
extra_arguments = self.extra_arguments.dumps()
return r'\{command}{arguments}{options}{extra_arguments}'\
.format(command=self.latex_name, arguments=arguments,
options=options, extra_arguments=extra_arguments) | python | def dumps(self):
"""Represent the command as a string in LaTeX syntax.
Returns
-------
str
The LaTeX formatted command
"""
options = self.options.dumps()
arguments = self.arguments.dumps()
if self.extra_arguments is None:
return r'\{command}{options}{arguments}'\
.format(command=self.latex_name, options=options,
arguments=arguments)
extra_arguments = self.extra_arguments.dumps()
return r'\{command}{arguments}{options}{extra_arguments}'\
.format(command=self.latex_name, arguments=arguments,
options=options, extra_arguments=extra_arguments) | [
"def",
"dumps",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"options",
".",
"dumps",
"(",
")",
"arguments",
"=",
"self",
".",
"arguments",
".",
"dumps",
"(",
")",
"if",
"self",
".",
"extra_arguments",
"is",
"None",
":",
"return",
"r'\\{command}... | Represent the command as a string in LaTeX syntax.
Returns
-------
str
The LaTeX formatted command | [
"Represent",
"the",
"command",
"as",
"a",
"string",
"in",
"LaTeX",
"syntax",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L107-L128 | train | 223,017 |
JelteF/PyLaTeX | pylatex/base_classes/command.py | Parameters._format_contents | def _format_contents(self, prefix, separator, suffix):
"""Format the parameters.
The formatting is done using the three arguments suplied to this
function.
Arguments
---------
prefix: str
separator: str
suffix: str
Returns
-------
str
"""
params = self._list_args_kwargs()
if len(params) <= 0:
return ''
string = prefix + dumps_list(params, escape=self.escape,
token=separator) + suffix
return string | python | def _format_contents(self, prefix, separator, suffix):
"""Format the parameters.
The formatting is done using the three arguments suplied to this
function.
Arguments
---------
prefix: str
separator: str
suffix: str
Returns
-------
str
"""
params = self._list_args_kwargs()
if len(params) <= 0:
return ''
string = prefix + dumps_list(params, escape=self.escape,
token=separator) + suffix
return string | [
"def",
"_format_contents",
"(",
"self",
",",
"prefix",
",",
"separator",
",",
"suffix",
")",
":",
"params",
"=",
"self",
".",
"_list_args_kwargs",
"(",
")",
"if",
"len",
"(",
"params",
")",
"<=",
"0",
":",
"return",
"''",
"string",
"=",
"prefix",
"+",
... | Format the parameters.
The formatting is done using the three arguments suplied to this
function.
Arguments
---------
prefix: str
separator: str
suffix: str
Returns
-------
str | [
"Format",
"the",
"parameters",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L264-L289 | train | 223,018 |
JelteF/PyLaTeX | pylatex/base_classes/command.py | Parameters._list_args_kwargs | def _list_args_kwargs(self):
"""Make a list of strings representing al parameters.
Returns
-------
list
"""
params = []
params.extend(self._positional_args)
params.extend(['{k}={v}'.format(k=k, v=v) for k, v in
self._key_value_args.items()])
return params | python | def _list_args_kwargs(self):
"""Make a list of strings representing al parameters.
Returns
-------
list
"""
params = []
params.extend(self._positional_args)
params.extend(['{k}={v}'.format(k=k, v=v) for k, v in
self._key_value_args.items()])
return params | [
"def",
"_list_args_kwargs",
"(",
"self",
")",
":",
"params",
"=",
"[",
"]",
"params",
".",
"extend",
"(",
"self",
".",
"_positional_args",
")",
"params",
".",
"extend",
"(",
"[",
"'{k}={v}'",
".",
"format",
"(",
"k",
"=",
"k",
",",
"v",
"=",
"v",
"... | Make a list of strings representing al parameters.
Returns
-------
list | [
"Make",
"a",
"list",
"of",
"strings",
"representing",
"al",
"parameters",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/command.py#L291-L304 | train | 223,019 |
JelteF/PyLaTeX | pylatex/math.py | Matrix.dumps_content | def dumps_content(self):
"""Return a string representing the matrix in LaTeX syntax.
Returns
-------
str
"""
import numpy as np
string = ''
shape = self.matrix.shape
for (y, x), value in np.ndenumerate(self.matrix):
if x:
string += '&'
string += str(value)
if x == shape[1] - 1 and y != shape[0] - 1:
string += r'\\' + '%\n'
super().dumps_content()
return string | python | def dumps_content(self):
"""Return a string representing the matrix in LaTeX syntax.
Returns
-------
str
"""
import numpy as np
string = ''
shape = self.matrix.shape
for (y, x), value in np.ndenumerate(self.matrix):
if x:
string += '&'
string += str(value)
if x == shape[1] - 1 and y != shape[0] - 1:
string += r'\\' + '%\n'
super().dumps_content()
return string | [
"def",
"dumps_content",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"string",
"=",
"''",
"shape",
"=",
"self",
".",
"matrix",
".",
"shape",
"for",
"(",
"y",
",",
"x",
")",
",",
"value",
"in",
"np",
".",
"ndenumerate",
"(",
"self",
".",
... | Return a string representing the matrix in LaTeX syntax.
Returns
-------
str | [
"Return",
"a",
"string",
"representing",
"the",
"matrix",
"in",
"LaTeX",
"syntax",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/math.py#L133-L156 | train | 223,020 |
JelteF/PyLaTeX | pylatex/headfoot.py | PageStyle.change_thickness | def change_thickness(self, element, thickness):
r"""Change line thickness.
Changes the thickness of the line under/over the header/footer
to the specified thickness.
Args
----
element: str
the name of the element to change thickness for: header, footer
thickness: float
the thickness to set the line to
"""
if element == "header":
self.data.append(Command("renewcommand",
arguments=[NoEscape(r"\headrulewidth"),
str(thickness) + 'pt']))
elif element == "footer":
self.data.append(Command("renewcommand", arguments=[
NoEscape(r"\footrulewidth"), str(thickness) + 'pt'])) | python | def change_thickness(self, element, thickness):
r"""Change line thickness.
Changes the thickness of the line under/over the header/footer
to the specified thickness.
Args
----
element: str
the name of the element to change thickness for: header, footer
thickness: float
the thickness to set the line to
"""
if element == "header":
self.data.append(Command("renewcommand",
arguments=[NoEscape(r"\headrulewidth"),
str(thickness) + 'pt']))
elif element == "footer":
self.data.append(Command("renewcommand", arguments=[
NoEscape(r"\footrulewidth"), str(thickness) + 'pt'])) | [
"def",
"change_thickness",
"(",
"self",
",",
"element",
",",
"thickness",
")",
":",
"if",
"element",
"==",
"\"header\"",
":",
"self",
".",
"data",
".",
"append",
"(",
"Command",
"(",
"\"renewcommand\"",
",",
"arguments",
"=",
"[",
"NoEscape",
"(",
"r\"\\he... | r"""Change line thickness.
Changes the thickness of the line under/over the header/footer
to the specified thickness.
Args
----
element: str
the name of the element to change thickness for: header, footer
thickness: float
the thickness to set the line to | [
"r",
"Change",
"line",
"thickness",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/headfoot.py#L47-L67 | train | 223,021 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZCoordinate.from_str | def from_str(cls, coordinate):
"""Build a TikZCoordinate object from a string."""
m = cls._coordinate_str_regex.match(coordinate)
if m is None:
raise ValueError('invalid coordinate string')
if m.group(1) == '++':
relative = True
else:
relative = False
return TikZCoordinate(
float(m.group(2)), float(m.group(4)), relative=relative) | python | def from_str(cls, coordinate):
"""Build a TikZCoordinate object from a string."""
m = cls._coordinate_str_regex.match(coordinate)
if m is None:
raise ValueError('invalid coordinate string')
if m.group(1) == '++':
relative = True
else:
relative = False
return TikZCoordinate(
float(m.group(2)), float(m.group(4)), relative=relative) | [
"def",
"from_str",
"(",
"cls",
",",
"coordinate",
")",
":",
"m",
"=",
"cls",
".",
"_coordinate_str_regex",
".",
"match",
"(",
"coordinate",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'invalid coordinate string'",
")",
"if",
"m",
".",
... | Build a TikZCoordinate object from a string. | [
"Build",
"a",
"TikZCoordinate",
"object",
"from",
"a",
"string",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L89-L103 | train | 223,022 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZCoordinate.distance_to | def distance_to(self, other):
"""Euclidean distance between two coordinates."""
other_coord = self._arith_check(other)
return math.sqrt(math.pow(self._x - other_coord._x, 2) +
math.pow(self._y - other_coord._y, 2)) | python | def distance_to(self, other):
"""Euclidean distance between two coordinates."""
other_coord = self._arith_check(other)
return math.sqrt(math.pow(self._x - other_coord._x, 2) +
math.pow(self._y - other_coord._y, 2)) | [
"def",
"distance_to",
"(",
"self",
",",
"other",
")",
":",
"other_coord",
"=",
"self",
".",
"_arith_check",
"(",
"other",
")",
"return",
"math",
".",
"sqrt",
"(",
"math",
".",
"pow",
"(",
"self",
".",
"_x",
"-",
"other_coord",
".",
"_x",
",",
"2",
... | Euclidean distance between two coordinates. | [
"Euclidean",
"distance",
"between",
"two",
"coordinates",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L151-L156 | train | 223,023 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZNode.dumps | def dumps(self):
"""Return string representation of the node."""
ret_str = []
ret_str.append(Command('node', options=self.options).dumps())
if self.handle is not None:
ret_str.append('({})'.format(self.handle))
if self._node_position is not None:
ret_str.append('at {}'.format(str(self._position)))
if self._node_text is not None:
ret_str.append('{{{text}}};'.format(text=self._node_text))
else:
ret_str.append('{};')
return ' '.join(ret_str) | python | def dumps(self):
"""Return string representation of the node."""
ret_str = []
ret_str.append(Command('node', options=self.options).dumps())
if self.handle is not None:
ret_str.append('({})'.format(self.handle))
if self._node_position is not None:
ret_str.append('at {}'.format(str(self._position)))
if self._node_text is not None:
ret_str.append('{{{text}}};'.format(text=self._node_text))
else:
ret_str.append('{};')
return ' '.join(ret_str) | [
"def",
"dumps",
"(",
"self",
")",
":",
"ret_str",
"=",
"[",
"]",
"ret_str",
".",
"append",
"(",
"Command",
"(",
"'node'",
",",
"options",
"=",
"self",
".",
"options",
")",
".",
"dumps",
"(",
")",
")",
"if",
"self",
".",
"handle",
"is",
"not",
"No... | Return string representation of the node. | [
"Return",
"string",
"representation",
"of",
"the",
"node",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L230-L247 | train | 223,024 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZNode.get_anchor_point | def get_anchor_point(self, anchor_name):
"""Return an anchor point of the node, if it exists."""
if anchor_name in self._possible_anchors:
return TikZNodeAnchor(self.handle, anchor_name)
else:
try:
anchor = int(anchor_name.split('_')[1])
except:
anchor = None
if anchor is not None:
return TikZNodeAnchor(self.handle, str(anchor))
raise ValueError('Invalid anchor name: "{}"'.format(anchor_name)) | python | def get_anchor_point(self, anchor_name):
"""Return an anchor point of the node, if it exists."""
if anchor_name in self._possible_anchors:
return TikZNodeAnchor(self.handle, anchor_name)
else:
try:
anchor = int(anchor_name.split('_')[1])
except:
anchor = None
if anchor is not None:
return TikZNodeAnchor(self.handle, str(anchor))
raise ValueError('Invalid anchor name: "{}"'.format(anchor_name)) | [
"def",
"get_anchor_point",
"(",
"self",
",",
"anchor_name",
")",
":",
"if",
"anchor_name",
"in",
"self",
".",
"_possible_anchors",
":",
"return",
"TikZNodeAnchor",
"(",
"self",
".",
"handle",
",",
"anchor_name",
")",
"else",
":",
"try",
":",
"anchor",
"=",
... | Return an anchor point of the node, if it exists. | [
"Return",
"an",
"anchor",
"point",
"of",
"the",
"node",
"if",
"it",
"exists",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L249-L263 | train | 223,025 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZUserPath.dumps | def dumps(self):
"""Return path command representation."""
ret_str = self.path_type
if self.options is not None:
ret_str += self.options.dumps()
return ret_str | python | def dumps(self):
"""Return path command representation."""
ret_str = self.path_type
if self.options is not None:
ret_str += self.options.dumps()
return ret_str | [
"def",
"dumps",
"(",
"self",
")",
":",
"ret_str",
"=",
"self",
".",
"path_type",
"if",
"self",
".",
"options",
"is",
"not",
"None",
":",
"ret_str",
"+=",
"self",
".",
"options",
".",
"dumps",
"(",
")",
"return",
"ret_str"
] | Return path command representation. | [
"Return",
"path",
"command",
"representation",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L292-L300 | train | 223,026 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZPathList.dumps | def dumps(self):
"""Return representation of the path command."""
ret_str = []
for item in self._arg_list:
if isinstance(item, TikZUserPath):
ret_str.append(item.dumps())
elif isinstance(item, TikZCoordinate):
ret_str.append(item.dumps())
elif isinstance(item, str):
ret_str.append(item)
return ' '.join(ret_str) | python | def dumps(self):
"""Return representation of the path command."""
ret_str = []
for item in self._arg_list:
if isinstance(item, TikZUserPath):
ret_str.append(item.dumps())
elif isinstance(item, TikZCoordinate):
ret_str.append(item.dumps())
elif isinstance(item, str):
ret_str.append(item)
return ' '.join(ret_str) | [
"def",
"dumps",
"(",
"self",
")",
":",
"ret_str",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"_arg_list",
":",
"if",
"isinstance",
"(",
"item",
",",
"TikZUserPath",
")",
":",
"ret_str",
".",
"append",
"(",
"item",
".",
"dumps",
"(",
")",
")",... | Return representation of the path command. | [
"Return",
"representation",
"of",
"the",
"path",
"command",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L423-L435 | train | 223,027 |
JelteF/PyLaTeX | pylatex/tikz.py | TikZPath.dumps | def dumps(self):
"""Return a representation for the command."""
ret_str = [Command('path', options=self.options).dumps()]
ret_str.append(self.path.dumps())
return ' '.join(ret_str) + ';' | python | def dumps(self):
"""Return a representation for the command."""
ret_str = [Command('path', options=self.options).dumps()]
ret_str.append(self.path.dumps())
return ' '.join(ret_str) + ';' | [
"def",
"dumps",
"(",
"self",
")",
":",
"ret_str",
"=",
"[",
"Command",
"(",
"'path'",
",",
"options",
"=",
"self",
".",
"options",
")",
".",
"dumps",
"(",
")",
"]",
"ret_str",
".",
"append",
"(",
"self",
".",
"path",
".",
"dumps",
"(",
")",
")",
... | Return a representation for the command. | [
"Return",
"a",
"representation",
"for",
"the",
"command",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L467-L474 | train | 223,028 |
JelteF/PyLaTeX | pylatex/tikz.py | Plot.dumps | def dumps(self):
"""Represent the plot as a string in LaTeX syntax.
Returns
-------
str
"""
string = Command('addplot', options=self.options).dumps()
if self.coordinates is not None:
string += ' coordinates {%\n'
if self.error_bar is None:
for x, y in self.coordinates:
# ie: "(x,y)"
string += '(' + str(x) + ',' + str(y) + ')%\n'
else:
for (x, y), (e_x, e_y) in zip(self.coordinates,
self.error_bar):
# ie: "(x,y) +- (e_x,e_y)"
string += '(' + str(x) + ',' + str(y) + \
') +- (' + str(e_x) + ',' + str(e_y) + ')%\n'
string += '};%\n%\n'
elif self.func is not None:
string += '{' + self.func + '};%\n%\n'
if self.name is not None:
string += Command('addlegendentry', self.name).dumps()
super().dumps()
return string | python | def dumps(self):
"""Represent the plot as a string in LaTeX syntax.
Returns
-------
str
"""
string = Command('addplot', options=self.options).dumps()
if self.coordinates is not None:
string += ' coordinates {%\n'
if self.error_bar is None:
for x, y in self.coordinates:
# ie: "(x,y)"
string += '(' + str(x) + ',' + str(y) + ')%\n'
else:
for (x, y), (e_x, e_y) in zip(self.coordinates,
self.error_bar):
# ie: "(x,y) +- (e_x,e_y)"
string += '(' + str(x) + ',' + str(y) + \
') +- (' + str(e_x) + ',' + str(e_y) + ')%\n'
string += '};%\n%\n'
elif self.func is not None:
string += '{' + self.func + '};%\n%\n'
if self.name is not None:
string += Command('addlegendentry', self.name).dumps()
super().dumps()
return string | [
"def",
"dumps",
"(",
"self",
")",
":",
"string",
"=",
"Command",
"(",
"'addplot'",
",",
"options",
"=",
"self",
".",
"options",
")",
".",
"dumps",
"(",
")",
"if",
"self",
".",
"coordinates",
"is",
"not",
"None",
":",
"string",
"+=",
"' coordinates {%\\... | Represent the plot as a string in LaTeX syntax.
Returns
-------
str | [
"Represent",
"the",
"plot",
"as",
"a",
"string",
"in",
"LaTeX",
"syntax",
"."
] | 62d9d9912ce8445e6629cdbcb80ad86143a1ed23 | https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/tikz.py#L530-L565 | train | 223,029 |
SheffieldML/GPyOpt | GPyOpt/core/task/cost.py | CostModel._cost_gp | def _cost_gp(self,x):
"""
Predicts the time cost of evaluating the function at x.
"""
m, _, _, _ = self.cost_model.predict_withGradients(x)
return np.exp(m) | python | def _cost_gp(self,x):
"""
Predicts the time cost of evaluating the function at x.
"""
m, _, _, _ = self.cost_model.predict_withGradients(x)
return np.exp(m) | [
"def",
"_cost_gp",
"(",
"self",
",",
"x",
")",
":",
"m",
",",
"_",
",",
"_",
",",
"_",
"=",
"self",
".",
"cost_model",
".",
"predict_withGradients",
"(",
"x",
")",
"return",
"np",
".",
"exp",
"(",
"m",
")"
] | Predicts the time cost of evaluating the function at x. | [
"Predicts",
"the",
"time",
"cost",
"of",
"evaluating",
"the",
"function",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L41-L46 | train | 223,030 |
SheffieldML/GPyOpt | GPyOpt/core/task/cost.py | CostModel._cost_gp_withGradients | def _cost_gp_withGradients(self,x):
"""
Predicts the time cost and its gradient of evaluating the function at x.
"""
m, _, dmdx, _= self.cost_model.predict_withGradients(x)
return np.exp(m), np.exp(m)*dmdx | python | def _cost_gp_withGradients(self,x):
"""
Predicts the time cost and its gradient of evaluating the function at x.
"""
m, _, dmdx, _= self.cost_model.predict_withGradients(x)
return np.exp(m), np.exp(m)*dmdx | [
"def",
"_cost_gp_withGradients",
"(",
"self",
",",
"x",
")",
":",
"m",
",",
"_",
",",
"dmdx",
",",
"_",
"=",
"self",
".",
"cost_model",
".",
"predict_withGradients",
"(",
"x",
")",
"return",
"np",
".",
"exp",
"(",
"m",
")",
",",
"np",
".",
"exp",
... | Predicts the time cost and its gradient of evaluating the function at x. | [
"Predicts",
"the",
"time",
"cost",
"and",
"its",
"gradient",
"of",
"evaluating",
"the",
"function",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L48-L53 | train | 223,031 |
SheffieldML/GPyOpt | GPyOpt/core/task/cost.py | CostModel.update_cost_model | def update_cost_model(self, x, cost_x):
"""
Updates the GP used to handle the cost.
param x: input of the GP for the cost model.
param x_cost: values of the time cost at the input locations.
"""
if self.cost_type == 'evaluation_time':
cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T)
if self.num_updates == 0:
X_all = x
costs_all = cost_evals
else:
X_all = np.vstack((self.cost_model.model.X,x))
costs_all = np.vstack((self.cost_model.model.Y,cost_evals))
self.num_updates += 1
self.cost_model.updateModel(X_all, costs_all, None, None) | python | def update_cost_model(self, x, cost_x):
"""
Updates the GP used to handle the cost.
param x: input of the GP for the cost model.
param x_cost: values of the time cost at the input locations.
"""
if self.cost_type == 'evaluation_time':
cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T)
if self.num_updates == 0:
X_all = x
costs_all = cost_evals
else:
X_all = np.vstack((self.cost_model.model.X,x))
costs_all = np.vstack((self.cost_model.model.Y,cost_evals))
self.num_updates += 1
self.cost_model.updateModel(X_all, costs_all, None, None) | [
"def",
"update_cost_model",
"(",
"self",
",",
"x",
",",
"cost_x",
")",
":",
"if",
"self",
".",
"cost_type",
"==",
"'evaluation_time'",
":",
"cost_evals",
"=",
"np",
".",
"log",
"(",
"np",
".",
"atleast_2d",
"(",
"np",
".",
"asarray",
"(",
"cost_x",
")"... | Updates the GP used to handle the cost.
param x: input of the GP for the cost model.
param x_cost: values of the time cost at the input locations. | [
"Updates",
"the",
"GP",
"used",
"to",
"handle",
"the",
"cost",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/cost.py#L55-L74 | train | 223,032 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP.update_batches | def update_batches(self, X_batch, L, Min):
"""
Updates the batches internally and pre-computes the
"""
self.X_batch = X_batch
if X_batch is not None:
self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model) | python | def update_batches(self, X_batch, L, Min):
"""
Updates the batches internally and pre-computes the
"""
self.X_batch = X_batch
if X_batch is not None:
self.r_x0, self.s_x0 = self._hammer_function_precompute(X_batch, L, Min, self.model) | [
"def",
"update_batches",
"(",
"self",
",",
"X_batch",
",",
"L",
",",
"Min",
")",
":",
"self",
".",
"X_batch",
"=",
"X_batch",
"if",
"X_batch",
"is",
"not",
"None",
":",
"self",
".",
"r_x0",
",",
"self",
".",
"s_x0",
"=",
"self",
".",
"_hammer_functio... | Updates the batches internally and pre-computes the | [
"Updates",
"the",
"batches",
"internally",
"and",
"pre",
"-",
"computes",
"the"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L40-L46 | train | 223,033 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP._hammer_function_precompute | def _hammer_function_precompute(self,x0, L, Min, model):
"""
Pre-computes the parameters of a penalizer centered at x0.
"""
if x0 is None: return None, None
if len(x0.shape)==1: x0 = x0[None,:]
m = model.predict(x0)[0]
pred = model.predict(x0)[1].copy()
pred[pred<1e-16] = 1e-16
s = np.sqrt(pred)
r_x0 = (m-Min)/L
s_x0 = s/L
r_x0 = r_x0.flatten()
s_x0 = s_x0.flatten()
return r_x0, s_x0 | python | def _hammer_function_precompute(self,x0, L, Min, model):
"""
Pre-computes the parameters of a penalizer centered at x0.
"""
if x0 is None: return None, None
if len(x0.shape)==1: x0 = x0[None,:]
m = model.predict(x0)[0]
pred = model.predict(x0)[1].copy()
pred[pred<1e-16] = 1e-16
s = np.sqrt(pred)
r_x0 = (m-Min)/L
s_x0 = s/L
r_x0 = r_x0.flatten()
s_x0 = s_x0.flatten()
return r_x0, s_x0 | [
"def",
"_hammer_function_precompute",
"(",
"self",
",",
"x0",
",",
"L",
",",
"Min",
",",
"model",
")",
":",
"if",
"x0",
"is",
"None",
":",
"return",
"None",
",",
"None",
"if",
"len",
"(",
"x0",
".",
"shape",
")",
"==",
"1",
":",
"x0",
"=",
"x0",
... | Pre-computes the parameters of a penalizer centered at x0. | [
"Pre",
"-",
"computes",
"the",
"parameters",
"of",
"a",
"penalizer",
"centered",
"at",
"x0",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L48-L62 | train | 223,034 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP._hammer_function | def _hammer_function(self, x,x0,r_x0, s_x0):
'''
Creates the function to define the exclusion zones
'''
return norm.logcdf((np.sqrt((np.square(np.atleast_2d(x)[:,None,:]-np.atleast_2d(x0)[None,:,:])).sum(-1))- r_x0)/s_x0) | python | def _hammer_function(self, x,x0,r_x0, s_x0):
'''
Creates the function to define the exclusion zones
'''
return norm.logcdf((np.sqrt((np.square(np.atleast_2d(x)[:,None,:]-np.atleast_2d(x0)[None,:,:])).sum(-1))- r_x0)/s_x0) | [
"def",
"_hammer_function",
"(",
"self",
",",
"x",
",",
"x0",
",",
"r_x0",
",",
"s_x0",
")",
":",
"return",
"norm",
".",
"logcdf",
"(",
"(",
"np",
".",
"sqrt",
"(",
"(",
"np",
".",
"square",
"(",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"[",
":",... | Creates the function to define the exclusion zones | [
"Creates",
"the",
"function",
"to",
"define",
"the",
"exclusion",
"zones"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L64-L68 | train | 223,035 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP._penalized_acquisition | def _penalized_acquisition(self, x, model, X_batch, r_x0, s_x0):
'''
Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch
.. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable.
'''
fval = -self.acq.acquisition_function(x)[:,0]
if self.transform=='softplus':
fval_org = fval.copy()
fval[fval_org>=40.] = np.log(fval_org[fval_org>=40.])
fval[fval_org<40.] = np.log(np.log1p(np.exp(fval_org[fval_org<40.])))
elif self.transform=='none':
fval = np.log(fval+1e-50)
fval = -fval
if X_batch is not None:
h_vals = self._hammer_function(x, X_batch, r_x0, s_x0)
fval += -h_vals.sum(axis=-1)
return fval | python | def _penalized_acquisition(self, x, model, X_batch, r_x0, s_x0):
'''
Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch
.. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable.
'''
fval = -self.acq.acquisition_function(x)[:,0]
if self.transform=='softplus':
fval_org = fval.copy()
fval[fval_org>=40.] = np.log(fval_org[fval_org>=40.])
fval[fval_org<40.] = np.log(np.log1p(np.exp(fval_org[fval_org<40.])))
elif self.transform=='none':
fval = np.log(fval+1e-50)
fval = -fval
if X_batch is not None:
h_vals = self._hammer_function(x, X_batch, r_x0, s_x0)
fval += -h_vals.sum(axis=-1)
return fval | [
"def",
"_penalized_acquisition",
"(",
"self",
",",
"x",
",",
"model",
",",
"X_batch",
",",
"r_x0",
",",
"s_x0",
")",
":",
"fval",
"=",
"-",
"self",
".",
"acq",
".",
"acquisition_function",
"(",
"x",
")",
"[",
":",
",",
"0",
"]",
"if",
"self",
".",
... | Creates a penalized acquisition function using 'hammer' functions around the points collected in the batch
.. Note:: the penalized acquisition is always mapped to the log space. This way gradients can be computed additively and are more stable. | [
"Creates",
"a",
"penalized",
"acquisition",
"function",
"using",
"hammer",
"functions",
"around",
"the",
"points",
"collected",
"in",
"the",
"batch"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L70-L89 | train | 223,036 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP.acquisition_function | def acquisition_function(self, x):
"""
Returns the value of the acquisition function at x.
"""
return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0) | python | def acquisition_function(self, x):
"""
Returns the value of the acquisition function at x.
"""
return self._penalized_acquisition(x, self.model, self.X_batch, self.r_x0, self.s_x0) | [
"def",
"acquisition_function",
"(",
"self",
",",
"x",
")",
":",
"return",
"self",
".",
"_penalized_acquisition",
"(",
"x",
",",
"self",
".",
"model",
",",
"self",
".",
"X_batch",
",",
"self",
".",
"r_x0",
",",
"self",
".",
"s_x0",
")"
] | Returns the value of the acquisition function at x. | [
"Returns",
"the",
"value",
"of",
"the",
"acquisition",
"function",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L105-L110 | train | 223,037 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP.d_acquisition_function | def d_acquisition_function(self, x):
"""
Returns the gradient of the acquisition function at x.
"""
x = np.atleast_2d(x)
if self.transform=='softplus':
fval = -self.acq.acquisition_function(x)[:,0]
scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval)))
elif self.transform=='none':
fval = -self.acq.acquisition_function(x)[:,0]
scale = 1./fval
else:
scale = 1.
if self.X_batch is None:
_, grad_acq_x = self.acq.acquisition_function_withGradients(x)
return scale*grad_acq_x
else:
_, grad_acq_x = self.acq.acquisition_function_withGradients(x)
return scale*grad_acq_x - self._d_hammer_function(x, self.X_batch, self.r_x0, self.s_x0) | python | def d_acquisition_function(self, x):
"""
Returns the gradient of the acquisition function at x.
"""
x = np.atleast_2d(x)
if self.transform=='softplus':
fval = -self.acq.acquisition_function(x)[:,0]
scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval)))
elif self.transform=='none':
fval = -self.acq.acquisition_function(x)[:,0]
scale = 1./fval
else:
scale = 1.
if self.X_batch is None:
_, grad_acq_x = self.acq.acquisition_function_withGradients(x)
return scale*grad_acq_x
else:
_, grad_acq_x = self.acq.acquisition_function_withGradients(x)
return scale*grad_acq_x - self._d_hammer_function(x, self.X_batch, self.r_x0, self.s_x0) | [
"def",
"d_acquisition_function",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"if",
"self",
".",
"transform",
"==",
"'softplus'",
":",
"fval",
"=",
"-",
"self",
".",
"acq",
".",
"acquisition_function",
"(",
"x",
... | Returns the gradient of the acquisition function at x. | [
"Returns",
"the",
"gradient",
"of",
"the",
"acquisition",
"function",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L112-L132 | train | 223,038 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LP.py | AcquisitionLP.acquisition_function_withGradients | def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return aqu_x, aqu_x_grad | python | def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return aqu_x, aqu_x_grad | [
"def",
"acquisition_function_withGradients",
"(",
"self",
",",
"x",
")",
":",
"aqu_x",
"=",
"self",
".",
"acquisition_function",
"(",
"x",
")",
"aqu_x_grad",
"=",
"self",
".",
"d_acquisition_function",
"(",
"x",
")",
"return",
"aqu_x",
",",
"aqu_x_grad"
] | Returns the acquisition function and its its gradient at x. | [
"Returns",
"the",
"acquisition",
"function",
"and",
"its",
"its",
"gradient",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L134-L140 | train | 223,039 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/base.py | AcquisitionBase.acquisition_function | def acquisition_function(self,x):
"""
Takes an acquisition and weights it so the domain and cost are taken into account.
"""
f_acqu = self._compute_acq(x)
cost_x, _ = self.cost_withGradients(x)
return -(f_acqu*self.space.indicator_constraints(x))/cost_x | python | def acquisition_function(self,x):
"""
Takes an acquisition and weights it so the domain and cost are taken into account.
"""
f_acqu = self._compute_acq(x)
cost_x, _ = self.cost_withGradients(x)
return -(f_acqu*self.space.indicator_constraints(x))/cost_x | [
"def",
"acquisition_function",
"(",
"self",
",",
"x",
")",
":",
"f_acqu",
"=",
"self",
".",
"_compute_acq",
"(",
"x",
")",
"cost_x",
",",
"_",
"=",
"self",
".",
"cost_withGradients",
"(",
"x",
")",
"return",
"-",
"(",
"f_acqu",
"*",
"self",
".",
"spa... | Takes an acquisition and weights it so the domain and cost are taken into account. | [
"Takes",
"an",
"acquisition",
"and",
"weights",
"it",
"so",
"the",
"domain",
"and",
"cost",
"are",
"taken",
"into",
"account",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L33-L39 | train | 223,040 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/base.py | AcquisitionBase.acquisition_function_withGradients | def acquisition_function_withGradients(self, x):
"""
Takes an acquisition and it gradient and weights it so the domain and cost are taken into account.
"""
f_acqu,df_acqu = self._compute_acq_withGradients(x)
cost_x, cost_grad_x = self.cost_withGradients(x)
f_acq_cost = f_acqu/cost_x
df_acq_cost = (df_acqu*cost_x - f_acqu*cost_grad_x)/(cost_x**2)
return -f_acq_cost*self.space.indicator_constraints(x), -df_acq_cost*self.space.indicator_constraints(x) | python | def acquisition_function_withGradients(self, x):
"""
Takes an acquisition and it gradient and weights it so the domain and cost are taken into account.
"""
f_acqu,df_acqu = self._compute_acq_withGradients(x)
cost_x, cost_grad_x = self.cost_withGradients(x)
f_acq_cost = f_acqu/cost_x
df_acq_cost = (df_acqu*cost_x - f_acqu*cost_grad_x)/(cost_x**2)
return -f_acq_cost*self.space.indicator_constraints(x), -df_acq_cost*self.space.indicator_constraints(x) | [
"def",
"acquisition_function_withGradients",
"(",
"self",
",",
"x",
")",
":",
"f_acqu",
",",
"df_acqu",
"=",
"self",
".",
"_compute_acq_withGradients",
"(",
"x",
")",
"cost_x",
",",
"cost_grad_x",
"=",
"self",
".",
"cost_withGradients",
"(",
"x",
")",
"f_acq_c... | Takes an acquisition and it gradient and weights it so the domain and cost are taken into account. | [
"Takes",
"an",
"acquisition",
"and",
"it",
"gradient",
"and",
"weights",
"it",
"so",
"the",
"domain",
"and",
"cost",
"are",
"taken",
"into",
"account",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L42-L50 | train | 223,041 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | reshape | def reshape(x,input_dim):
'''
Reshapes x into a matrix with input_dim columns
'''
x = np.array(x)
if x.size ==input_dim:
x = x.reshape((1,input_dim))
return x | python | def reshape(x,input_dim):
'''
Reshapes x into a matrix with input_dim columns
'''
x = np.array(x)
if x.size ==input_dim:
x = x.reshape((1,input_dim))
return x | [
"def",
"reshape",
"(",
"x",
",",
"input_dim",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"if",
"x",
".",
"size",
"==",
"input_dim",
":",
"x",
"=",
"x",
".",
"reshape",
"(",
"(",
"1",
",",
"input_dim",
")",
")",
"return",
"x"
] | Reshapes x into a matrix with input_dim columns | [
"Reshapes",
"x",
"into",
"a",
"matrix",
"with",
"input_dim",
"columns"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L76-L84 | train | 223,042 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | spawn | def spawn(f):
'''
Function for parallel evaluation of the acquisition function
'''
def fun(pipe,x):
pipe.send(f(x))
pipe.close()
return fun | python | def spawn(f):
'''
Function for parallel evaluation of the acquisition function
'''
def fun(pipe,x):
pipe.send(f(x))
pipe.close()
return fun | [
"def",
"spawn",
"(",
"f",
")",
":",
"def",
"fun",
"(",
"pipe",
",",
"x",
")",
":",
"pipe",
".",
"send",
"(",
"f",
"(",
"x",
")",
")",
"pipe",
".",
"close",
"(",
")",
"return",
"fun"
] | Function for parallel evaluation of the acquisition function | [
"Function",
"for",
"parallel",
"evaluation",
"of",
"the",
"acquisition",
"function"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L144-L151 | train | 223,043 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | values_to_array | def values_to_array(input_values):
'''
Transforms a values of int, float and tuples to a column vector numpy array
'''
if type(input_values)==tuple:
values = np.array(input_values).reshape(-1,1)
elif type(input_values) == np.ndarray:
values = np.atleast_2d(input_values)
elif type(input_values)==int or type(input_values)==float or type(np.int64):
values = np.atleast_2d(np.array(input_values))
else:
print('Type to transform not recognized')
return values | python | def values_to_array(input_values):
'''
Transforms a values of int, float and tuples to a column vector numpy array
'''
if type(input_values)==tuple:
values = np.array(input_values).reshape(-1,1)
elif type(input_values) == np.ndarray:
values = np.atleast_2d(input_values)
elif type(input_values)==int or type(input_values)==float or type(np.int64):
values = np.atleast_2d(np.array(input_values))
else:
print('Type to transform not recognized')
return values | [
"def",
"values_to_array",
"(",
"input_values",
")",
":",
"if",
"type",
"(",
"input_values",
")",
"==",
"tuple",
":",
"values",
"=",
"np",
".",
"array",
"(",
"input_values",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"elif",
"type",
"(",
"inpu... | Transforms a values of int, float and tuples to a column vector numpy array | [
"Transforms",
"a",
"values",
"of",
"int",
"float",
"and",
"tuples",
"to",
"a",
"column",
"vector",
"numpy",
"array"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L168-L180 | train | 223,044 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | merge_values | def merge_values(values1,values2):
'''
Merges two numpy arrays by calculating all possible combinations of rows
'''
array1 = values_to_array(values1)
array2 = values_to_array(values2)
if array1.size == 0:
return array2
if array2.size == 0:
return array1
merged_array = []
for row_array1 in array1:
for row_array2 in array2:
merged_row = np.hstack((row_array1,row_array2))
merged_array.append(merged_row)
return np.atleast_2d(merged_array) | python | def merge_values(values1,values2):
'''
Merges two numpy arrays by calculating all possible combinations of rows
'''
array1 = values_to_array(values1)
array2 = values_to_array(values2)
if array1.size == 0:
return array2
if array2.size == 0:
return array1
merged_array = []
for row_array1 in array1:
for row_array2 in array2:
merged_row = np.hstack((row_array1,row_array2))
merged_array.append(merged_row)
return np.atleast_2d(merged_array) | [
"def",
"merge_values",
"(",
"values1",
",",
"values2",
")",
":",
"array1",
"=",
"values_to_array",
"(",
"values1",
")",
"array2",
"=",
"values_to_array",
"(",
"values2",
")",
"if",
"array1",
".",
"size",
"==",
"0",
":",
"return",
"array2",
"if",
"array2",
... | Merges two numpy arrays by calculating all possible combinations of rows | [
"Merges",
"two",
"numpy",
"arrays",
"by",
"calculating",
"all",
"possible",
"combinations",
"of",
"rows"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L183-L200 | train | 223,045 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | normalize | def normalize(Y, normalization_type='stats'):
"""Normalize the vector Y using statistics or its range.
:param Y: Row or column vector that you want to normalize.
:param normalization_type: String specifying the kind of normalization
to use. Options are 'stats' to use mean and standard deviation,
or 'maxmin' to use the range of function values.
:return Y_normalized: The normalized vector.
"""
Y = np.asarray(Y, dtype=float)
if np.max(Y.shape) != Y.size:
raise NotImplementedError('Only 1-dimensional arrays are supported.')
# Only normalize with non null sdev (divide by zero). For only one
# data point both std and ptp return 0.
if normalization_type == 'stats':
Y_norm = Y - Y.mean()
std = Y.std()
if std > 0:
Y_norm /= std
elif normalization_type == 'maxmin':
Y_norm = Y - Y.min()
y_range = np.ptp(Y)
if y_range > 0:
Y_norm /= y_range
# A range of [-1, 1] is more natural for a zero-mean GP
Y_norm = 2 * (Y_norm - 0.5)
else:
raise ValueError('Unknown normalization type: {}'.format(normalization_type))
return Y_norm | python | def normalize(Y, normalization_type='stats'):
"""Normalize the vector Y using statistics or its range.
:param Y: Row or column vector that you want to normalize.
:param normalization_type: String specifying the kind of normalization
to use. Options are 'stats' to use mean and standard deviation,
or 'maxmin' to use the range of function values.
:return Y_normalized: The normalized vector.
"""
Y = np.asarray(Y, dtype=float)
if np.max(Y.shape) != Y.size:
raise NotImplementedError('Only 1-dimensional arrays are supported.')
# Only normalize with non null sdev (divide by zero). For only one
# data point both std and ptp return 0.
if normalization_type == 'stats':
Y_norm = Y - Y.mean()
std = Y.std()
if std > 0:
Y_norm /= std
elif normalization_type == 'maxmin':
Y_norm = Y - Y.min()
y_range = np.ptp(Y)
if y_range > 0:
Y_norm /= y_range
# A range of [-1, 1] is more natural for a zero-mean GP
Y_norm = 2 * (Y_norm - 0.5)
else:
raise ValueError('Unknown normalization type: {}'.format(normalization_type))
return Y_norm | [
"def",
"normalize",
"(",
"Y",
",",
"normalization_type",
"=",
"'stats'",
")",
":",
"Y",
"=",
"np",
".",
"asarray",
"(",
"Y",
",",
"dtype",
"=",
"float",
")",
"if",
"np",
".",
"max",
"(",
"Y",
".",
"shape",
")",
"!=",
"Y",
".",
"size",
":",
"rai... | Normalize the vector Y using statistics or its range.
:param Y: Row or column vector that you want to normalize.
:param normalization_type: String specifying the kind of normalization
to use. Options are 'stats' to use mean and standard deviation,
or 'maxmin' to use the range of function values.
:return Y_normalized: The normalized vector. | [
"Normalize",
"the",
"vector",
"Y",
"using",
"statistics",
"or",
"its",
"range",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L203-L234 | train | 223,046 |
SheffieldML/GPyOpt | GPyOpt/experiment_design/grid_design.py | GridDesign.get_samples | def get_samples(self, init_points_count):
"""
This method may return less points than requested.
The total number of generated points is the smallest closest integer of n^d to the selected amount of points.
"""
init_points_count = self._adjust_init_points_count(init_points_count)
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
X_design = multigrid(self.space.get_continuous_bounds(), self.data_per_dimension)
samples[:,self.space.get_continuous_dims()] = X_design
return samples | python | def get_samples(self, init_points_count):
"""
This method may return less points than requested.
The total number of generated points is the smallest closest integer of n^d to the selected amount of points.
"""
init_points_count = self._adjust_init_points_count(init_points_count)
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
X_design = multigrid(self.space.get_continuous_bounds(), self.data_per_dimension)
samples[:,self.space.get_continuous_dims()] = X_design
return samples | [
"def",
"get_samples",
"(",
"self",
",",
"init_points_count",
")",
":",
"init_points_count",
"=",
"self",
".",
"_adjust_init_points_count",
"(",
"init_points_count",
")",
"samples",
"=",
"np",
".",
"empty",
"(",
"(",
"init_points_count",
",",
"self",
".",
"space"... | This method may return less points than requested.
The total number of generated points is the smallest closest integer of n^d to the selected amount of points. | [
"This",
"method",
"may",
"return",
"less",
"points",
"than",
"requested",
".",
"The",
"total",
"number",
"of",
"generated",
"points",
"is",
"the",
"smallest",
"closest",
"integer",
"of",
"n^d",
"to",
"the",
"selected",
"amount",
"of",
"points",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/grid_design.py#L26-L43 | train | 223,047 |
SheffieldML/GPyOpt | GPyOpt/experiment_design/random_design.py | RandomDesign.get_samples_with_constraints | def get_samples_with_constraints(self, init_points_count):
"""
Draw random samples and only save those that satisfy constraints
Finish when required number of samples is generated
"""
samples = np.empty((0, self.space.dimensionality))
while samples.shape[0] < init_points_count:
domain_samples = self.get_samples_without_constraints(init_points_count)
valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten()
if sum(valid_indices) > 0:
valid_samples = domain_samples[valid_indices,:]
samples = np.vstack((samples,valid_samples))
return samples[0:init_points_count,:] | python | def get_samples_with_constraints(self, init_points_count):
"""
Draw random samples and only save those that satisfy constraints
Finish when required number of samples is generated
"""
samples = np.empty((0, self.space.dimensionality))
while samples.shape[0] < init_points_count:
domain_samples = self.get_samples_without_constraints(init_points_count)
valid_indices = (self.space.indicator_constraints(domain_samples) == 1).flatten()
if sum(valid_indices) > 0:
valid_samples = domain_samples[valid_indices,:]
samples = np.vstack((samples,valid_samples))
return samples[0:init_points_count,:] | [
"def",
"get_samples_with_constraints",
"(",
"self",
",",
"init_points_count",
")",
":",
"samples",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"self",
".",
"space",
".",
"dimensionality",
")",
")",
"while",
"samples",
".",
"shape",
"[",
"0",
"]",
"<",
... | Draw random samples and only save those that satisfy constraints
Finish when required number of samples is generated | [
"Draw",
"random",
"samples",
"and",
"only",
"save",
"those",
"that",
"satisfy",
"constraints",
"Finish",
"when",
"required",
"number",
"of",
"samples",
"is",
"generated"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L21-L35 | train | 223,048 |
SheffieldML/GPyOpt | GPyOpt/experiment_design/random_design.py | RandomDesign.fill_noncontinous_variables | def fill_noncontinous_variables(self, samples):
"""
Fill sample values to non-continuous variables in place
"""
init_points_count = samples.shape[0]
for (idx, var) in enumerate(self.space.space_expanded):
if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) :
sample_var = np.atleast_2d(np.random.choice(var.domain, init_points_count))
samples[:,idx] = sample_var.flatten()
# sample in the case of bandit variables
elif isinstance(var, BanditVariable):
# Bandit variable is represented by a several adjacent columns in the samples array
idx_samples = np.random.randint(var.domain.shape[0], size=init_points_count)
bandit_idx = np.arange(idx, idx + var.domain.shape[1])
samples[:, bandit_idx] = var.domain[idx_samples,:] | python | def fill_noncontinous_variables(self, samples):
"""
Fill sample values to non-continuous variables in place
"""
init_points_count = samples.shape[0]
for (idx, var) in enumerate(self.space.space_expanded):
if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) :
sample_var = np.atleast_2d(np.random.choice(var.domain, init_points_count))
samples[:,idx] = sample_var.flatten()
# sample in the case of bandit variables
elif isinstance(var, BanditVariable):
# Bandit variable is represented by a several adjacent columns in the samples array
idx_samples = np.random.randint(var.domain.shape[0], size=init_points_count)
bandit_idx = np.arange(idx, idx + var.domain.shape[1])
samples[:, bandit_idx] = var.domain[idx_samples,:] | [
"def",
"fill_noncontinous_variables",
"(",
"self",
",",
"samples",
")",
":",
"init_points_count",
"=",
"samples",
".",
"shape",
"[",
"0",
"]",
"for",
"(",
"idx",
",",
"var",
")",
"in",
"enumerate",
"(",
"self",
".",
"space",
".",
"space_expanded",
")",
"... | Fill sample values to non-continuous variables in place | [
"Fill",
"sample",
"values",
"to",
"non",
"-",
"continuous",
"variables",
"in",
"place"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L37-L53 | train | 223,049 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._get_obj | def _get_obj(self,space):
"""
Imports the acquisition function.
"""
obj_func = self.obj_func
from ..core.task import SingleObjective
return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True) | python | def _get_obj(self,space):
"""
Imports the acquisition function.
"""
obj_func = self.obj_func
from ..core.task import SingleObjective
return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True) | [
"def",
"_get_obj",
"(",
"self",
",",
"space",
")",
":",
"obj_func",
"=",
"self",
".",
"obj_func",
"from",
".",
".",
"core",
".",
"task",
"import",
"SingleObjective",
"return",
"SingleObjective",
"(",
"obj_func",
",",
"self",
".",
"config",
"[",
"'resources... | Imports the acquisition function. | [
"Imports",
"the",
"acquisition",
"function",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L24-L32 | train | 223,050 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._get_space | def _get_space(self):
"""
Imports the domain.
"""
assert 'space' in self.config, 'The search space is NOT configured!'
space_config = self.config['space']
constraint_config = self.config['constraints']
from ..core.task.space import Design_space
return Design_space.fromConfig(space_config, constraint_config) | python | def _get_space(self):
"""
Imports the domain.
"""
assert 'space' in self.config, 'The search space is NOT configured!'
space_config = self.config['space']
constraint_config = self.config['constraints']
from ..core.task.space import Design_space
return Design_space.fromConfig(space_config, constraint_config) | [
"def",
"_get_space",
"(",
"self",
")",
":",
"assert",
"'space'",
"in",
"self",
".",
"config",
",",
"'The search space is NOT configured!'",
"space_config",
"=",
"self",
".",
"config",
"[",
"'space'",
"]",
"constraint_config",
"=",
"self",
".",
"config",
"[",
"... | Imports the domain. | [
"Imports",
"the",
"domain",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L34-L43 | train | 223,051 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._get_model | def _get_model(self):
"""
Imports the model.
"""
from copy import deepcopy
model_args = deepcopy(self.config['model'])
del model_args['type']
from ..models import select_model
return select_model(self.config['model']['type']).fromConfig(model_args) | python | def _get_model(self):
"""
Imports the model.
"""
from copy import deepcopy
model_args = deepcopy(self.config['model'])
del model_args['type']
from ..models import select_model
return select_model(self.config['model']['type']).fromConfig(model_args) | [
"def",
"_get_model",
"(",
"self",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"model_args",
"=",
"deepcopy",
"(",
"self",
".",
"config",
"[",
"'model'",
"]",
")",
"del",
"model_args",
"[",
"'type'",
"]",
"from",
".",
".",
"models",
"import",
"select_... | Imports the model. | [
"Imports",
"the",
"model",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L45-L55 | train | 223,052 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._get_acquisition | def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])
acqOpt_name = acqOpt_config['name']
del acqOpt_config['name']
from ..optimization import AcquisitionOptimizer
acqOpt = AcquisitionOptimizer(space, acqOpt_name, **acqOpt_config)
from ..acquisitions import select_acquisition
return select_acquisition(self.config['acquisition']['type']).fromConfig(model, space, acqOpt, None, self.config['acquisition']) | python | def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])
acqOpt_name = acqOpt_config['name']
del acqOpt_config['name']
from ..optimization import AcquisitionOptimizer
acqOpt = AcquisitionOptimizer(space, acqOpt_name, **acqOpt_config)
from ..acquisitions import select_acquisition
return select_acquisition(self.config['acquisition']['type']).fromConfig(model, space, acqOpt, None, self.config['acquisition']) | [
"def",
"_get_acquisition",
"(",
"self",
",",
"model",
",",
"space",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"acqOpt_config",
"=",
"deepcopy",
"(",
"self",
".",
"config",
"[",
"'acquisition'",
"]",
"[",
"'optimizer'",
"]",
")",
"acqOpt_name",
"=",
"... | Imports the acquisition | [
"Imports",
"the",
"acquisition"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L58-L71 | train | 223,053 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._get_acq_evaluator | def _get_acq_evaluator(self, acq):
"""
Imports the evaluator
"""
from ..core.evaluators import select_evaluator
from copy import deepcopy
eval_args = deepcopy(self.config['acquisition']['evaluator'])
del eval_args['type']
return select_evaluator(self.config['acquisition']['evaluator']['type'])(acq, **eval_args) | python | def _get_acq_evaluator(self, acq):
"""
Imports the evaluator
"""
from ..core.evaluators import select_evaluator
from copy import deepcopy
eval_args = deepcopy(self.config['acquisition']['evaluator'])
del eval_args['type']
return select_evaluator(self.config['acquisition']['evaluator']['type'])(acq, **eval_args) | [
"def",
"_get_acq_evaluator",
"(",
"self",
",",
"acq",
")",
":",
"from",
".",
".",
"core",
".",
"evaluators",
"import",
"select_evaluator",
"from",
"copy",
"import",
"deepcopy",
"eval_args",
"=",
"deepcopy",
"(",
"self",
".",
"config",
"[",
"'acquisition'",
"... | Imports the evaluator | [
"Imports",
"the",
"evaluator"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L73-L82 | train | 223,054 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver._check_stop | def _check_stop(self, iters, elapsed_time, converged):
"""
Defines the stopping criterion.
"""
r_c = self.config['resources']
stop = False
if converged==0:
stop=True
if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']:
stop = True
if r_c['max-run-time'] != 'NA' and elapsed_time/60.>= r_c['max-run-time']:
stop = True
return stop | python | def _check_stop(self, iters, elapsed_time, converged):
"""
Defines the stopping criterion.
"""
r_c = self.config['resources']
stop = False
if converged==0:
stop=True
if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']:
stop = True
if r_c['max-run-time'] != 'NA' and elapsed_time/60.>= r_c['max-run-time']:
stop = True
return stop | [
"def",
"_check_stop",
"(",
"self",
",",
"iters",
",",
"elapsed_time",
",",
"converged",
")",
":",
"r_c",
"=",
"self",
".",
"config",
"[",
"'resources'",
"]",
"stop",
"=",
"False",
"if",
"converged",
"==",
"0",
":",
"stop",
"=",
"True",
"if",
"r_c",
"... | Defines the stopping criterion. | [
"Defines",
"the",
"stopping",
"criterion",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L84-L98 | train | 223,055 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | BODriver.run | def run(self):
"""
Runs the optimization using the previously loaded elements.
"""
space = self._get_space()
obj_func = self._get_obj(space)
model = self._get_model()
acq = self._get_acquisition(model, space)
acq_eval = self._get_acq_evaluator(acq)
from ..experiment_design import initial_design
X_init = initial_design(self.config['initialization']['type'], space, self.config['initialization']['num-eval'])
from ..methods import ModularBayesianOptimization
bo = ModularBayesianOptimization(model, space, obj_func, acq, acq_eval, X_init)
bo.run_optimization(max_iter = self.config['resources']['maximum-iterations'], max_time = self.config['resources']['max-run-time'] if self.config['resources']['max-run-time']!="NA" else np.inf,
eps = self.config['resources']['tolerance'], verbosity=True)
return bo | python | def run(self):
"""
Runs the optimization using the previously loaded elements.
"""
space = self._get_space()
obj_func = self._get_obj(space)
model = self._get_model()
acq = self._get_acquisition(model, space)
acq_eval = self._get_acq_evaluator(acq)
from ..experiment_design import initial_design
X_init = initial_design(self.config['initialization']['type'], space, self.config['initialization']['num-eval'])
from ..methods import ModularBayesianOptimization
bo = ModularBayesianOptimization(model, space, obj_func, acq, acq_eval, X_init)
bo.run_optimization(max_iter = self.config['resources']['maximum-iterations'], max_time = self.config['resources']['max-run-time'] if self.config['resources']['max-run-time']!="NA" else np.inf,
eps = self.config['resources']['tolerance'], verbosity=True)
return bo | [
"def",
"run",
"(",
"self",
")",
":",
"space",
"=",
"self",
".",
"_get_space",
"(",
")",
"obj_func",
"=",
"self",
".",
"_get_obj",
"(",
"space",
")",
"model",
"=",
"self",
".",
"_get_model",
"(",
")",
"acq",
"=",
"self",
".",
"_get_acquisition",
"(",
... | Runs the optimization using the previously loaded elements. | [
"Runs",
"the",
"optimization",
"using",
"the",
"previously",
"loaded",
"elements",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L100-L119 | train | 223,056 |
SheffieldML/GPyOpt | GPyOpt/optimization/optimizer.py | choose_optimizer | def choose_optimizer(optimizer_name, bounds):
"""
Selects the type of local optimizer
"""
if optimizer_name == 'lbfgs':
optimizer = OptLbfgs(bounds)
elif optimizer_name == 'DIRECT':
optimizer = OptDirect(bounds)
elif optimizer_name == 'CMA':
optimizer = OptCma(bounds)
else:
raise InvalidVariableNameError('Invalid optimizer selected.')
return optimizer | python | def choose_optimizer(optimizer_name, bounds):
"""
Selects the type of local optimizer
"""
if optimizer_name == 'lbfgs':
optimizer = OptLbfgs(bounds)
elif optimizer_name == 'DIRECT':
optimizer = OptDirect(bounds)
elif optimizer_name == 'CMA':
optimizer = OptCma(bounds)
else:
raise InvalidVariableNameError('Invalid optimizer selected.')
return optimizer | [
"def",
"choose_optimizer",
"(",
"optimizer_name",
",",
"bounds",
")",
":",
"if",
"optimizer_name",
"==",
"'lbfgs'",
":",
"optimizer",
"=",
"OptLbfgs",
"(",
"bounds",
")",
"elif",
"optimizer_name",
"==",
"'DIRECT'",
":",
"optimizer",
"=",
"OptDirect",
"(",
"bou... | Selects the type of local optimizer | [
"Selects",
"the",
"type",
"of",
"local",
"optimizer"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/optimization/optimizer.py#L238-L253 | train | 223,057 |
SheffieldML/GPyOpt | GPyOpt/util/arguments_manager.py | ArgumentsManager.evaluator_creator | def evaluator_creator(self, evaluator_type, acquisition, batch_size, model_type, model, space, acquisition_optimizer):
"""
Acquisition chooser from the available options. Guide the optimization through sequential or parallel evalutions of the objective.
"""
acquisition_transformation = self.kwargs.get('acquisition_transformation','none')
if batch_size == 1 or evaluator_type == 'sequential':
return Sequential(acquisition)
elif batch_size >1 and (evaluator_type == 'random' or evaluator_type is None):
return RandomBatch(acquisition, batch_size)
elif batch_size >1 and evaluator_type == 'thompson_sampling':
return ThompsonBatch(acquisition, batch_size)
elif evaluator_type == 'local_penalization':
if model_type not in ['GP', 'sparseGP', 'GP_MCMC', 'warpedGP']:
raise InvalidConfigError('local_penalization evaluator can only be used with GP models')
if not isinstance(acquisition, AcquisitionLP):
acquisition_lp = AcquisitionLP(model, space, acquisition_optimizer, acquisition, acquisition_transformation)
return LocalPenalization(acquisition_lp, batch_size) | python | def evaluator_creator(self, evaluator_type, acquisition, batch_size, model_type, model, space, acquisition_optimizer):
"""
Acquisition chooser from the available options. Guide the optimization through sequential or parallel evalutions of the objective.
"""
acquisition_transformation = self.kwargs.get('acquisition_transformation','none')
if batch_size == 1 or evaluator_type == 'sequential':
return Sequential(acquisition)
elif batch_size >1 and (evaluator_type == 'random' or evaluator_type is None):
return RandomBatch(acquisition, batch_size)
elif batch_size >1 and evaluator_type == 'thompson_sampling':
return ThompsonBatch(acquisition, batch_size)
elif evaluator_type == 'local_penalization':
if model_type not in ['GP', 'sparseGP', 'GP_MCMC', 'warpedGP']:
raise InvalidConfigError('local_penalization evaluator can only be used with GP models')
if not isinstance(acquisition, AcquisitionLP):
acquisition_lp = AcquisitionLP(model, space, acquisition_optimizer, acquisition, acquisition_transformation)
return LocalPenalization(acquisition_lp, batch_size) | [
"def",
"evaluator_creator",
"(",
"self",
",",
"evaluator_type",
",",
"acquisition",
",",
"batch_size",
",",
"model_type",
",",
"model",
",",
"space",
",",
"acquisition_optimizer",
")",
":",
"acquisition_transformation",
"=",
"self",
".",
"kwargs",
".",
"get",
"(... | Acquisition chooser from the available options. Guide the optimization through sequential or parallel evalutions of the objective. | [
"Acquisition",
"chooser",
"from",
"the",
"available",
"options",
".",
"Guide",
"the",
"optimization",
"through",
"sequential",
"or",
"parallel",
"evalutions",
"of",
"the",
"objective",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/arguments_manager.py#L17-L38 | train | 223,058 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LCB.py | AcquisitionLCB._compute_acq | def _compute_acq(self, x):
"""
Computes the GP-Lower Confidence Bound
"""
m, s = self.model.predict(x)
f_acqu = -m + self.exploration_weight * s
return f_acqu | python | def _compute_acq(self, x):
"""
Computes the GP-Lower Confidence Bound
"""
m, s = self.model.predict(x)
f_acqu = -m + self.exploration_weight * s
return f_acqu | [
"def",
"_compute_acq",
"(",
"self",
",",
"x",
")",
":",
"m",
",",
"s",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"x",
")",
"f_acqu",
"=",
"-",
"m",
"+",
"self",
".",
"exploration_weight",
"*",
"s",
"return",
"f_acqu"
] | Computes the GP-Lower Confidence Bound | [
"Computes",
"the",
"GP",
"-",
"Lower",
"Confidence",
"Bound"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB.py#L31-L37 | train | 223,059 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LCB.py | AcquisitionLCB._compute_acq_withGradients | def _compute_acq_withGradients(self, x):
"""
Computes the GP-Lower Confidence Bound and its derivative
"""
m, s, dmdx, dsdx = self.model.predict_withGradients(x)
f_acqu = -m + self.exploration_weight * s
df_acqu = -dmdx + self.exploration_weight * dsdx
return f_acqu, df_acqu | python | def _compute_acq_withGradients(self, x):
"""
Computes the GP-Lower Confidence Bound and its derivative
"""
m, s, dmdx, dsdx = self.model.predict_withGradients(x)
f_acqu = -m + self.exploration_weight * s
df_acqu = -dmdx + self.exploration_weight * dsdx
return f_acqu, df_acqu | [
"def",
"_compute_acq_withGradients",
"(",
"self",
",",
"x",
")",
":",
"m",
",",
"s",
",",
"dmdx",
",",
"dsdx",
"=",
"self",
".",
"model",
".",
"predict_withGradients",
"(",
"x",
")",
"f_acqu",
"=",
"-",
"m",
"+",
"self",
".",
"exploration_weight",
"*",... | Computes the GP-Lower Confidence Bound and its derivative | [
"Computes",
"the",
"GP",
"-",
"Lower",
"Confidence",
"Bound",
"and",
"its",
"derivative"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB.py#L39-L46 | train | 223,060 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | create_variable | def create_variable(descriptor):
"""
Creates a variable from a dictionary descriptor
"""
if descriptor['type'] == 'continuous':
return ContinuousVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
elif descriptor['type'] == 'bandit':
return BanditVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', None)) # bandits variables cannot be repeated
elif descriptor['type'] == 'discrete':
return DiscreteVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
elif descriptor['type'] == 'categorical':
return CategoricalVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
else:
raise InvalidConfigError('Unknown variable type ' + descriptor['type']) | python | def create_variable(descriptor):
"""
Creates a variable from a dictionary descriptor
"""
if descriptor['type'] == 'continuous':
return ContinuousVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
elif descriptor['type'] == 'bandit':
return BanditVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', None)) # bandits variables cannot be repeated
elif descriptor['type'] == 'discrete':
return DiscreteVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
elif descriptor['type'] == 'categorical':
return CategoricalVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1))
else:
raise InvalidConfigError('Unknown variable type ' + descriptor['type']) | [
"def",
"create_variable",
"(",
"descriptor",
")",
":",
"if",
"descriptor",
"[",
"'type'",
"]",
"==",
"'continuous'",
":",
"return",
"ContinuousVariable",
"(",
"descriptor",
"[",
"'name'",
"]",
",",
"descriptor",
"[",
"'domain'",
"]",
",",
"descriptor",
".",
... | Creates a variable from a dictionary descriptor | [
"Creates",
"a",
"variable",
"from",
"a",
"dictionary",
"descriptor"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L230-L243 | train | 223,061 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | Variable.expand | def expand(self):
"""
Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, each representing a single dimension
continuous {0<=x<=1, 2<=y<=3} -> continuous {0<=x<=1}, continuous {2<=y<=3}
"""
expanded_variables = []
for i in range(self.dimensionality):
one_d_variable = deepcopy(self)
one_d_variable.dimensionality = 1
if self.dimensionality > 1:
one_d_variable.name = '{}_{}'.format(self.name, i+1)
else:
one_d_variable.name = self.name
one_d_variable.dimensionality_in_model = 1
expanded_variables.append(one_d_variable)
return expanded_variables | python | def expand(self):
"""
Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, each representing a single dimension
continuous {0<=x<=1, 2<=y<=3} -> continuous {0<=x<=1}, continuous {2<=y<=3}
"""
expanded_variables = []
for i in range(self.dimensionality):
one_d_variable = deepcopy(self)
one_d_variable.dimensionality = 1
if self.dimensionality > 1:
one_d_variable.name = '{}_{}'.format(self.name, i+1)
else:
one_d_variable.name = self.name
one_d_variable.dimensionality_in_model = 1
expanded_variables.append(one_d_variable)
return expanded_variables | [
"def",
"expand",
"(",
"self",
")",
":",
"expanded_variables",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"dimensionality",
")",
":",
"one_d_variable",
"=",
"deepcopy",
"(",
"self",
")",
"one_d_variable",
".",
"dimensionality",
"=",
"1",
... | Builds a list of single dimensional variables representing current variable.
Examples:
For single dimensional variable, it is returned as is
discrete of (0,2,4) -> discrete of (0,2,4)
For multi dimensional variable, a list of variables is returned, each representing a single dimension
continuous {0<=x<=1, 2<=y<=3} -> continuous {0<=x<=1}, continuous {2<=y<=3} | [
"Builds",
"a",
"list",
"of",
"single",
"dimensional",
"variables",
"representing",
"current",
"variable",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L16-L36 | train | 223,062 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | ContinuousVariable.round | def round(self, value_array):
"""
If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input.
"""
min_value = self.domain[0]
max_value = self.domain[1]
rounded_value = value_array[0]
if rounded_value < min_value:
rounded_value = min_value
elif rounded_value > max_value:
rounded_value = max_value
return [rounded_value] | python | def round(self, value_array):
"""
If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input.
"""
min_value = self.domain[0]
max_value = self.domain[1]
rounded_value = value_array[0]
if rounded_value < min_value:
rounded_value = min_value
elif rounded_value > max_value:
rounded_value = max_value
return [rounded_value] | [
"def",
"round",
"(",
"self",
",",
"value_array",
")",
":",
"min_value",
"=",
"self",
".",
"domain",
"[",
"0",
"]",
"max_value",
"=",
"self",
".",
"domain",
"[",
"1",
"]",
"rounded_value",
"=",
"value_array",
"[",
"0",
"]",
"if",
"rounded_value",
"<",
... | If value falls within bounds, just return it
otherwise return min or max, whichever is closer to the value
Assumes an 1d array with a single element as an input. | [
"If",
"value",
"falls",
"within",
"bounds",
"just",
"return",
"it",
"otherwise",
"return",
"min",
"or",
"max",
"whichever",
"is",
"closer",
"to",
"the",
"value",
"Assumes",
"an",
"1d",
"array",
"with",
"a",
"single",
"element",
"as",
"an",
"input",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L100-L116 | train | 223,063 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | BanditVariable.round | def round(self, value_array):
"""
Rounds a bandit variable by selecting the closest point in the domain
Closest here is defined by euclidian distance
Assumes an 1d array of the same length as the single variable value
"""
distances = np.linalg.norm(np.array(self.domain) - value_array, axis=1)
idx = np.argmin(distances)
return [self.domain[idx]] | python | def round(self, value_array):
"""
Rounds a bandit variable by selecting the closest point in the domain
Closest here is defined by euclidian distance
Assumes an 1d array of the same length as the single variable value
"""
distances = np.linalg.norm(np.array(self.domain) - value_array, axis=1)
idx = np.argmin(distances)
return [self.domain[idx]] | [
"def",
"round",
"(",
"self",
",",
"value_array",
")",
":",
"distances",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"array",
"(",
"self",
".",
"domain",
")",
"-",
"value_array",
",",
"axis",
"=",
"1",
")",
"idx",
"=",
"np",
".",
"argmi... | Rounds a bandit variable by selecting the closest point in the domain
Closest here is defined by euclidian distance
Assumes an 1d array of the same length as the single variable value | [
"Rounds",
"a",
"bandit",
"variable",
"by",
"selecting",
"the",
"closest",
"point",
"in",
"the",
"domain",
"Closest",
"here",
"is",
"defined",
"by",
"euclidian",
"distance",
"Assumes",
"an",
"1d",
"array",
"of",
"the",
"same",
"length",
"as",
"the",
"single",... | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L151-L159 | train | 223,064 |
SheffieldML/GPyOpt | GPyOpt/core/task/variables.py | DiscreteVariable.round | def round(self, value_array):
"""
Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input.
"""
value = value_array[0]
rounded_value = self.domain[0]
for domain_value in self.domain:
if np.abs(domain_value - value) < np.abs(rounded_value - value):
rounded_value = domain_value
return [rounded_value] | python | def round(self, value_array):
"""
Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input.
"""
value = value_array[0]
rounded_value = self.domain[0]
for domain_value in self.domain:
if np.abs(domain_value - value) < np.abs(rounded_value - value):
rounded_value = domain_value
return [rounded_value] | [
"def",
"round",
"(",
"self",
",",
"value_array",
")",
":",
"value",
"=",
"value_array",
"[",
"0",
"]",
"rounded_value",
"=",
"self",
".",
"domain",
"[",
"0",
"]",
"for",
"domain_value",
"in",
"self",
".",
"domain",
":",
"if",
"np",
".",
"abs",
"(",
... | Rounds a discrete variable by selecting the closest point in the domain
Assumes an 1d array with a single element as an input. | [
"Rounds",
"a",
"discrete",
"variable",
"by",
"selecting",
"the",
"closest",
"point",
"in",
"the",
"domain",
"Assumes",
"an",
"1d",
"array",
"with",
"a",
"single",
"element",
"as",
"an",
"input",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L175-L187 | train | 223,065 |
SheffieldML/GPyOpt | GPyOpt/optimization/acquisition_optimizer.py | AcquisitionOptimizer.optimize | def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None):
"""
Optimizes the input function.
:param f: function to optimize.
:param df: gradient of the function to optimize.
:param f_df: returns both the function to optimize and its gradient.
"""
self.f = f
self.df = df
self.f_df = f_df
## --- Update the optimizer, in case context has beee passed.
self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)
## --- Selecting the anchor points and removing duplicates
if self.type_anchor_points_logic == max_objective_anchor_points_logic:
anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f)
elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:
anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)
## -- Select the anchor points (with context)
anchor_points = anchor_points_generator.get(duplicate_manager=duplicate_manager, context_manager=self.context_manager)
## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)
optimized_points = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points]
x_min, fx_min = min(optimized_points, key=lambda t:t[1])
#x_min, fx_min = min([apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points], key=lambda t:t[1])
return x_min, fx_min | python | def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None):
"""
Optimizes the input function.
:param f: function to optimize.
:param df: gradient of the function to optimize.
:param f_df: returns both the function to optimize and its gradient.
"""
self.f = f
self.df = df
self.f_df = f_df
## --- Update the optimizer, in case context has beee passed.
self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds)
## --- Selecting the anchor points and removing duplicates
if self.type_anchor_points_logic == max_objective_anchor_points_logic:
anchor_points_generator = ObjectiveAnchorPointsGenerator(self.space, random_design_type, f)
elif self.type_anchor_points_logic == thompson_sampling_anchor_points_logic:
anchor_points_generator = ThompsonSamplingAnchorPointsGenerator(self.space, sobol_design_type, self.model)
## -- Select the anchor points (with context)
anchor_points = anchor_points_generator.get(duplicate_manager=duplicate_manager, context_manager=self.context_manager)
## --- Applying local optimizers at the anchor points and update bounds of the optimizer (according to the context)
optimized_points = [apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points]
x_min, fx_min = min(optimized_points, key=lambda t:t[1])
#x_min, fx_min = min([apply_optimizer(self.optimizer, a, f=f, df=None, f_df=f_df, duplicate_manager=duplicate_manager, context_manager=self.context_manager, space = self.space) for a in anchor_points], key=lambda t:t[1])
return x_min, fx_min | [
"def",
"optimize",
"(",
"self",
",",
"f",
"=",
"None",
",",
"df",
"=",
"None",
",",
"f_df",
"=",
"None",
",",
"duplicate_manager",
"=",
"None",
")",
":",
"self",
".",
"f",
"=",
"f",
"self",
".",
"df",
"=",
"df",
"self",
".",
"f_df",
"=",
"f_df"... | Optimizes the input function.
:param f: function to optimize.
:param df: gradient of the function to optimize.
:param f_df: returns both the function to optimize and its gradient. | [
"Optimizes",
"the",
"input",
"function",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/optimization/acquisition_optimizer.py#L46-L77 | train | 223,066 |
SheffieldML/GPyOpt | GPyOpt/core/task/objective.py | SingleObjective.evaluate | def evaluate(self, x):
"""
Performs the evaluation of the objective at x.
"""
if self.n_procs == 1:
f_evals, cost_evals = self._eval_func(x)
else:
try:
f_evals, cost_evals = self._syncronous_batch_evaluation(x)
except:
if not hasattr(self, 'parallel_error'):
print('Error in parallel computation. Fall back to single process!')
else:
self.parallel_error = True
f_evals, cost_evals = self._eval_func(x)
return f_evals, cost_evals | python | def evaluate(self, x):
"""
Performs the evaluation of the objective at x.
"""
if self.n_procs == 1:
f_evals, cost_evals = self._eval_func(x)
else:
try:
f_evals, cost_evals = self._syncronous_batch_evaluation(x)
except:
if not hasattr(self, 'parallel_error'):
print('Error in parallel computation. Fall back to single process!')
else:
self.parallel_error = True
f_evals, cost_evals = self._eval_func(x)
return f_evals, cost_evals | [
"def",
"evaluate",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"n_procs",
"==",
"1",
":",
"f_evals",
",",
"cost_evals",
"=",
"self",
".",
"_eval_func",
"(",
"x",
")",
"else",
":",
"try",
":",
"f_evals",
",",
"cost_evals",
"=",
"self",
".",
... | Performs the evaluation of the objective at x. | [
"Performs",
"the",
"evaluation",
"of",
"the",
"objective",
"at",
"x",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/objective.py#L44-L61 | train | 223,067 |
SheffieldML/GPyOpt | GPyOpt/core/task/objective.py | SingleObjective._syncronous_batch_evaluation | def _syncronous_batch_evaluation(self,x):
"""
Evaluates the function a x, where x can be a single location or a batch. The evaluation is performed in parallel
according to the number of accessible cores.
"""
from multiprocessing import Process, Pipe
# --- parallel evaluation of the function
divided_samples = [x[i::self.n_procs] for i in range(self.n_procs)]
pipe = [Pipe() for i in range(self.n_procs)]
proc = [Process(target=spawn(self._eval_func),args=(c,k)) for k,(p,c) in zip(divided_samples,pipe)]
[p.start() for p in proc]
[p.join() for p in proc]
# --- time of evaluation is set to constant (=1). This is one of the hypothesis of synchronous batch methods.
f_evals = np.zeros((x.shape[0],1))
cost_evals = np.ones((x.shape[0],1))
i = 0
for (p,c) in pipe:
f_evals[i::self.n_procs] = p.recv()[0] # throw away costs
i += 1
return f_evals, cost_evals | python | def _syncronous_batch_evaluation(self,x):
"""
Evaluates the function a x, where x can be a single location or a batch. The evaluation is performed in parallel
according to the number of accessible cores.
"""
from multiprocessing import Process, Pipe
# --- parallel evaluation of the function
divided_samples = [x[i::self.n_procs] for i in range(self.n_procs)]
pipe = [Pipe() for i in range(self.n_procs)]
proc = [Process(target=spawn(self._eval_func),args=(c,k)) for k,(p,c) in zip(divided_samples,pipe)]
[p.start() for p in proc]
[p.join() for p in proc]
# --- time of evaluation is set to constant (=1). This is one of the hypothesis of synchronous batch methods.
f_evals = np.zeros((x.shape[0],1))
cost_evals = np.ones((x.shape[0],1))
i = 0
for (p,c) in pipe:
f_evals[i::self.n_procs] = p.recv()[0] # throw away costs
i += 1
return f_evals, cost_evals | [
"def",
"_syncronous_batch_evaluation",
"(",
"self",
",",
"x",
")",
":",
"from",
"multiprocessing",
"import",
"Process",
",",
"Pipe",
"# --- parallel evaluation of the function",
"divided_samples",
"=",
"[",
"x",
"[",
"i",
":",
":",
"self",
".",
"n_procs",
"]",
"... | Evaluates the function a x, where x can be a single location or a batch. The evaluation is performed in parallel
according to the number of accessible cores. | [
"Evaluates",
"the",
"function",
"a",
"x",
"where",
"x",
"can",
"be",
"a",
"single",
"location",
"or",
"a",
"batch",
".",
"The",
"evaluation",
"is",
"performed",
"in",
"parallel",
"according",
"to",
"the",
"number",
"of",
"accessible",
"cores",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/objective.py#L80-L101 | train | 223,068 |
SheffieldML/GPyOpt | GPyOpt/core/evaluators/sequential.py | Sequential.compute_batch | def compute_batch(self, duplicate_manager=None,context_manager=None):
"""
Selects the new location to evaluate the objective.
"""
x, _ = self.acquisition.optimize(duplicate_manager=duplicate_manager)
return x | python | def compute_batch(self, duplicate_manager=None,context_manager=None):
"""
Selects the new location to evaluate the objective.
"""
x, _ = self.acquisition.optimize(duplicate_manager=duplicate_manager)
return x | [
"def",
"compute_batch",
"(",
"self",
",",
"duplicate_manager",
"=",
"None",
",",
"context_manager",
"=",
"None",
")",
":",
"x",
",",
"_",
"=",
"self",
".",
"acquisition",
".",
"optimize",
"(",
"duplicate_manager",
"=",
"duplicate_manager",
")",
"return",
"x"... | Selects the new location to evaluate the objective. | [
"Selects",
"the",
"new",
"location",
"to",
"evaluate",
"the",
"objective",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/evaluators/sequential.py#L18-L23 | train | 223,069 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LCB_mcmc.py | AcquisitionLCB_MCMC._compute_acq | def _compute_acq(self,x):
"""
Integrated GP-Lower Confidence Bound
"""
means, stds = self.model.predict(x)
f_acqu = 0
for m,s in zip(means, stds):
f_acqu += -m + self.exploration_weight * s
return f_acqu/(len(means)) | python | def _compute_acq(self,x):
"""
Integrated GP-Lower Confidence Bound
"""
means, stds = self.model.predict(x)
f_acqu = 0
for m,s in zip(means, stds):
f_acqu += -m + self.exploration_weight * s
return f_acqu/(len(means)) | [
"def",
"_compute_acq",
"(",
"self",
",",
"x",
")",
":",
"means",
",",
"stds",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"x",
")",
"f_acqu",
"=",
"0",
"for",
"m",
",",
"s",
"in",
"zip",
"(",
"means",
",",
"stds",
")",
":",
"f_acqu",
"+=",
... | Integrated GP-Lower Confidence Bound | [
"Integrated",
"GP",
"-",
"Lower",
"Confidence",
"Bound"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB_mcmc.py#L26-L34 | train | 223,070 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/LCB_mcmc.py | AcquisitionLCB_MCMC._compute_acq_withGradients | def _compute_acq_withGradients(self, x):
"""
Integrated GP-Lower Confidence Bound and its derivative
"""
means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x)
f_acqu = None
df_acqu = None
for m, s, dmdx, dsdx in zip(means, stds, dmdxs, dsdxs):
f = -m + self.exploration_weight * s
df = -dmdx + self.exploration_weight * dsdx
if f_acqu is None:
f_acqu = f
df_acqu = df
else:
f_acqu += f
df_acqu += df
return f_acqu/(len(means)), df_acqu/(len(means)) | python | def _compute_acq_withGradients(self, x):
"""
Integrated GP-Lower Confidence Bound and its derivative
"""
means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x)
f_acqu = None
df_acqu = None
for m, s, dmdx, dsdx in zip(means, stds, dmdxs, dsdxs):
f = -m + self.exploration_weight * s
df = -dmdx + self.exploration_weight * dsdx
if f_acqu is None:
f_acqu = f
df_acqu = df
else:
f_acqu += f
df_acqu += df
return f_acqu/(len(means)), df_acqu/(len(means)) | [
"def",
"_compute_acq_withGradients",
"(",
"self",
",",
"x",
")",
":",
"means",
",",
"stds",
",",
"dmdxs",
",",
"dsdxs",
"=",
"self",
".",
"model",
".",
"predict_withGradients",
"(",
"x",
")",
"f_acqu",
"=",
"None",
"df_acqu",
"=",
"None",
"for",
"m",
"... | Integrated GP-Lower Confidence Bound and its derivative | [
"Integrated",
"GP",
"-",
"Lower",
"Confidence",
"Bound",
"and",
"its",
"derivative"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB_mcmc.py#L36-L52 | train | 223,071 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space._expand_config_space | def _expand_config_space(self):
"""
Expands the config input space into a list of diccionaries, one for each variable_dic
in which the dimensionality is always one.
Example: It would transform
config_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':2},
into
config_expande_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1},
{'name': 'var_2_1', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1}]
"""
self.config_space_expanded = []
for variable in self.config_space:
variable_dic = variable.copy()
if 'dimensionality' in variable_dic.keys():
dimensionality = variable_dic['dimensionality']
variable_dic['dimensionality'] = 1
variables_set = [variable_dic.copy() for d in range(dimensionality)]
k=1
for variable in variables_set:
variable['name'] = variable['name'] + '_'+str(k)
k+=1
self.config_space_expanded += variables_set
else:
self.config_space_expanded += [variable_dic] | python | def _expand_config_space(self):
"""
Expands the config input space into a list of diccionaries, one for each variable_dic
in which the dimensionality is always one.
Example: It would transform
config_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':2},
into
config_expande_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1},
{'name': 'var_2_1', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1}]
"""
self.config_space_expanded = []
for variable in self.config_space:
variable_dic = variable.copy()
if 'dimensionality' in variable_dic.keys():
dimensionality = variable_dic['dimensionality']
variable_dic['dimensionality'] = 1
variables_set = [variable_dic.copy() for d in range(dimensionality)]
k=1
for variable in variables_set:
variable['name'] = variable['name'] + '_'+str(k)
k+=1
self.config_space_expanded += variables_set
else:
self.config_space_expanded += [variable_dic] | [
"def",
"_expand_config_space",
"(",
"self",
")",
":",
"self",
".",
"config_space_expanded",
"=",
"[",
"]",
"for",
"variable",
"in",
"self",
".",
"config_space",
":",
"variable_dic",
"=",
"variable",
".",
"copy",
"(",
")",
"if",
"'dimensionality'",
"in",
"var... | Expands the config input space into a list of diccionaries, one for each variable_dic
in which the dimensionality is always one.
Example: It would transform
config_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':2},
into
config_expande_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1},
{'name': 'var_2', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1},
{'name': 'var_2_1', 'type': 'continuous', 'domain':(-3,1), 'dimensionality':1}] | [
"Expands",
"the",
"config",
"input",
"space",
"into",
"a",
"list",
"of",
"diccionaries",
"one",
"for",
"each",
"variable_dic",
"in",
"which",
"the",
"dimensionality",
"is",
"always",
"one",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L101-L131 | train | 223,072 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space._create_variables_dic | def _create_variables_dic(self):
"""
Returns the variable by passing its name
"""
self.name_to_variable = {}
for variable in self.space_expanded:
self.name_to_variable[variable.name] = variable | python | def _create_variables_dic(self):
"""
Returns the variable by passing its name
"""
self.name_to_variable = {}
for variable in self.space_expanded:
self.name_to_variable[variable.name] = variable | [
"def",
"_create_variables_dic",
"(",
"self",
")",
":",
"self",
".",
"name_to_variable",
"=",
"{",
"}",
"for",
"variable",
"in",
"self",
".",
"space_expanded",
":",
"self",
".",
"name_to_variable",
"[",
"variable",
".",
"name",
"]",
"=",
"variable"
] | Returns the variable by passing its name | [
"Returns",
"the",
"variable",
"by",
"passing",
"its",
"name"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L162-L168 | train | 223,073 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space._translate_space | def _translate_space(self, space):
"""
Translates a list of dictionaries into internal list of variables
"""
self.space = []
self.dimensionality = 0
self.has_types = d = {t: False for t in self.supported_types}
for i, d in enumerate(space):
descriptor = deepcopy(d)
descriptor['name'] = descriptor.get('name', 'var_' + str(i))
descriptor['type'] = descriptor.get('type', 'continuous')
if 'domain' not in descriptor:
raise InvalidConfigError('Domain attribute is missing for variable ' + descriptor['name'])
variable = create_variable(descriptor)
self.space.append(variable)
self.dimensionality += variable.dimensionality
self.has_types[variable.type] = True
# Check if there are any bandit and non-bandit variables together in the space
if any(v.is_bandit() for v in self.space) and any(not v.is_bandit() for v in self.space):
raise InvalidConfigError('Invalid mixed domain configuration. Bandit variables cannot be mixed with other types.') | python | def _translate_space(self, space):
"""
Translates a list of dictionaries into internal list of variables
"""
self.space = []
self.dimensionality = 0
self.has_types = d = {t: False for t in self.supported_types}
for i, d in enumerate(space):
descriptor = deepcopy(d)
descriptor['name'] = descriptor.get('name', 'var_' + str(i))
descriptor['type'] = descriptor.get('type', 'continuous')
if 'domain' not in descriptor:
raise InvalidConfigError('Domain attribute is missing for variable ' + descriptor['name'])
variable = create_variable(descriptor)
self.space.append(variable)
self.dimensionality += variable.dimensionality
self.has_types[variable.type] = True
# Check if there are any bandit and non-bandit variables together in the space
if any(v.is_bandit() for v in self.space) and any(not v.is_bandit() for v in self.space):
raise InvalidConfigError('Invalid mixed domain configuration. Bandit variables cannot be mixed with other types.') | [
"def",
"_translate_space",
"(",
"self",
",",
"space",
")",
":",
"self",
".",
"space",
"=",
"[",
"]",
"self",
".",
"dimensionality",
"=",
"0",
"self",
".",
"has_types",
"=",
"d",
"=",
"{",
"t",
":",
"False",
"for",
"t",
"in",
"self",
".",
"supported... | Translates a list of dictionaries into internal list of variables | [
"Translates",
"a",
"list",
"of",
"dictionaries",
"into",
"internal",
"list",
"of",
"variables"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L170-L191 | train | 223,074 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space._expand_space | def _expand_space(self):
"""
Creates an internal list where the variables with dimensionality larger than one are expanded.
This list is the one that is used internally to do the optimization.
"""
## --- Expand the config space
self._expand_config_space()
## --- Expand the space
self.space_expanded = []
for variable in self.space:
self.space_expanded += variable.expand() | python | def _expand_space(self):
"""
Creates an internal list where the variables with dimensionality larger than one are expanded.
This list is the one that is used internally to do the optimization.
"""
## --- Expand the config space
self._expand_config_space()
## --- Expand the space
self.space_expanded = []
for variable in self.space:
self.space_expanded += variable.expand() | [
"def",
"_expand_space",
"(",
"self",
")",
":",
"## --- Expand the config space",
"self",
".",
"_expand_config_space",
"(",
")",
"## --- Expand the space",
"self",
".",
"space_expanded",
"=",
"[",
"]",
"for",
"variable",
"in",
"self",
".",
"space",
":",
"self",
"... | Creates an internal list where the variables with dimensionality larger than one are expanded.
This list is the one that is used internally to do the optimization. | [
"Creates",
"an",
"internal",
"list",
"where",
"the",
"variables",
"with",
"dimensionality",
"larger",
"than",
"one",
"are",
"expanded",
".",
"This",
"list",
"is",
"the",
"one",
"that",
"is",
"used",
"internally",
"to",
"do",
"the",
"optimization",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L193-L205 | train | 223,075 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.objective_to_model | def objective_to_model(self, x_objective):
''' This function serves as interface between objective input vectors and
model input vectors'''
x_model = []
for k in range(self.objective_dimensionality):
variable = self.space_expanded[k]
new_entry = variable.objective_to_model(x_objective[0,k])
x_model += new_entry
return x_model | python | def objective_to_model(self, x_objective):
''' This function serves as interface between objective input vectors and
model input vectors'''
x_model = []
for k in range(self.objective_dimensionality):
variable = self.space_expanded[k]
new_entry = variable.objective_to_model(x_objective[0,k])
x_model += new_entry
return x_model | [
"def",
"objective_to_model",
"(",
"self",
",",
"x_objective",
")",
":",
"x_model",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"objective_dimensionality",
")",
":",
"variable",
"=",
"self",
".",
"space_expanded",
"[",
"k",
"]",
"new_entry",... | This function serves as interface between objective input vectors and
model input vectors | [
"This",
"function",
"serves",
"as",
"interface",
"between",
"objective",
"input",
"vectors",
"and",
"model",
"input",
"vectors"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L207-L218 | train | 223,076 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.model_to_objective | def model_to_objective(self, x_model):
''' This function serves as interface between model input vectors and
objective input vectors
'''
idx_model = 0
x_objective = []
for idx_obj in range(self.objective_dimensionality):
variable = self.space_expanded[idx_obj]
new_entry = variable.model_to_objective(x_model, idx_model)
x_objective += new_entry
idx_model += variable.dimensionality_in_model
return x_objective | python | def model_to_objective(self, x_model):
''' This function serves as interface between model input vectors and
objective input vectors
'''
idx_model = 0
x_objective = []
for idx_obj in range(self.objective_dimensionality):
variable = self.space_expanded[idx_obj]
new_entry = variable.model_to_objective(x_model, idx_model)
x_objective += new_entry
idx_model += variable.dimensionality_in_model
return x_objective | [
"def",
"model_to_objective",
"(",
"self",
",",
"x_model",
")",
":",
"idx_model",
"=",
"0",
"x_objective",
"=",
"[",
"]",
"for",
"idx_obj",
"in",
"range",
"(",
"self",
".",
"objective_dimensionality",
")",
":",
"variable",
"=",
"self",
".",
"space_expanded",
... | This function serves as interface between model input vectors and
objective input vectors | [
"This",
"function",
"serves",
"as",
"interface",
"between",
"model",
"input",
"vectors",
"and",
"objective",
"input",
"vectors"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L238-L251 | train | 223,077 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_subspace | def get_subspace(self, dims):
'''
Extracts subspace from the reference of a list of variables in the inputs
of the model.
'''
subspace = []
k = 0
for variable in self.space_expanded:
if k in dims:
subspace.append(variable)
k += variable.dimensionality_in_model
return subspace | python | def get_subspace(self, dims):
'''
Extracts subspace from the reference of a list of variables in the inputs
of the model.
'''
subspace = []
k = 0
for variable in self.space_expanded:
if k in dims:
subspace.append(variable)
k += variable.dimensionality_in_model
return subspace | [
"def",
"get_subspace",
"(",
"self",
",",
"dims",
")",
":",
"subspace",
"=",
"[",
"]",
"k",
"=",
"0",
"for",
"variable",
"in",
"self",
".",
"space_expanded",
":",
"if",
"k",
"in",
"dims",
":",
"subspace",
".",
"append",
"(",
"variable",
")",
"k",
"+... | Extracts subspace from the reference of a list of variables in the inputs
of the model. | [
"Extracts",
"subspace",
"from",
"the",
"reference",
"of",
"a",
"list",
"of",
"variables",
"in",
"the",
"inputs",
"of",
"the",
"model",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L283-L294 | train | 223,078 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.indicator_constraints | def indicator_constraints(self,x):
"""
Returns array of ones and zeros indicating if x is within the constraints
"""
x = np.atleast_2d(x)
I_x = np.ones((x.shape[0],1))
if self.constraints is not None:
for d in self.constraints:
try:
exec('constraint = lambda x:' + d['constraint'], globals())
ind_x = (constraint(x) <= 0) * 1
I_x *= ind_x.reshape(x.shape[0],1)
except:
print('Fail to compile the constraint: ' + str(d))
raise
return I_x | python | def indicator_constraints(self,x):
"""
Returns array of ones and zeros indicating if x is within the constraints
"""
x = np.atleast_2d(x)
I_x = np.ones((x.shape[0],1))
if self.constraints is not None:
for d in self.constraints:
try:
exec('constraint = lambda x:' + d['constraint'], globals())
ind_x = (constraint(x) <= 0) * 1
I_x *= ind_x.reshape(x.shape[0],1)
except:
print('Fail to compile the constraint: ' + str(d))
raise
return I_x | [
"def",
"indicator_constraints",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"I_x",
"=",
"np",
".",
"ones",
"(",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
"if",
"self",
".",
"constraints",
... | Returns array of ones and zeros indicating if x is within the constraints | [
"Returns",
"array",
"of",
"ones",
"and",
"zeros",
"indicating",
"if",
"x",
"is",
"within",
"the",
"constraints"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L297-L312 | train | 223,079 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.input_dim | def input_dim(self):
"""
Extracts the input dimension of the domain.
"""
n_cont = len(self.get_continuous_dims())
n_disc = len(self.get_discrete_dims())
return n_cont + n_disc | python | def input_dim(self):
"""
Extracts the input dimension of the domain.
"""
n_cont = len(self.get_continuous_dims())
n_disc = len(self.get_discrete_dims())
return n_cont + n_disc | [
"def",
"input_dim",
"(",
"self",
")",
":",
"n_cont",
"=",
"len",
"(",
"self",
".",
"get_continuous_dims",
"(",
")",
")",
"n_disc",
"=",
"len",
"(",
"self",
".",
"get_discrete_dims",
"(",
")",
")",
"return",
"n_cont",
"+",
"n_disc"
] | Extracts the input dimension of the domain. | [
"Extracts",
"the",
"input",
"dimension",
"of",
"the",
"domain",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L314-L320 | train | 223,080 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.round_optimum | def round_optimum(self, x):
"""
Rounds some value x to a feasible value in the design space.
x is expected to be a vector or an array with a single row
"""
x = np.array(x)
if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)):
raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim))
if x.ndim == 2:
x = x[0]
x_rounded = []
value_index = 0
for variable in self.space_expanded:
var_value = x[value_index : value_index + variable.dimensionality_in_model]
var_value_rounded = variable.round(var_value)
x_rounded.append(var_value_rounded)
value_index += variable.dimensionality_in_model
return np.atleast_2d(np.concatenate(x_rounded)) | python | def round_optimum(self, x):
"""
Rounds some value x to a feasible value in the design space.
x is expected to be a vector or an array with a single row
"""
x = np.array(x)
if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)):
raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim))
if x.ndim == 2:
x = x[0]
x_rounded = []
value_index = 0
for variable in self.space_expanded:
var_value = x[value_index : value_index + variable.dimensionality_in_model]
var_value_rounded = variable.round(var_value)
x_rounded.append(var_value_rounded)
value_index += variable.dimensionality_in_model
return np.atleast_2d(np.concatenate(x_rounded)) | [
"def",
"round_optimum",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"if",
"not",
"(",
"(",
"x",
".",
"ndim",
"==",
"1",
")",
"or",
"(",
"x",
".",
"ndim",
"==",
"2",
"and",
"x",
".",
"shape",
"[",
"0",
"]"... | Rounds some value x to a feasible value in the design space.
x is expected to be a vector or an array with a single row | [
"Rounds",
"some",
"value",
"x",
"to",
"a",
"feasible",
"value",
"in",
"the",
"design",
"space",
".",
"x",
"is",
"expected",
"to",
"be",
"a",
"vector",
"or",
"an",
"array",
"with",
"a",
"single",
"row"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L322-L343 | train | 223,081 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_continuous_bounds | def get_continuous_bounds(self):
"""
Extracts the bounds of the continuous variables.
"""
bounds = []
for d in self.space:
if d.type == 'continuous':
bounds.extend([d.domain]*d.dimensionality)
return bounds | python | def get_continuous_bounds(self):
"""
Extracts the bounds of the continuous variables.
"""
bounds = []
for d in self.space:
if d.type == 'continuous':
bounds.extend([d.domain]*d.dimensionality)
return bounds | [
"def",
"get_continuous_bounds",
"(",
"self",
")",
":",
"bounds",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"space",
":",
"if",
"d",
".",
"type",
"==",
"'continuous'",
":",
"bounds",
".",
"extend",
"(",
"[",
"d",
".",
"domain",
"]",
"*",
"d",
... | Extracts the bounds of the continuous variables. | [
"Extracts",
"the",
"bounds",
"of",
"the",
"continuous",
"variables",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L353-L361 | train | 223,082 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_continuous_dims | def get_continuous_dims(self):
"""
Returns the dimension of the continuous components of the domain.
"""
continuous_dims = []
for i in range(self.dimensionality):
if self.space_expanded[i].type == 'continuous':
continuous_dims += [i]
return continuous_dims | python | def get_continuous_dims(self):
"""
Returns the dimension of the continuous components of the domain.
"""
continuous_dims = []
for i in range(self.dimensionality):
if self.space_expanded[i].type == 'continuous':
continuous_dims += [i]
return continuous_dims | [
"def",
"get_continuous_dims",
"(",
"self",
")",
":",
"continuous_dims",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"dimensionality",
")",
":",
"if",
"self",
".",
"space_expanded",
"[",
"i",
"]",
".",
"type",
"==",
"'continuous'",
":",
... | Returns the dimension of the continuous components of the domain. | [
"Returns",
"the",
"dimension",
"of",
"the",
"continuous",
"components",
"of",
"the",
"domain",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L364-L372 | train | 223,083 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_discrete_grid | def get_discrete_grid(self):
"""
Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables
"""
sets_grid = []
for d in self.space:
if d.type == 'discrete':
sets_grid.extend([d.domain]*d.dimensionality)
return np.array(list(itertools.product(*sets_grid))) | python | def get_discrete_grid(self):
"""
Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables
"""
sets_grid = []
for d in self.space:
if d.type == 'discrete':
sets_grid.extend([d.domain]*d.dimensionality)
return np.array(list(itertools.product(*sets_grid))) | [
"def",
"get_discrete_grid",
"(",
"self",
")",
":",
"sets_grid",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"space",
":",
"if",
"d",
".",
"type",
"==",
"'discrete'",
":",
"sets_grid",
".",
"extend",
"(",
"[",
"d",
".",
"domain",
"]",
"*",
"d",
... | Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete
variables | [
"Computes",
"a",
"Numpy",
"array",
"with",
"the",
"grid",
"of",
"points",
"that",
"results",
"after",
"crossing",
"the",
"possible",
"outputs",
"of",
"the",
"discrete",
"variables"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L387-L396 | train | 223,084 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_discrete_dims | def get_discrete_dims(self):
"""
Returns the dimension of the discrete components of the domain.
"""
discrete_dims = []
for i in range(self.dimensionality):
if self.space_expanded[i].type == 'discrete':
discrete_dims += [i]
return discrete_dims | python | def get_discrete_dims(self):
"""
Returns the dimension of the discrete components of the domain.
"""
discrete_dims = []
for i in range(self.dimensionality):
if self.space_expanded[i].type == 'discrete':
discrete_dims += [i]
return discrete_dims | [
"def",
"get_discrete_dims",
"(",
"self",
")",
":",
"discrete_dims",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"dimensionality",
")",
":",
"if",
"self",
".",
"space_expanded",
"[",
"i",
"]",
".",
"type",
"==",
"'discrete'",
":",
"discr... | Returns the dimension of the discrete components of the domain. | [
"Returns",
"the",
"dimension",
"of",
"the",
"discrete",
"components",
"of",
"the",
"domain",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L399-L407 | train | 223,085 |
SheffieldML/GPyOpt | GPyOpt/core/task/space.py | Design_space.get_bandit | def get_bandit(self):
"""
Extracts the arms of the bandit if any.
"""
arms_bandit = []
for d in self.space:
if d.type == 'bandit':
arms_bandit += tuple(map(tuple, d.domain))
return np.asarray(arms_bandit) | python | def get_bandit(self):
"""
Extracts the arms of the bandit if any.
"""
arms_bandit = []
for d in self.space:
if d.type == 'bandit':
arms_bandit += tuple(map(tuple, d.domain))
return np.asarray(arms_bandit) | [
"def",
"get_bandit",
"(",
"self",
")",
":",
"arms_bandit",
"=",
"[",
"]",
"for",
"d",
"in",
"self",
".",
"space",
":",
"if",
"d",
".",
"type",
"==",
"'bandit'",
":",
"arms_bandit",
"+=",
"tuple",
"(",
"map",
"(",
"tuple",
",",
"d",
".",
"domain",
... | Extracts the arms of the bandit if any. | [
"Extracts",
"the",
"arms",
"of",
"the",
"bandit",
"if",
"any",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L422-L430 | train | 223,086 |
SheffieldML/GPyOpt | GPyOpt/models/rfmodel.py | RFModel.predict | def predict(self, X):
"""
Predictions with the model. Returns posterior means and standard deviations at X.
"""
X = np.atleast_2d(X)
m = np.empty(shape=(0,1))
s = np.empty(shape=(0,1))
for k in range(X.shape[0]):
preds = []
for pred in self.model.estimators_:
preds.append(pred.predict(X[k,:])[0])
m = np.vstack((m ,np.array(preds).mean()))
s = np.vstack((s ,np.array(preds).std()))
return m, s | python | def predict(self, X):
"""
Predictions with the model. Returns posterior means and standard deviations at X.
"""
X = np.atleast_2d(X)
m = np.empty(shape=(0,1))
s = np.empty(shape=(0,1))
for k in range(X.shape[0]):
preds = []
for pred in self.model.estimators_:
preds.append(pred.predict(X[k,:])[0])
m = np.vstack((m ,np.array(preds).mean()))
s = np.vstack((s ,np.array(preds).std()))
return m, s | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"atleast_2d",
"(",
"X",
")",
"m",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"0",
",",
"1",
")",
")",
"s",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"0",... | Predictions with the model. Returns posterior means and standard deviations at X. | [
"Predictions",
"with",
"the",
"model",
".",
"Returns",
"posterior",
"means",
"and",
"standard",
"deviations",
"at",
"X",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/rfmodel.py#L79-L93 | train | 223,087 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/MPI_mcmc.py | AcquisitionMPI_MCMC._compute_acq | def _compute_acq(self,x):
"""
Integrated Expected Improvement
"""
means, stds = self.model.predict(x)
fmins = self.model.get_fmin()
f_acqu = 0
for m,s,fmin in zip(means, stds, fmins):
_, Phi, _ = get_quantiles(self.jitter, fmin, m, s)
f_acqu += Phi
return f_acqu/len(means) | python | def _compute_acq(self,x):
"""
Integrated Expected Improvement
"""
means, stds = self.model.predict(x)
fmins = self.model.get_fmin()
f_acqu = 0
for m,s,fmin in zip(means, stds, fmins):
_, Phi, _ = get_quantiles(self.jitter, fmin, m, s)
f_acqu += Phi
return f_acqu/len(means) | [
"def",
"_compute_acq",
"(",
"self",
",",
"x",
")",
":",
"means",
",",
"stds",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"x",
")",
"fmins",
"=",
"self",
".",
"model",
".",
"get_fmin",
"(",
")",
"f_acqu",
"=",
"0",
"for",
"m",
",",
"s",
","... | Integrated Expected Improvement | [
"Integrated",
"Expected",
"Improvement"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/MPI_mcmc.py#L29-L39 | train | 223,088 |
SheffieldML/GPyOpt | GPyOpt/acquisitions/MPI_mcmc.py | AcquisitionMPI_MCMC._compute_acq_withGradients | def _compute_acq_withGradients(self, x):
"""
Integrated Expected Improvement and its derivative
"""
means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x)
fmins = self.model.get_fmin()
f_acqu = None
df_acqu = None
for m, s, fmin, dmdx, dsdx in zip(means, stds, fmins, dmdxs, dsdxs):
phi, Phi, u = get_quantiles(self.jitter, fmin, m, s)
f = Phi
df = -(phi/s)* (dmdx + dsdx * u)
if f_acqu is None:
f_acqu = f
df_acqu = df
else:
f_acqu += f
df_acqu += df
return f_acqu/(len(means)), df_acqu/(len(means)) | python | def _compute_acq_withGradients(self, x):
"""
Integrated Expected Improvement and its derivative
"""
means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x)
fmins = self.model.get_fmin()
f_acqu = None
df_acqu = None
for m, s, fmin, dmdx, dsdx in zip(means, stds, fmins, dmdxs, dsdxs):
phi, Phi, u = get_quantiles(self.jitter, fmin, m, s)
f = Phi
df = -(phi/s)* (dmdx + dsdx * u)
if f_acqu is None:
f_acqu = f
df_acqu = df
else:
f_acqu += f
df_acqu += df
return f_acqu/(len(means)), df_acqu/(len(means)) | [
"def",
"_compute_acq_withGradients",
"(",
"self",
",",
"x",
")",
":",
"means",
",",
"stds",
",",
"dmdxs",
",",
"dsdxs",
"=",
"self",
".",
"model",
".",
"predict_withGradients",
"(",
"x",
")",
"fmins",
"=",
"self",
".",
"model",
".",
"get_fmin",
"(",
")... | Integrated Expected Improvement and its derivative | [
"Integrated",
"Expected",
"Improvement",
"and",
"its",
"derivative"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/MPI_mcmc.py#L41-L59 | train | 223,089 |
SheffieldML/GPyOpt | GPyOpt/plotting/plots_bo.py | plot_convergence | def plot_convergence(Xdata,best_Y, filename = None):
'''
Plots to evaluate the convergence of standard Bayesian optimization algorithms
'''
n = Xdata.shape[0]
aux = (Xdata[1:n,:]-Xdata[0:n-1,:])**2
distances = np.sqrt(aux.sum(axis=1))
## Distances between consecutive x's
plt.figure(figsize=(10,5))
plt.subplot(1, 2, 1)
plt.plot(list(range(n-1)), distances, '-ro')
plt.xlabel('Iteration')
plt.ylabel('d(x[n], x[n-1])')
plt.title('Distance between consecutive x\'s')
grid(True)
# Estimated m(x) at the proposed sampling points
plt.subplot(1, 2, 2)
plt.plot(list(range(n)),best_Y,'-o')
plt.title('Value of the best selected sample')
plt.xlabel('Iteration')
plt.ylabel('Best y')
grid(True)
if filename!=None:
savefig(filename)
else:
plt.show() | python | def plot_convergence(Xdata,best_Y, filename = None):
'''
Plots to evaluate the convergence of standard Bayesian optimization algorithms
'''
n = Xdata.shape[0]
aux = (Xdata[1:n,:]-Xdata[0:n-1,:])**2
distances = np.sqrt(aux.sum(axis=1))
## Distances between consecutive x's
plt.figure(figsize=(10,5))
plt.subplot(1, 2, 1)
plt.plot(list(range(n-1)), distances, '-ro')
plt.xlabel('Iteration')
plt.ylabel('d(x[n], x[n-1])')
plt.title('Distance between consecutive x\'s')
grid(True)
# Estimated m(x) at the proposed sampling points
plt.subplot(1, 2, 2)
plt.plot(list(range(n)),best_Y,'-o')
plt.title('Value of the best selected sample')
plt.xlabel('Iteration')
plt.ylabel('Best y')
grid(True)
if filename!=None:
savefig(filename)
else:
plt.show() | [
"def",
"plot_convergence",
"(",
"Xdata",
",",
"best_Y",
",",
"filename",
"=",
"None",
")",
":",
"n",
"=",
"Xdata",
".",
"shape",
"[",
"0",
"]",
"aux",
"=",
"(",
"Xdata",
"[",
"1",
":",
"n",
",",
":",
"]",
"-",
"Xdata",
"[",
"0",
":",
"n",
"-"... | Plots to evaluate the convergence of standard Bayesian optimization algorithms | [
"Plots",
"to",
"evaluate",
"the",
"convergence",
"of",
"standard",
"Bayesian",
"optimization",
"algorithms"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/plotting/plots_bo.py#L122-L150 | train | 223,090 |
SheffieldML/GPyOpt | GPyOpt/core/evaluators/batch_local_penalization.py | LocalPenalization.compute_batch | def compute_batch(self, duplicate_manager=None, context_manager=None):
"""
Computes the elements of the batch sequentially by penalizing the acquisition.
"""
from ...acquisitions import AcquisitionLP
assert isinstance(self.acquisition, AcquisitionLP)
self.acquisition.update_batches(None,None,None)
# --- GET first element in the batch
X_batch = self.acquisition.optimize()[0]
k=1
if self.batch_size >1:
# ---------- Approximate the constants of the the method
L = estimate_L(self.acquisition.model.model,self.acquisition.space.get_bounds())
Min = self.acquisition.model.model.Y.min()
# --- GET the remaining elements
while k<self.batch_size:
self.acquisition.update_batches(X_batch,L,Min)
new_sample = self.acquisition.optimize()[0]
X_batch = np.vstack((X_batch,new_sample))
k +=1
# --- Back to the non-penalized acquisition
self.acquisition.update_batches(None,None,None)
return X_batch | python | def compute_batch(self, duplicate_manager=None, context_manager=None):
"""
Computes the elements of the batch sequentially by penalizing the acquisition.
"""
from ...acquisitions import AcquisitionLP
assert isinstance(self.acquisition, AcquisitionLP)
self.acquisition.update_batches(None,None,None)
# --- GET first element in the batch
X_batch = self.acquisition.optimize()[0]
k=1
if self.batch_size >1:
# ---------- Approximate the constants of the the method
L = estimate_L(self.acquisition.model.model,self.acquisition.space.get_bounds())
Min = self.acquisition.model.model.Y.min()
# --- GET the remaining elements
while k<self.batch_size:
self.acquisition.update_batches(X_batch,L,Min)
new_sample = self.acquisition.optimize()[0]
X_batch = np.vstack((X_batch,new_sample))
k +=1
# --- Back to the non-penalized acquisition
self.acquisition.update_batches(None,None,None)
return X_batch | [
"def",
"compute_batch",
"(",
"self",
",",
"duplicate_manager",
"=",
"None",
",",
"context_manager",
"=",
"None",
")",
":",
"from",
".",
".",
".",
"acquisitions",
"import",
"AcquisitionLP",
"assert",
"isinstance",
"(",
"self",
".",
"acquisition",
",",
"Acquisit... | Computes the elements of the batch sequentially by penalizing the acquisition. | [
"Computes",
"the",
"elements",
"of",
"the",
"batch",
"sequentially",
"by",
"penalizing",
"the",
"acquisition",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/evaluators/batch_local_penalization.py#L22-L49 | train | 223,091 |
SheffieldML/GPyOpt | manual/notebooks_check.py | check_notebooks_for_errors | def check_notebooks_for_errors(notebooks_directory):
''' Evaluates all notebooks in given directory and prints errors, if any '''
print("Checking notebooks in directory {} for errors".format(notebooks_directory))
failed_notebooks_count = 0
for file in os.listdir(notebooks_directory):
if file.endswith(".ipynb"):
print("Checking notebook " + file)
full_file_path = os.path.join(notebooks_directory, file)
output, errors = run_notebook(full_file_path)
if errors is not None and len(errors) > 0:
failed_notebooks_count += 1
print("Errors in notebook " + file)
print(errors)
if failed_notebooks_count == 0:
print("No errors found in notebooks under " + notebooks_directory) | python | def check_notebooks_for_errors(notebooks_directory):
''' Evaluates all notebooks in given directory and prints errors, if any '''
print("Checking notebooks in directory {} for errors".format(notebooks_directory))
failed_notebooks_count = 0
for file in os.listdir(notebooks_directory):
if file.endswith(".ipynb"):
print("Checking notebook " + file)
full_file_path = os.path.join(notebooks_directory, file)
output, errors = run_notebook(full_file_path)
if errors is not None and len(errors) > 0:
failed_notebooks_count += 1
print("Errors in notebook " + file)
print(errors)
if failed_notebooks_count == 0:
print("No errors found in notebooks under " + notebooks_directory) | [
"def",
"check_notebooks_for_errors",
"(",
"notebooks_directory",
")",
":",
"print",
"(",
"\"Checking notebooks in directory {} for errors\"",
".",
"format",
"(",
"notebooks_directory",
")",
")",
"failed_notebooks_count",
"=",
"0",
"for",
"file",
"in",
"os",
".",
"listdi... | Evaluates all notebooks in given directory and prints errors, if any | [
"Evaluates",
"all",
"notebooks",
"in",
"given",
"directory",
"and",
"prints",
"errors",
"if",
"any"
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/manual/notebooks_check.py#L8-L24 | train | 223,092 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel.predict | def predict(self, X, with_noise=True):
"""
Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True.
"""
m, v = self._predict(X, False, with_noise)
# We can take the square root because v is just a diagonal matrix of variances
return m, np.sqrt(v) | python | def predict(self, X, with_noise=True):
"""
Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True.
"""
m, v = self._predict(X, False, with_noise)
# We can take the square root because v is just a diagonal matrix of variances
return m, np.sqrt(v) | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"with_noise",
"=",
"True",
")",
":",
"m",
",",
"v",
"=",
"self",
".",
"_predict",
"(",
"X",
",",
"False",
",",
"with_noise",
")",
"# We can take the square root because v is just a diagonal matrix of variances",
"ret... | Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True. | [
"Predictions",
"with",
"the",
"model",
".",
"Returns",
"posterior",
"means",
"and",
"standard",
"deviations",
"at",
"X",
".",
"Note",
"that",
"this",
"is",
"different",
"in",
"GPy",
"where",
"the",
"variances",
"are",
"given",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L100-L110 | train | 223,093 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel.predict_covariance | def predict_covariance(self, X, with_noise=True):
"""
Predicts the covariance matric for points in X.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True.
"""
_, v = self._predict(X, True, with_noise)
return v | python | def predict_covariance(self, X, with_noise=True):
"""
Predicts the covariance matric for points in X.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True.
"""
_, v = self._predict(X, True, with_noise)
return v | [
"def",
"predict_covariance",
"(",
"self",
",",
"X",
",",
"with_noise",
"=",
"True",
")",
":",
"_",
",",
"v",
"=",
"self",
".",
"_predict",
"(",
"X",
",",
"True",
",",
"with_noise",
")",
"return",
"v"
] | Predicts the covariance matric for points in X.
Parameters:
X (np.ndarray) - points to run the prediction for.
with_noise (bool) - whether to add noise to the prediction. Default is True. | [
"Predicts",
"the",
"covariance",
"matric",
"for",
"points",
"in",
"X",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L112-L121 | train | 223,094 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel.predict_withGradients | def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X.
"""
if X.ndim==1: X = X[None,:]
m, v = self.model.predict(X)
v = np.clip(v, 1e-10, np.inf)
dmdx, dvdx = self.model.predictive_gradients(X)
dmdx = dmdx[:,:,0]
dsdx = dvdx / (2*np.sqrt(v))
return m, np.sqrt(v), dmdx, dsdx | python | def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X.
"""
if X.ndim==1: X = X[None,:]
m, v = self.model.predict(X)
v = np.clip(v, 1e-10, np.inf)
dmdx, dvdx = self.model.predictive_gradients(X)
dmdx = dmdx[:,:,0]
dsdx = dvdx / (2*np.sqrt(v))
return m, np.sqrt(v), dmdx, dsdx | [
"def",
"predict_withGradients",
"(",
"self",
",",
"X",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
"None",
",",
":",
"]",
"m",
",",
"v",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"X",
")",
"v",
"=",
"np",
"."... | Returns the mean, standard deviation, mean gradient and standard deviation gradient at X. | [
"Returns",
"the",
"mean",
"standard",
"deviation",
"mean",
"gradient",
"and",
"standard",
"deviation",
"gradient",
"at",
"X",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L129-L140 | train | 223,095 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel_MCMC.predict | def predict(self, X):
"""
Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
m, v = self.model.predict(X)
means.append(m)
stds.append(np.sqrt(np.clip(v, 1e-10, np.inf)))
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return means, stds | python | def predict(self, X):
"""
Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
m, v = self.model.predict(X)
means.append(m)
stds.append(np.sqrt(np.clip(v, 1e-10, np.inf)))
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return means, stds | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
"None",
",",
":",
"]",
"ps",
"=",
"self",
".",
"model",
".",
"param_array",
".",
"copy",
"(",
")",
"means",
"=",
"[",
"]",
"stds"... | Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. | [
"Predictions",
"with",
"the",
"model",
"for",
"all",
"the",
"MCMC",
"samples",
".",
"Returns",
"posterior",
"means",
"and",
"standard",
"deviations",
"at",
"X",
".",
"Note",
"that",
"this",
"is",
"different",
"in",
"GPy",
"where",
"the",
"variances",
"are",
... | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L255-L275 | train | 223,096 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel_MCMC.get_fmin | def get_fmin(self):
"""
Returns the location where the posterior mean is takes its minimal value.
"""
ps = self.model.param_array.copy()
fmins = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
fmins.append(self.model.predict(self.model.X)[0].min())
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return fmins | python | def get_fmin(self):
"""
Returns the location where the posterior mean is takes its minimal value.
"""
ps = self.model.param_array.copy()
fmins = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
fmins.append(self.model.predict(self.model.X)[0].min())
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return fmins | [
"def",
"get_fmin",
"(",
"self",
")",
":",
"ps",
"=",
"self",
".",
"model",
".",
"param_array",
".",
"copy",
"(",
")",
"fmins",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"hmc_samples",
":",
"if",
"self",
".",
"model",
".",
"_fixes_",
"is",
"No... | Returns the location where the posterior mean is takes its minimal value. | [
"Returns",
"the",
"location",
"where",
"the",
"posterior",
"mean",
"is",
"takes",
"its",
"minimal",
"value",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L277-L293 | train | 223,097 |
SheffieldML/GPyOpt | GPyOpt/models/gpmodel.py | GPModel_MCMC.predict_withGradients | def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
dmdxs = []
dsdxs = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
m, v = self.model.predict(X)
std = np.sqrt(np.clip(v, 1e-10, np.inf))
dmdx, dvdx = self.model.predictive_gradients(X)
dmdx = dmdx[:,:,0]
dsdx = dvdx / (2*std)
means.append(m)
stds.append(std)
dmdxs.append(dmdx)
dsdxs.append(dsdx)
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return means, stds, dmdxs, dsdxs | python | def predict_withGradients(self, X):
"""
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
"""
if X.ndim==1: X = X[None,:]
ps = self.model.param_array.copy()
means = []
stds = []
dmdxs = []
dsdxs = []
for s in self.hmc_samples:
if self.model._fixes_ is None:
self.model[:] = s
else:
self.model[self.model._fixes_] = s
self.model._trigger_params_changed()
m, v = self.model.predict(X)
std = np.sqrt(np.clip(v, 1e-10, np.inf))
dmdx, dvdx = self.model.predictive_gradients(X)
dmdx = dmdx[:,:,0]
dsdx = dvdx / (2*std)
means.append(m)
stds.append(std)
dmdxs.append(dmdx)
dsdxs.append(dsdx)
self.model.param_array[:] = ps
self.model._trigger_params_changed()
return means, stds, dmdxs, dsdxs | [
"def",
"predict_withGradients",
"(",
"self",
",",
"X",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"1",
":",
"X",
"=",
"X",
"[",
"None",
",",
":",
"]",
"ps",
"=",
"self",
".",
"model",
".",
"param_array",
".",
"copy",
"(",
")",
"means",
"=",
"[",
... | Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples. | [
"Returns",
"the",
"mean",
"standard",
"deviation",
"mean",
"gradient",
"and",
"standard",
"deviation",
"gradient",
"at",
"X",
"for",
"all",
"the",
"MCMC",
"samples",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L295-L322 | train | 223,098 |
SheffieldML/GPyOpt | GPyOpt/interface/func_loader.py | load_objective | def load_objective(config):
"""
Loads the objective function from a .json file.
"""
assert 'prjpath' in config
assert 'main-file' in config, "The problem file ('main-file') is missing!"
os.chdir(config['prjpath'])
if config['language'].lower()=='python':
assert config['main-file'].endswith('.py'), 'The python problem file has to end with .py!'
import imp
m = imp.load_source(config['main-file'][:-3], os.path.join(config['prjpath'],config['main-file']))
func = m.__dict__[config['main-file'][:-3]]
return func | python | def load_objective(config):
"""
Loads the objective function from a .json file.
"""
assert 'prjpath' in config
assert 'main-file' in config, "The problem file ('main-file') is missing!"
os.chdir(config['prjpath'])
if config['language'].lower()=='python':
assert config['main-file'].endswith('.py'), 'The python problem file has to end with .py!'
import imp
m = imp.load_source(config['main-file'][:-3], os.path.join(config['prjpath'],config['main-file']))
func = m.__dict__[config['main-file'][:-3]]
return func | [
"def",
"load_objective",
"(",
"config",
")",
":",
"assert",
"'prjpath'",
"in",
"config",
"assert",
"'main-file'",
"in",
"config",
",",
"\"The problem file ('main-file') is missing!\"",
"os",
".",
"chdir",
"(",
"config",
"[",
"'prjpath'",
"]",
")",
"if",
"config",
... | Loads the objective function from a .json file. | [
"Loads",
"the",
"objective",
"function",
"from",
"a",
".",
"json",
"file",
"."
] | 255539dc5927819ca701e44fe3d76cd4864222fa | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/func_loader.py#L7-L21 | train | 223,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.