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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
chemlab/chemlab | chemlab/libs/cirpy.py | download | def download(input, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Resolve and download structure as a file """
kwargs['format'] = format
if resolvers:
kwargs['resolver'] = ",".join(resolvers)
url = API_BASE+'/%s/file?%s' % (urlquote(input), urlencode(kwargs))
try:
servefile = urlopen(url)
if not overwrite and os.path.isfile(filename):
raise IOError("%s already exists. Use 'overwrite=True' to overwrite it." % filename)
file = open(filename, "w")
file.write(servefile.read())
file.close()
except urllib.error.HTTPError:
# TODO: Proper handling of 404, for now just does nothing
pass | python | def download(input, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Resolve and download structure as a file """
kwargs['format'] = format
if resolvers:
kwargs['resolver'] = ",".join(resolvers)
url = API_BASE+'/%s/file?%s' % (urlquote(input), urlencode(kwargs))
try:
servefile = urlopen(url)
if not overwrite and os.path.isfile(filename):
raise IOError("%s already exists. Use 'overwrite=True' to overwrite it." % filename)
file = open(filename, "w")
file.write(servefile.read())
file.close()
except urllib.error.HTTPError:
# TODO: Proper handling of 404, for now just does nothing
pass | [
"def",
"download",
"(",
"input",
",",
"filename",
",",
"format",
"=",
"'sdf'",
",",
"overwrite",
"=",
"False",
",",
"resolvers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'format'",
"]",
"=",
"format",
"if",
"resolvers",
":",
"kwargs",
"[",
"'resolver'",
"]",
"=",
"\",\"",
".",
"join",
"(",
"resolvers",
")",
"url",
"=",
"API_BASE",
"+",
"'/%s/file?%s'",
"%",
"(",
"urlquote",
"(",
"input",
")",
",",
"urlencode",
"(",
"kwargs",
")",
")",
"try",
":",
"servefile",
"=",
"urlopen",
"(",
"url",
")",
"if",
"not",
"overwrite",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"IOError",
"(",
"\"%s already exists. Use 'overwrite=True' to overwrite it.\"",
"%",
"filename",
")",
"file",
"=",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"file",
".",
"write",
"(",
"servefile",
".",
"read",
"(",
")",
")",
"file",
".",
"close",
"(",
")",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
":",
"# TODO: Proper handling of 404, for now just does nothing",
"pass"
] | Resolve and download structure as a file | [
"Resolve",
"and",
"download",
"structure",
"as",
"a",
"file"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L66-L81 | train |
chemlab/chemlab | chemlab/libs/cirpy.py | Molecule.download | def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Download the resolved structure as a file """
download(self.input, filename, format, overwrite, resolvers, **kwargs) | python | def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Download the resolved structure as a file """
download(self.input, filename, format, overwrite, resolvers, **kwargs) | [
"def",
"download",
"(",
"self",
",",
"filename",
",",
"format",
"=",
"'sdf'",
",",
"overwrite",
"=",
"False",
",",
"resolvers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"download",
"(",
"self",
".",
"input",
",",
"filename",
",",
"format",
",",
"overwrite",
",",
"resolvers",
",",
"*",
"*",
"kwargs",
")"
] | Download the resolved structure as a file | [
"Download",
"the",
"resolved",
"structure",
"as",
"a",
"file"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/libs/cirpy.py#L196-L198 | train |
chemlab/chemlab | chemlab/utils/__init__.py | dipole_moment | def dipole_moment(r_array, charge_array):
'''Return the dipole moment of a neutral system.
'''
return np.sum(r_array * charge_array[:, np.newaxis], axis=0) | python | def dipole_moment(r_array, charge_array):
'''Return the dipole moment of a neutral system.
'''
return np.sum(r_array * charge_array[:, np.newaxis], axis=0) | [
"def",
"dipole_moment",
"(",
"r_array",
",",
"charge_array",
")",
":",
"return",
"np",
".",
"sum",
"(",
"r_array",
"*",
"charge_array",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"axis",
"=",
"0",
")"
] | Return the dipole moment of a neutral system. | [
"Return",
"the",
"dipole",
"moment",
"of",
"a",
"neutral",
"system",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/__init__.py#L90-L93 | train |
chemlab/chemlab | chemlab/graphics/qt/qtviewer.py | QtViewer.schedule | def schedule(self, callback, timeout=100):
'''Schedule a function to be called repeated time.
This method can be used to perform animations.
**Example**
This is a typical way to perform an animation, just::
from chemlab.graphics.qt import QtViewer
from chemlab.graphics.renderers import SphereRenderer
v = QtViewer()
sr = v.add_renderer(SphereRenderer, centers, radii, colors)
def update():
# calculate new_positions
sr.update_positions(new_positions)
v.widget.repaint()
v.schedule(update)
v.run()
.. note:: remember to call QtViewer.widget.repaint() each
once you want to update the display.
**Parameters**
callback: function()
A function that takes no arguments that will be
called at intervals.
timeout: int
Time in milliseconds between calls of the *callback*
function.
**Returns**
a `QTimer`, to stop the animation you can use `Qtimer.stop`
'''
timer = QTimer(self)
timer.timeout.connect(callback)
timer.start(timeout)
return timer | python | def schedule(self, callback, timeout=100):
'''Schedule a function to be called repeated time.
This method can be used to perform animations.
**Example**
This is a typical way to perform an animation, just::
from chemlab.graphics.qt import QtViewer
from chemlab.graphics.renderers import SphereRenderer
v = QtViewer()
sr = v.add_renderer(SphereRenderer, centers, radii, colors)
def update():
# calculate new_positions
sr.update_positions(new_positions)
v.widget.repaint()
v.schedule(update)
v.run()
.. note:: remember to call QtViewer.widget.repaint() each
once you want to update the display.
**Parameters**
callback: function()
A function that takes no arguments that will be
called at intervals.
timeout: int
Time in milliseconds between calls of the *callback*
function.
**Returns**
a `QTimer`, to stop the animation you can use `Qtimer.stop`
'''
timer = QTimer(self)
timer.timeout.connect(callback)
timer.start(timeout)
return timer | [
"def",
"schedule",
"(",
"self",
",",
"callback",
",",
"timeout",
"=",
"100",
")",
":",
"timer",
"=",
"QTimer",
"(",
"self",
")",
"timer",
".",
"timeout",
".",
"connect",
"(",
"callback",
")",
"timer",
".",
"start",
"(",
"timeout",
")",
"return",
"timer"
] | Schedule a function to be called repeated time.
This method can be used to perform animations.
**Example**
This is a typical way to perform an animation, just::
from chemlab.graphics.qt import QtViewer
from chemlab.graphics.renderers import SphereRenderer
v = QtViewer()
sr = v.add_renderer(SphereRenderer, centers, radii, colors)
def update():
# calculate new_positions
sr.update_positions(new_positions)
v.widget.repaint()
v.schedule(update)
v.run()
.. note:: remember to call QtViewer.widget.repaint() each
once you want to update the display.
**Parameters**
callback: function()
A function that takes no arguments that will be
called at intervals.
timeout: int
Time in milliseconds between calls of the *callback*
function.
**Returns**
a `QTimer`, to stop the animation you can use `Qtimer.stop` | [
"Schedule",
"a",
"function",
"to",
"be",
"called",
"repeated",
"time",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qtviewer.py#L87-L129 | train |
chemlab/chemlab | chemlab/graphics/qt/qtviewer.py | QtViewer.add_ui | def add_ui(self, klass, *args, **kwargs):
'''Add an UI element for the current scene. The approach is
the same as renderers.
.. warning:: The UI api is not yet finalized
'''
ui = klass(self.widget, *args, **kwargs)
self.widget.uis.append(ui)
return ui | python | def add_ui(self, klass, *args, **kwargs):
'''Add an UI element for the current scene. The approach is
the same as renderers.
.. warning:: The UI api is not yet finalized
'''
ui = klass(self.widget, *args, **kwargs)
self.widget.uis.append(ui)
return ui | [
"def",
"add_ui",
"(",
"self",
",",
"klass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ui",
"=",
"klass",
"(",
"self",
".",
"widget",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"widget",
".",
"uis",
".",
"append",
"(",
"ui",
")",
"return",
"ui"
] | Add an UI element for the current scene. The approach is
the same as renderers.
.. warning:: The UI api is not yet finalized | [
"Add",
"an",
"UI",
"element",
"for",
"the",
"current",
"scene",
".",
"The",
"approach",
"is",
"the",
"same",
"as",
"renderers",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qtviewer.py#L182-L191 | train |
chemlab/chemlab | chemlab/io/handlers/gamess.py | parse_card | def parse_card(card, text, default=None):
"""Parse a card from an input string
"""
match = re.search(card.lower() + r"\s*=\s*(\w+)", text.lower())
return match.group(1) if match else default | python | def parse_card(card, text, default=None):
"""Parse a card from an input string
"""
match = re.search(card.lower() + r"\s*=\s*(\w+)", text.lower())
return match.group(1) if match else default | [
"def",
"parse_card",
"(",
"card",
",",
"text",
",",
"default",
"=",
"None",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"card",
".",
"lower",
"(",
")",
"+",
"r\"\\s*=\\s*(\\w+)\"",
",",
"text",
".",
"lower",
"(",
")",
")",
"return",
"match",
".",
"group",
"(",
"1",
")",
"if",
"match",
"else",
"default"
] | Parse a card from an input string | [
"Parse",
"a",
"card",
"from",
"an",
"input",
"string"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L143-L148 | train |
chemlab/chemlab | chemlab/io/handlers/gamess.py | GamessDataParser._parse_geometry | def _parse_geometry(self, geom):
"""Parse a geometry string and return Molecule object from
it.
"""
atoms = []
for i, line in enumerate(geom.splitlines()):
sym, atno, x, y, z = line.split()
atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))
return Molecule(atoms) | python | def _parse_geometry(self, geom):
"""Parse a geometry string and return Molecule object from
it.
"""
atoms = []
for i, line in enumerate(geom.splitlines()):
sym, atno, x, y, z = line.split()
atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))
return Molecule(atoms) | [
"def",
"_parse_geometry",
"(",
"self",
",",
"geom",
")",
":",
"atoms",
"=",
"[",
"]",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"geom",
".",
"splitlines",
"(",
")",
")",
":",
"sym",
",",
"atno",
",",
"x",
",",
"y",
",",
"z",
"=",
"line",
".",
"split",
"(",
")",
"atoms",
".",
"append",
"(",
"Atom",
"(",
"sym",
",",
"[",
"float",
"(",
"x",
")",
",",
"float",
"(",
"y",
")",
",",
"float",
"(",
"z",
")",
"]",
",",
"id",
"=",
"i",
")",
")",
"return",
"Molecule",
"(",
"atoms",
")"
] | Parse a geometry string and return Molecule object from
it. | [
"Parse",
"a",
"geometry",
"string",
"and",
"return",
"Molecule",
"object",
"from",
"it",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L67-L77 | train |
chemlab/chemlab | chemlab/io/handlers/gamess.py | GamessDataParser.parse_optimize | def parse_optimize(self):
"""Parse the ouput resulted of a geometry optimization. Or a
saddle point.
"""
match = re.search("EQUILIBRIUM GEOMETRY LOCATED", self.text)
spmatch = "SADDLE POINT LOCATED" in self.text
located = True if match or spmatch else False
points = grep_split(" BEGINNING GEOMETRY SEARCH POINT NSERCH=",
self.text)
if self.tddft == "excite":
points = [self.parse_energy(point) for point in points[1:]]
else:
regex = re.compile(r'NSERCH:\s+\d+\s+E=\s+([+-]?\d+\.\d+)')
points = [Energy(states=[State(0,None,float(m.group(1)), 0.0, 0.0)]) for m in regex.finditer(self.text)]
# Error handling
if "FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN" in self.text:
self.errcode = GEOM_NOT_LOCATED
self.errmsg = "too many steps taken: %i"%len(points)
if located:
self.errcode = OK
return Optimize(points=points) | python | def parse_optimize(self):
"""Parse the ouput resulted of a geometry optimization. Or a
saddle point.
"""
match = re.search("EQUILIBRIUM GEOMETRY LOCATED", self.text)
spmatch = "SADDLE POINT LOCATED" in self.text
located = True if match or spmatch else False
points = grep_split(" BEGINNING GEOMETRY SEARCH POINT NSERCH=",
self.text)
if self.tddft == "excite":
points = [self.parse_energy(point) for point in points[1:]]
else:
regex = re.compile(r'NSERCH:\s+\d+\s+E=\s+([+-]?\d+\.\d+)')
points = [Energy(states=[State(0,None,float(m.group(1)), 0.0, 0.0)]) for m in regex.finditer(self.text)]
# Error handling
if "FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN" in self.text:
self.errcode = GEOM_NOT_LOCATED
self.errmsg = "too many steps taken: %i"%len(points)
if located:
self.errcode = OK
return Optimize(points=points) | [
"def",
"parse_optimize",
"(",
"self",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"\"EQUILIBRIUM GEOMETRY LOCATED\"",
",",
"self",
".",
"text",
")",
"spmatch",
"=",
"\"SADDLE POINT LOCATED\"",
"in",
"self",
".",
"text",
"located",
"=",
"True",
"if",
"match",
"or",
"spmatch",
"else",
"False",
"points",
"=",
"grep_split",
"(",
"\" BEGINNING GEOMETRY SEARCH POINT NSERCH=\"",
",",
"self",
".",
"text",
")",
"if",
"self",
".",
"tddft",
"==",
"\"excite\"",
":",
"points",
"=",
"[",
"self",
".",
"parse_energy",
"(",
"point",
")",
"for",
"point",
"in",
"points",
"[",
"1",
":",
"]",
"]",
"else",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'NSERCH:\\s+\\d+\\s+E=\\s+([+-]?\\d+\\.\\d+)'",
")",
"points",
"=",
"[",
"Energy",
"(",
"states",
"=",
"[",
"State",
"(",
"0",
",",
"None",
",",
"float",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
",",
"0.0",
",",
"0.0",
")",
"]",
")",
"for",
"m",
"in",
"regex",
".",
"finditer",
"(",
"self",
".",
"text",
")",
"]",
"# Error handling",
"if",
"\"FAILURE TO LOCATE STATIONARY POINT, TOO MANY STEPS TAKEN\"",
"in",
"self",
".",
"text",
":",
"self",
".",
"errcode",
"=",
"GEOM_NOT_LOCATED",
"self",
".",
"errmsg",
"=",
"\"too many steps taken: %i\"",
"%",
"len",
"(",
"points",
")",
"if",
"located",
":",
"self",
".",
"errcode",
"=",
"OK",
"return",
"Optimize",
"(",
"points",
"=",
"points",
")"
] | Parse the ouput resulted of a geometry optimization. Or a
saddle point. | [
"Parse",
"the",
"ouput",
"resulted",
"of",
"a",
"geometry",
"optimization",
".",
"Or",
"a",
"saddle",
"point",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/gamess.py#L79-L104 | train |
chemlab/chemlab | chemlab/graphics/renderers/cylinder_imp.py | CylinderImpostorRenderer.change_attributes | def change_attributes(self, bounds, radii, colors):
"""Reinitialize the buffers, to accomodate the new
attributes. This is used to change the number of cylinders to
be displayed.
"""
self.n_cylinders = len(bounds)
self.is_empty = True if self.n_cylinders == 0 else False
if self.is_empty:
self.bounds = bounds
self.radii = radii
self.colors = colors
return # Do nothing
# We pass the starting position 8 times, and each of these has
# a mapping to the bounding box corner.
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
local = np.array([
# First face -- front
0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
0.0, 0.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0,
# Second face -- back
0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0,
0.0, 0.0, 1.0,
1.0, 1.0, 1.0,
1.0, 0.0, 1.0,
# Third face -- left
0.0, 0.0, 0.0,
0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
0.0, 0.0, 0.0,
0.0, 1.0, 1.0,
0.0, 1.0, 0.0,
# Fourth face -- right
1.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 1.0, 1.0,
1.0, 0.0, 0.0,
1.0, 1.0, 1.0,
1.0, 1.0, 0.0,
# Fifth face -- up
0.0, 1.0, 0.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0,
0.0, 1.0, 0.0,
1.0, 1.0, 1.0,
1.0, 1.0, 0.0,
# Sixth face -- down
0.0, 0.0, 0.0,
0.0, 0.0, 1.0,
1.0, 0.0, 1.0,
0.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 0.0, 0.0,
]).astype('float32')
local = np.tile(local, self.n_cylinders)
self._verts_vbo = VertexBuffer(vertices,GL_DYNAMIC_DRAW)
self._directions_vbo = VertexBuffer(directions, GL_DYNAMIC_DRAW)
self._local_vbo = VertexBuffer(local,GL_DYNAMIC_DRAW)
self._color_vbo = VertexBuffer(prim_colors, GL_DYNAMIC_DRAW)
self._radii_vbo = VertexBuffer(prim_radii, GL_DYNAMIC_DRAW) | python | def change_attributes(self, bounds, radii, colors):
"""Reinitialize the buffers, to accomodate the new
attributes. This is used to change the number of cylinders to
be displayed.
"""
self.n_cylinders = len(bounds)
self.is_empty = True if self.n_cylinders == 0 else False
if self.is_empty:
self.bounds = bounds
self.radii = radii
self.colors = colors
return # Do nothing
# We pass the starting position 8 times, and each of these has
# a mapping to the bounding box corner.
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
local = np.array([
# First face -- front
0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
0.0, 0.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0,
# Second face -- back
0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0,
0.0, 0.0, 1.0,
1.0, 1.0, 1.0,
1.0, 0.0, 1.0,
# Third face -- left
0.0, 0.0, 0.0,
0.0, 0.0, 1.0,
0.0, 1.0, 1.0,
0.0, 0.0, 0.0,
0.0, 1.0, 1.0,
0.0, 1.0, 0.0,
# Fourth face -- right
1.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 1.0, 1.0,
1.0, 0.0, 0.0,
1.0, 1.0, 1.0,
1.0, 1.0, 0.0,
# Fifth face -- up
0.0, 1.0, 0.0,
0.0, 1.0, 1.0,
1.0, 1.0, 1.0,
0.0, 1.0, 0.0,
1.0, 1.0, 1.0,
1.0, 1.0, 0.0,
# Sixth face -- down
0.0, 0.0, 0.0,
0.0, 0.0, 1.0,
1.0, 0.0, 1.0,
0.0, 0.0, 0.0,
1.0, 0.0, 1.0,
1.0, 0.0, 0.0,
]).astype('float32')
local = np.tile(local, self.n_cylinders)
self._verts_vbo = VertexBuffer(vertices,GL_DYNAMIC_DRAW)
self._directions_vbo = VertexBuffer(directions, GL_DYNAMIC_DRAW)
self._local_vbo = VertexBuffer(local,GL_DYNAMIC_DRAW)
self._color_vbo = VertexBuffer(prim_colors, GL_DYNAMIC_DRAW)
self._radii_vbo = VertexBuffer(prim_radii, GL_DYNAMIC_DRAW) | [
"def",
"change_attributes",
"(",
"self",
",",
"bounds",
",",
"radii",
",",
"colors",
")",
":",
"self",
".",
"n_cylinders",
"=",
"len",
"(",
"bounds",
")",
"self",
".",
"is_empty",
"=",
"True",
"if",
"self",
".",
"n_cylinders",
"==",
"0",
"else",
"False",
"if",
"self",
".",
"is_empty",
":",
"self",
".",
"bounds",
"=",
"bounds",
"self",
".",
"radii",
"=",
"radii",
"self",
".",
"colors",
"=",
"colors",
"return",
"# Do nothing",
"# We pass the starting position 8 times, and each of these has",
"# a mapping to the bounding box corner.",
"self",
".",
"bounds",
"=",
"np",
".",
"array",
"(",
"bounds",
",",
"dtype",
"=",
"'float32'",
")",
"vertices",
",",
"directions",
"=",
"self",
".",
"_gen_bounds",
"(",
"self",
".",
"bounds",
")",
"self",
".",
"radii",
"=",
"np",
".",
"array",
"(",
"radii",
",",
"dtype",
"=",
"'float32'",
")",
"prim_radii",
"=",
"self",
".",
"_gen_radii",
"(",
"self",
".",
"radii",
")",
"self",
".",
"colors",
"=",
"np",
".",
"array",
"(",
"colors",
",",
"dtype",
"=",
"'uint8'",
")",
"prim_colors",
"=",
"self",
".",
"_gen_colors",
"(",
"self",
".",
"colors",
")",
"local",
"=",
"np",
".",
"array",
"(",
"[",
"# First face -- front",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"# Second face -- back",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"# Third face -- left",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"# Fourth face -- right",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"# Fifth face -- up",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"# Sixth face -- down",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
",",
"0.0",
",",
"1.0",
",",
"1.0",
",",
"0.0",
",",
"0.0",
",",
"]",
")",
".",
"astype",
"(",
"'float32'",
")",
"local",
"=",
"np",
".",
"tile",
"(",
"local",
",",
"self",
".",
"n_cylinders",
")",
"self",
".",
"_verts_vbo",
"=",
"VertexBuffer",
"(",
"vertices",
",",
"GL_DYNAMIC_DRAW",
")",
"self",
".",
"_directions_vbo",
"=",
"VertexBuffer",
"(",
"directions",
",",
"GL_DYNAMIC_DRAW",
")",
"self",
".",
"_local_vbo",
"=",
"VertexBuffer",
"(",
"local",
",",
"GL_DYNAMIC_DRAW",
")",
"self",
".",
"_color_vbo",
"=",
"VertexBuffer",
"(",
"prim_colors",
",",
"GL_DYNAMIC_DRAW",
")",
"self",
".",
"_radii_vbo",
"=",
"VertexBuffer",
"(",
"prim_radii",
",",
"GL_DYNAMIC_DRAW",
")"
] | Reinitialize the buffers, to accomodate the new
attributes. This is used to change the number of cylinders to
be displayed. | [
"Reinitialize",
"the",
"buffers",
"to",
"accomodate",
"the",
"new",
"attributes",
".",
"This",
"is",
"used",
"to",
"change",
"the",
"number",
"of",
"cylinders",
"to",
"be",
"displayed",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L32-L123 | train |
chemlab/chemlab | chemlab/graphics/renderers/cylinder_imp.py | CylinderImpostorRenderer.update_bounds | def update_bounds(self, bounds):
'''Update the bounds inplace'''
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self._verts_vbo.set_data(vertices)
self._directions_vbo.set_data(directions)
self.widget.update() | python | def update_bounds(self, bounds):
'''Update the bounds inplace'''
self.bounds = np.array(bounds, dtype='float32')
vertices, directions = self._gen_bounds(self.bounds)
self._verts_vbo.set_data(vertices)
self._directions_vbo.set_data(directions)
self.widget.update() | [
"def",
"update_bounds",
"(",
"self",
",",
"bounds",
")",
":",
"self",
".",
"bounds",
"=",
"np",
".",
"array",
"(",
"bounds",
",",
"dtype",
"=",
"'float32'",
")",
"vertices",
",",
"directions",
"=",
"self",
".",
"_gen_bounds",
"(",
"self",
".",
"bounds",
")",
"self",
".",
"_verts_vbo",
".",
"set_data",
"(",
"vertices",
")",
"self",
".",
"_directions_vbo",
".",
"set_data",
"(",
"directions",
")",
"self",
".",
"widget",
".",
"update",
"(",
")"
] | Update the bounds inplace | [
"Update",
"the",
"bounds",
"inplace"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L209-L216 | train |
chemlab/chemlab | chemlab/graphics/renderers/cylinder_imp.py | CylinderImpostorRenderer.update_radii | def update_radii(self, radii):
'''Update the radii inplace'''
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self._radii_vbo.set_data(prim_radii)
self.widget.update() | python | def update_radii(self, radii):
'''Update the radii inplace'''
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self._radii_vbo.set_data(prim_radii)
self.widget.update() | [
"def",
"update_radii",
"(",
"self",
",",
"radii",
")",
":",
"self",
".",
"radii",
"=",
"np",
".",
"array",
"(",
"radii",
",",
"dtype",
"=",
"'float32'",
")",
"prim_radii",
"=",
"self",
".",
"_gen_radii",
"(",
"self",
".",
"radii",
")",
"self",
".",
"_radii_vbo",
".",
"set_data",
"(",
"prim_radii",
")",
"self",
".",
"widget",
".",
"update",
"(",
")"
] | Update the radii inplace | [
"Update",
"the",
"radii",
"inplace"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L218-L224 | train |
chemlab/chemlab | chemlab/graphics/renderers/cylinder_imp.py | CylinderImpostorRenderer.update_colors | def update_colors(self, colors):
'''Update the colors inplace'''
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
self._color_vbo.set_data(prim_colors)
self.widget.update() | python | def update_colors(self, colors):
'''Update the colors inplace'''
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
self._color_vbo.set_data(prim_colors)
self.widget.update() | [
"def",
"update_colors",
"(",
"self",
",",
"colors",
")",
":",
"self",
".",
"colors",
"=",
"np",
".",
"array",
"(",
"colors",
",",
"dtype",
"=",
"'uint8'",
")",
"prim_colors",
"=",
"self",
".",
"_gen_colors",
"(",
"self",
".",
"colors",
")",
"self",
".",
"_color_vbo",
".",
"set_data",
"(",
"prim_colors",
")",
"self",
".",
"widget",
".",
"update",
"(",
")"
] | Update the colors inplace | [
"Update",
"the",
"colors",
"inplace"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/cylinder_imp.py#L226-L232 | train |
chemlab/chemlab | chemlab/notebook/display.py | Display.system | def system(self, object, highlight=None, alpha=1.0, color=None,
transparent=None):
'''Display System object'''
if self.backend == 'povray':
kwargs = {}
if color is not None:
kwargs['color'] = color
else:
kwargs['color'] = default_colormap[object.type_array]
self.plotter.camera.autozoom(object.r_array)
self.plotter.points(object.r_array, alpha=alpha, **kwargs)
return self | python | def system(self, object, highlight=None, alpha=1.0, color=None,
transparent=None):
'''Display System object'''
if self.backend == 'povray':
kwargs = {}
if color is not None:
kwargs['color'] = color
else:
kwargs['color'] = default_colormap[object.type_array]
self.plotter.camera.autozoom(object.r_array)
self.plotter.points(object.r_array, alpha=alpha, **kwargs)
return self | [
"def",
"system",
"(",
"self",
",",
"object",
",",
"highlight",
"=",
"None",
",",
"alpha",
"=",
"1.0",
",",
"color",
"=",
"None",
",",
"transparent",
"=",
"None",
")",
":",
"if",
"self",
".",
"backend",
"==",
"'povray'",
":",
"kwargs",
"=",
"{",
"}",
"if",
"color",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'color'",
"]",
"=",
"color",
"else",
":",
"kwargs",
"[",
"'color'",
"]",
"=",
"default_colormap",
"[",
"object",
".",
"type_array",
"]",
"self",
".",
"plotter",
".",
"camera",
".",
"autozoom",
"(",
"object",
".",
"r_array",
")",
"self",
".",
"plotter",
".",
"points",
"(",
"object",
".",
"r_array",
",",
"alpha",
"=",
"alpha",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"
] | Display System object | [
"Display",
"System",
"object"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/notebook/display.py#L17-L29 | train |
chemlab/chemlab | chemlab/contrib/gromacs.py | make_gromacs | def make_gromacs(simulation, directory, clean=False):
"""Create gromacs directory structure"""
if clean is False and os.path.exists(directory):
raise ValueError(
'Cannot override {}, use option clean=True'.format(directory))
else:
shutil.rmtree(directory, ignore_errors=True)
os.mkdir(directory)
# Check custom simulation potential
if simulation.potential.intermolecular.type == 'custom':
for pair in simulation.potential.intermolecular.special_pairs:
table = to_table(simulation.potential.intermolecular.pair_interaction(*pair),
simulation.cutoff)
fname1 = os.path.join(directory,
'table_{}_{}.xvg'.format(pair[0], pair[1]))
fname2 = os.path.join(directory,
'table_{}_{}.xvg'.format(pair[1], pair[0]))
with open(fname1, 'w') as fd:
fd.write(table)
with open(fname2, 'w') as fd:
fd.write(table)
ndx = {'System' : np.arange(simulation.system.n_atoms, dtype='int')}
for particle in simulation.potential.intermolecular.particles:
idx = simulation.system.where(atom_name=particle)['atom'].nonzero()[0]
ndx[particle] = idx
with open(os.path.join(directory, 'index.ndx'), 'w') as fd:
fd.write(to_ndx(ndx))
# Parameter file
mdpfile = to_mdp(simulation)
with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd:
fd.write(mdpfile)
# Topology file
topfile = to_top(simulation.system, simulation.potential)
with open(os.path.join(directory, 'topol.top'), 'w') as fd:
fd.write(topfile)
# Simulation file
datafile(os.path.join(directory, 'conf.gro'),
'w').write('system', simulation.system)
return directory | python | def make_gromacs(simulation, directory, clean=False):
"""Create gromacs directory structure"""
if clean is False and os.path.exists(directory):
raise ValueError(
'Cannot override {}, use option clean=True'.format(directory))
else:
shutil.rmtree(directory, ignore_errors=True)
os.mkdir(directory)
# Check custom simulation potential
if simulation.potential.intermolecular.type == 'custom':
for pair in simulation.potential.intermolecular.special_pairs:
table = to_table(simulation.potential.intermolecular.pair_interaction(*pair),
simulation.cutoff)
fname1 = os.path.join(directory,
'table_{}_{}.xvg'.format(pair[0], pair[1]))
fname2 = os.path.join(directory,
'table_{}_{}.xvg'.format(pair[1], pair[0]))
with open(fname1, 'w') as fd:
fd.write(table)
with open(fname2, 'w') as fd:
fd.write(table)
ndx = {'System' : np.arange(simulation.system.n_atoms, dtype='int')}
for particle in simulation.potential.intermolecular.particles:
idx = simulation.system.where(atom_name=particle)['atom'].nonzero()[0]
ndx[particle] = idx
with open(os.path.join(directory, 'index.ndx'), 'w') as fd:
fd.write(to_ndx(ndx))
# Parameter file
mdpfile = to_mdp(simulation)
with open(os.path.join(directory, 'grompp.mdp'), 'w') as fd:
fd.write(mdpfile)
# Topology file
topfile = to_top(simulation.system, simulation.potential)
with open(os.path.join(directory, 'topol.top'), 'w') as fd:
fd.write(topfile)
# Simulation file
datafile(os.path.join(directory, 'conf.gro'),
'w').write('system', simulation.system)
return directory | [
"def",
"make_gromacs",
"(",
"simulation",
",",
"directory",
",",
"clean",
"=",
"False",
")",
":",
"if",
"clean",
"is",
"False",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot override {}, use option clean=True'",
".",
"format",
"(",
"directory",
")",
")",
"else",
":",
"shutil",
".",
"rmtree",
"(",
"directory",
",",
"ignore_errors",
"=",
"True",
")",
"os",
".",
"mkdir",
"(",
"directory",
")",
"# Check custom simulation potential",
"if",
"simulation",
".",
"potential",
".",
"intermolecular",
".",
"type",
"==",
"'custom'",
":",
"for",
"pair",
"in",
"simulation",
".",
"potential",
".",
"intermolecular",
".",
"special_pairs",
":",
"table",
"=",
"to_table",
"(",
"simulation",
".",
"potential",
".",
"intermolecular",
".",
"pair_interaction",
"(",
"*",
"pair",
")",
",",
"simulation",
".",
"cutoff",
")",
"fname1",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'table_{}_{}.xvg'",
".",
"format",
"(",
"pair",
"[",
"0",
"]",
",",
"pair",
"[",
"1",
"]",
")",
")",
"fname2",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'table_{}_{}.xvg'",
".",
"format",
"(",
"pair",
"[",
"1",
"]",
",",
"pair",
"[",
"0",
"]",
")",
")",
"with",
"open",
"(",
"fname1",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"table",
")",
"with",
"open",
"(",
"fname2",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"table",
")",
"ndx",
"=",
"{",
"'System'",
":",
"np",
".",
"arange",
"(",
"simulation",
".",
"system",
".",
"n_atoms",
",",
"dtype",
"=",
"'int'",
")",
"}",
"for",
"particle",
"in",
"simulation",
".",
"potential",
".",
"intermolecular",
".",
"particles",
":",
"idx",
"=",
"simulation",
".",
"system",
".",
"where",
"(",
"atom_name",
"=",
"particle",
")",
"[",
"'atom'",
"]",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"ndx",
"[",
"particle",
"]",
"=",
"idx",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'index.ndx'",
")",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"to_ndx",
"(",
"ndx",
")",
")",
"# Parameter file",
"mdpfile",
"=",
"to_mdp",
"(",
"simulation",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'grompp.mdp'",
")",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"mdpfile",
")",
"# Topology file",
"topfile",
"=",
"to_top",
"(",
"simulation",
".",
"system",
",",
"simulation",
".",
"potential",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'topol.top'",
")",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"topfile",
")",
"# Simulation file",
"datafile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'conf.gro'",
")",
",",
"'w'",
")",
".",
"write",
"(",
"'system'",
",",
"simulation",
".",
"system",
")",
"return",
"directory"
] | Create gromacs directory structure | [
"Create",
"gromacs",
"directory",
"structure"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/contrib/gromacs.py#L125-L175 | train |
chemlab/chemlab | chemlab/graphics/renderers/triangles.py | TriangleRenderer.update_vertices | def update_vertices(self, vertices):
"""
Update the triangle vertices.
"""
vertices = np.array(vertices, dtype=np.float32)
self._vbo_v.set_data(vertices) | python | def update_vertices(self, vertices):
"""
Update the triangle vertices.
"""
vertices = np.array(vertices, dtype=np.float32)
self._vbo_v.set_data(vertices) | [
"def",
"update_vertices",
"(",
"self",
",",
"vertices",
")",
":",
"vertices",
"=",
"np",
".",
"array",
"(",
"vertices",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"self",
".",
"_vbo_v",
".",
"set_data",
"(",
"vertices",
")"
] | Update the triangle vertices. | [
"Update",
"the",
"triangle",
"vertices",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/triangles.py#L86-L92 | train |
chemlab/chemlab | chemlab/graphics/renderers/triangles.py | TriangleRenderer.update_normals | def update_normals(self, normals):
"""
Update the triangle normals.
"""
normals = np.array(normals, dtype=np.float32)
self._vbo_n.set_data(normals) | python | def update_normals(self, normals):
"""
Update the triangle normals.
"""
normals = np.array(normals, dtype=np.float32)
self._vbo_n.set_data(normals) | [
"def",
"update_normals",
"(",
"self",
",",
"normals",
")",
":",
"normals",
"=",
"np",
".",
"array",
"(",
"normals",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"self",
".",
"_vbo_n",
".",
"set_data",
"(",
"normals",
")"
] | Update the triangle normals. | [
"Update",
"the",
"triangle",
"normals",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/renderers/triangles.py#L94-L100 | train |
chemlab/chemlab | chemlab/graphics/qt/qttrajectory.py | TrajectoryControls.set_ticks | def set_ticks(self, number):
'''Set the number of frames to animate.
'''
self.max_index = number
self.current_index = 0
self.slider.setMaximum(self.max_index-1)
self.slider.setMinimum(0)
self.slider.setPageStep(1) | python | def set_ticks(self, number):
'''Set the number of frames to animate.
'''
self.max_index = number
self.current_index = 0
self.slider.setMaximum(self.max_index-1)
self.slider.setMinimum(0)
self.slider.setPageStep(1) | [
"def",
"set_ticks",
"(",
"self",
",",
"number",
")",
":",
"self",
".",
"max_index",
"=",
"number",
"self",
".",
"current_index",
"=",
"0",
"self",
".",
"slider",
".",
"setMaximum",
"(",
"self",
".",
"max_index",
"-",
"1",
")",
"self",
".",
"slider",
".",
"setMinimum",
"(",
"0",
")",
"self",
".",
"slider",
".",
"setPageStep",
"(",
"1",
")"
] | Set the number of frames to animate. | [
"Set",
"the",
"number",
"of",
"frames",
"to",
"animate",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L229-L237 | train |
chemlab/chemlab | chemlab/graphics/qt/qttrajectory.py | QtTrajectoryViewer.set_text | def set_text(self, text):
'''Update the time indicator in the interface.
'''
self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text)) | python | def set_text(self, text):
'''Update the time indicator in the interface.
'''
self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text)) | [
"def",
"set_text",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"traj_controls",
".",
"timelabel",
".",
"setText",
"(",
"self",
".",
"traj_controls",
".",
"_label_tmp",
".",
"format",
"(",
"text",
")",
")"
] | Update the time indicator in the interface. | [
"Update",
"the",
"time",
"indicator",
"in",
"the",
"interface",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L316-L320 | train |
chemlab/chemlab | chemlab/graphics/qt/qttrajectory.py | QtTrajectoryViewer.update_function | def update_function(self, func, frames=None):
'''Set the function to be called when it's time to display a frame.
*func* should be a function that takes one integer argument that
represents the frame that has to be played::
def func(index):
# Update the renderers to match the
# current animation index
'''
# Back-compatibility
if frames is not None:
self.traj_controls.set_ticks(frames)
self._update_function = func | python | def update_function(self, func, frames=None):
'''Set the function to be called when it's time to display a frame.
*func* should be a function that takes one integer argument that
represents the frame that has to be played::
def func(index):
# Update the renderers to match the
# current animation index
'''
# Back-compatibility
if frames is not None:
self.traj_controls.set_ticks(frames)
self._update_function = func | [
"def",
"update_function",
"(",
"self",
",",
"func",
",",
"frames",
"=",
"None",
")",
":",
"# Back-compatibility",
"if",
"frames",
"is",
"not",
"None",
":",
"self",
".",
"traj_controls",
".",
"set_ticks",
"(",
"frames",
")",
"self",
".",
"_update_function",
"=",
"func"
] | Set the function to be called when it's time to display a frame.
*func* should be a function that takes one integer argument that
represents the frame that has to be played::
def func(index):
# Update the renderers to match the
# current animation index | [
"Set",
"the",
"function",
"to",
"be",
"called",
"when",
"it",
"s",
"time",
"to",
"display",
"a",
"frame",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/qt/qttrajectory.py#L371-L386 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | rotation_matrix | def rotation_matrix(angle, direction):
"""
Create a rotation matrix corresponding to the rotation around a general
axis by a specified angle.
R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)
Parameters:
angle : float a
direction : array d
"""
d = numpy.array(direction, dtype=numpy.float64)
d /= numpy.linalg.norm(d)
eye = numpy.eye(3, dtype=numpy.float64)
ddt = numpy.outer(d, d)
skew = numpy.array([[ 0, d[2], -d[1]],
[-d[2], 0, d[0]],
[d[1], -d[0], 0]], dtype=numpy.float64)
mtx = ddt + numpy.cos(angle) * (eye - ddt) + numpy.sin(angle) * skew
M = numpy.eye(4)
M[:3,:3] = mtx
return M | python | def rotation_matrix(angle, direction):
"""
Create a rotation matrix corresponding to the rotation around a general
axis by a specified angle.
R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)
Parameters:
angle : float a
direction : array d
"""
d = numpy.array(direction, dtype=numpy.float64)
d /= numpy.linalg.norm(d)
eye = numpy.eye(3, dtype=numpy.float64)
ddt = numpy.outer(d, d)
skew = numpy.array([[ 0, d[2], -d[1]],
[-d[2], 0, d[0]],
[d[1], -d[0], 0]], dtype=numpy.float64)
mtx = ddt + numpy.cos(angle) * (eye - ddt) + numpy.sin(angle) * skew
M = numpy.eye(4)
M[:3,:3] = mtx
return M | [
"def",
"rotation_matrix",
"(",
"angle",
",",
"direction",
")",
":",
"d",
"=",
"numpy",
".",
"array",
"(",
"direction",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"d",
"/=",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"d",
")",
"eye",
"=",
"numpy",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"ddt",
"=",
"numpy",
".",
"outer",
"(",
"d",
",",
"d",
")",
"skew",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"0",
",",
"d",
"[",
"2",
"]",
",",
"-",
"d",
"[",
"1",
"]",
"]",
",",
"[",
"-",
"d",
"[",
"2",
"]",
",",
"0",
",",
"d",
"[",
"0",
"]",
"]",
",",
"[",
"d",
"[",
"1",
"]",
",",
"-",
"d",
"[",
"0",
"]",
",",
"0",
"]",
"]",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"mtx",
"=",
"ddt",
"+",
"numpy",
".",
"cos",
"(",
"angle",
")",
"*",
"(",
"eye",
"-",
"ddt",
")",
"+",
"numpy",
".",
"sin",
"(",
"angle",
")",
"*",
"skew",
"M",
"=",
"numpy",
".",
"eye",
"(",
"4",
")",
"M",
"[",
":",
"3",
",",
":",
"3",
"]",
"=",
"mtx",
"return",
"M"
] | Create a rotation matrix corresponding to the rotation around a general
axis by a specified angle.
R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)
Parameters:
angle : float a
direction : array d | [
"Create",
"a",
"rotation",
"matrix",
"corresponding",
"to",
"the",
"rotation",
"around",
"a",
"general",
"axis",
"by",
"a",
"specified",
"angle",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L341-L366 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | rotation_from_matrix | def rotation_from_matrix(matrix):
"""Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
"""
R = numpy.array(matrix, dtype=numpy.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = numpy.linalg.eig(R33.T)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
direction = numpy.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R33 corresponding to eigenvalue of 1
w, Q = numpy.linalg.eig(R)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on direction
cosa = (numpy.trace(R33) - 1.0) / 2.0
if abs(direction[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
elif abs(direction[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
else:
sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
angle = math.atan2(sina, cosa)
return angle, direction, point | python | def rotation_from_matrix(matrix):
"""Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
"""
R = numpy.array(matrix, dtype=numpy.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = numpy.linalg.eig(R33.T)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
direction = numpy.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R33 corresponding to eigenvalue of 1
w, Q = numpy.linalg.eig(R)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on direction
cosa = (numpy.trace(R33) - 1.0) / 2.0
if abs(direction[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
elif abs(direction[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
else:
sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
angle = math.atan2(sina, cosa)
return angle, direction, point | [
"def",
"rotation_from_matrix",
"(",
"matrix",
")",
":",
"R",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"R33",
"=",
"R",
"[",
":",
"3",
",",
":",
"3",
"]",
"# direction: unit eigenvector of R33 corresponding to eigenvalue of 1",
"w",
",",
"W",
"=",
"numpy",
".",
"linalg",
".",
"eig",
"(",
"R33",
".",
"T",
")",
"i",
"=",
"numpy",
".",
"where",
"(",
"abs",
"(",
"numpy",
".",
"real",
"(",
"w",
")",
"-",
"1.0",
")",
"<",
"1e-8",
")",
"[",
"0",
"]",
"if",
"not",
"len",
"(",
"i",
")",
":",
"raise",
"ValueError",
"(",
"\"no unit eigenvector corresponding to eigenvalue 1\"",
")",
"direction",
"=",
"numpy",
".",
"real",
"(",
"W",
"[",
":",
",",
"i",
"[",
"-",
"1",
"]",
"]",
")",
".",
"squeeze",
"(",
")",
"# point: unit eigenvector of R33 corresponding to eigenvalue of 1",
"w",
",",
"Q",
"=",
"numpy",
".",
"linalg",
".",
"eig",
"(",
"R",
")",
"i",
"=",
"numpy",
".",
"where",
"(",
"abs",
"(",
"numpy",
".",
"real",
"(",
"w",
")",
"-",
"1.0",
")",
"<",
"1e-8",
")",
"[",
"0",
"]",
"if",
"not",
"len",
"(",
"i",
")",
":",
"raise",
"ValueError",
"(",
"\"no unit eigenvector corresponding to eigenvalue 1\"",
")",
"point",
"=",
"numpy",
".",
"real",
"(",
"Q",
"[",
":",
",",
"i",
"[",
"-",
"1",
"]",
"]",
")",
".",
"squeeze",
"(",
")",
"point",
"/=",
"point",
"[",
"3",
"]",
"# rotation angle depending on direction",
"cosa",
"=",
"(",
"numpy",
".",
"trace",
"(",
"R33",
")",
"-",
"1.0",
")",
"/",
"2.0",
"if",
"abs",
"(",
"direction",
"[",
"2",
"]",
")",
">",
"1e-8",
":",
"sina",
"=",
"(",
"R",
"[",
"1",
",",
"0",
"]",
"+",
"(",
"cosa",
"-",
"1.0",
")",
"*",
"direction",
"[",
"0",
"]",
"*",
"direction",
"[",
"1",
"]",
")",
"/",
"direction",
"[",
"2",
"]",
"elif",
"abs",
"(",
"direction",
"[",
"1",
"]",
")",
">",
"1e-8",
":",
"sina",
"=",
"(",
"R",
"[",
"0",
",",
"2",
"]",
"+",
"(",
"cosa",
"-",
"1.0",
")",
"*",
"direction",
"[",
"0",
"]",
"*",
"direction",
"[",
"2",
"]",
")",
"/",
"direction",
"[",
"1",
"]",
"else",
":",
"sina",
"=",
"(",
"R",
"[",
"2",
",",
"1",
"]",
"+",
"(",
"cosa",
"-",
"1.0",
")",
"*",
"direction",
"[",
"1",
"]",
"*",
"direction",
"[",
"2",
"]",
")",
"/",
"direction",
"[",
"0",
"]",
"angle",
"=",
"math",
".",
"atan2",
"(",
"sina",
",",
"cosa",
")",
"return",
"angle",
",",
"direction",
",",
"point"
] | Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True | [
"Return",
"rotation",
"angle",
"and",
"axis",
"from",
"rotation",
"matrix",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L369-L406 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | scale_from_matrix | def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
factor = numpy.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0]
direction = numpy.real(V[:, i]).squeeze()
direction /= vector_norm(direction)
except IndexError:
# uniform scaling
factor = (factor + 2.0) / 3.0
direction = None
# origin: any eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
origin = numpy.real(V[:, i[-1]]).squeeze()
origin /= origin[3]
return factor, origin, direction | python | def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
factor = numpy.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0]
direction = numpy.real(V[:, i]).squeeze()
direction /= vector_norm(direction)
except IndexError:
# uniform scaling
factor = (factor + 2.0) / 3.0
direction = None
# origin: any eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
origin = numpy.real(V[:, i[-1]]).squeeze()
origin /= origin[3]
return factor, origin, direction | [
"def",
"scale_from_matrix",
"(",
"matrix",
")",
":",
"M",
"=",
"numpy",
".",
"array",
"(",
"matrix",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"M33",
"=",
"M",
"[",
":",
"3",
",",
":",
"3",
"]",
"factor",
"=",
"numpy",
".",
"trace",
"(",
"M33",
")",
"-",
"2.0",
"try",
":",
"# direction: unit eigenvector corresponding to eigenvalue factor",
"w",
",",
"V",
"=",
"numpy",
".",
"linalg",
".",
"eig",
"(",
"M33",
")",
"i",
"=",
"numpy",
".",
"where",
"(",
"abs",
"(",
"numpy",
".",
"real",
"(",
"w",
")",
"-",
"factor",
")",
"<",
"1e-8",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"direction",
"=",
"numpy",
".",
"real",
"(",
"V",
"[",
":",
",",
"i",
"]",
")",
".",
"squeeze",
"(",
")",
"direction",
"/=",
"vector_norm",
"(",
"direction",
")",
"except",
"IndexError",
":",
"# uniform scaling",
"factor",
"=",
"(",
"factor",
"+",
"2.0",
")",
"/",
"3.0",
"direction",
"=",
"None",
"# origin: any eigenvector corresponding to eigenvalue 1",
"w",
",",
"V",
"=",
"numpy",
".",
"linalg",
".",
"eig",
"(",
"M",
")",
"i",
"=",
"numpy",
".",
"where",
"(",
"abs",
"(",
"numpy",
".",
"real",
"(",
"w",
")",
"-",
"1.0",
")",
"<",
"1e-8",
")",
"[",
"0",
"]",
"if",
"not",
"len",
"(",
"i",
")",
":",
"raise",
"ValueError",
"(",
"\"no eigenvector corresponding to eigenvalue 1\"",
")",
"origin",
"=",
"numpy",
".",
"real",
"(",
"V",
"[",
":",
",",
"i",
"[",
"-",
"1",
"]",
"]",
")",
".",
"squeeze",
"(",
")",
"origin",
"/=",
"origin",
"[",
"3",
"]",
"return",
"factor",
",",
"origin",
",",
"direction"
] | Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True | [
"Return",
"scaling",
"factor",
"origin",
"and",
"direction",
"from",
"scaling",
"matrix",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L443-L481 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | orthogonalization_matrix | def orthogonalization_matrix(lengths, angles):
"""Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True
"""
a, b, c = lengths
angles = numpy.radians(angles)
sina, sinb, _ = numpy.sin(angles)
cosa, cosb, cosg = numpy.cos(angles)
co = (cosa * cosb - cosg) / (sina * sinb)
return numpy.array([
[ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0],
[-a*sinb*co, b*sina, 0.0, 0.0],
[ a*cosb, b*cosa, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0]]) | python | def orthogonalization_matrix(lengths, angles):
"""Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True
"""
a, b, c = lengths
angles = numpy.radians(angles)
sina, sinb, _ = numpy.sin(angles)
cosa, cosb, cosg = numpy.cos(angles)
co = (cosa * cosb - cosg) / (sina * sinb)
return numpy.array([
[ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0],
[-a*sinb*co, b*sina, 0.0, 0.0],
[ a*cosb, b*cosa, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0]]) | [
"def",
"orthogonalization_matrix",
"(",
"lengths",
",",
"angles",
")",
":",
"a",
",",
"b",
",",
"c",
"=",
"lengths",
"angles",
"=",
"numpy",
".",
"radians",
"(",
"angles",
")",
"sina",
",",
"sinb",
",",
"_",
"=",
"numpy",
".",
"sin",
"(",
"angles",
")",
"cosa",
",",
"cosb",
",",
"cosg",
"=",
"numpy",
".",
"cos",
"(",
"angles",
")",
"co",
"=",
"(",
"cosa",
"*",
"cosb",
"-",
"cosg",
")",
"/",
"(",
"sina",
"*",
"sinb",
")",
"return",
"numpy",
".",
"array",
"(",
"[",
"[",
"a",
"*",
"sinb",
"*",
"math",
".",
"sqrt",
"(",
"1.0",
"-",
"co",
"*",
"co",
")",
",",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
",",
"[",
"-",
"a",
"*",
"sinb",
"*",
"co",
",",
"b",
"*",
"sina",
",",
"0.0",
",",
"0.0",
"]",
",",
"[",
"a",
"*",
"cosb",
",",
"b",
"*",
"cosa",
",",
"c",
",",
"0.0",
"]",
",",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"]",
")"
] | Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True | [
"Return",
"orthogonalization",
"matrix",
"for",
"crystallographic",
"cell",
"coordinates",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L903-L927 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | superimposition_matrix | def superimposition_matrix(v0, v1, scale=False, usesvd=True):
"""Return matrix to transform given 3D point set into second point set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points.
The parameters scale and usesvd are explained in the more general
affine_matrix_from_points function.
The returned matrix is a similarity or Eucledian transformation matrix.
This function has a fast C implementation in transformations.c.
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scale=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3))
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]
return affine_matrix_from_points(v0, v1, shear=False,
scale=scale, usesvd=usesvd) | python | def superimposition_matrix(v0, v1, scale=False, usesvd=True):
"""Return matrix to transform given 3D point set into second point set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points.
The parameters scale and usesvd are explained in the more general
affine_matrix_from_points function.
The returned matrix is a similarity or Eucledian transformation matrix.
This function has a fast C implementation in transformations.c.
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scale=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3))
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]
return affine_matrix_from_points(v0, v1, shear=False,
scale=scale, usesvd=usesvd) | [
"def",
"superimposition_matrix",
"(",
"v0",
",",
"v1",
",",
"scale",
"=",
"False",
",",
"usesvd",
"=",
"True",
")",
":",
"v0",
"=",
"numpy",
".",
"array",
"(",
"v0",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"[",
":",
"3",
"]",
"v1",
"=",
"numpy",
".",
"array",
"(",
"v1",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"[",
":",
"3",
"]",
"return",
"affine_matrix_from_points",
"(",
"v0",
",",
"v1",
",",
"shear",
"=",
"False",
",",
"scale",
"=",
"scale",
",",
"usesvd",
"=",
"usesvd",
")"
] | Return matrix to transform given 3D point set into second point set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points.
The parameters scale and usesvd are explained in the more general
affine_matrix_from_points function.
The returned matrix is a similarity or Eucledian transformation matrix.
This function has a fast C implementation in transformations.c.
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scale=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3))
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True | [
"Return",
"matrix",
"to",
"transform",
"given",
"3D",
"point",
"set",
"into",
"second",
"point",
"set",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1039-L1087 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | quaternion_matrix | def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> numpy.allclose(M, numpy.diag([1, -1, -1, 1]))
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
n = numpy.dot(q, q)
if n < _EPS:
return numpy.identity(4)
q *= math.sqrt(2.0 / n)
q = numpy.outer(q, q)
return numpy.array([
[1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0],
[ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0],
[ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0],
[ 0.0, 0.0, 0.0, 1.0]]) | python | def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> numpy.allclose(M, numpy.diag([1, -1, -1, 1]))
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
n = numpy.dot(q, q)
if n < _EPS:
return numpy.identity(4)
q *= math.sqrt(2.0 / n)
q = numpy.outer(q, q)
return numpy.array([
[1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0],
[ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0],
[ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0],
[ 0.0, 0.0, 0.0, 1.0]]) | [
"def",
"quaternion_matrix",
"(",
"quaternion",
")",
":",
"q",
"=",
"numpy",
".",
"array",
"(",
"quaternion",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"n",
"=",
"numpy",
".",
"dot",
"(",
"q",
",",
"q",
")",
"if",
"n",
"<",
"_EPS",
":",
"return",
"numpy",
".",
"identity",
"(",
"4",
")",
"q",
"*=",
"math",
".",
"sqrt",
"(",
"2.0",
"/",
"n",
")",
"q",
"=",
"numpy",
".",
"outer",
"(",
"q",
",",
"q",
")",
"return",
"numpy",
".",
"array",
"(",
"[",
"[",
"1.0",
"-",
"q",
"[",
"2",
",",
"2",
"]",
"-",
"q",
"[",
"3",
",",
"3",
"]",
",",
"q",
"[",
"1",
",",
"2",
"]",
"-",
"q",
"[",
"3",
",",
"0",
"]",
",",
"q",
"[",
"1",
",",
"3",
"]",
"+",
"q",
"[",
"2",
",",
"0",
"]",
",",
"0.0",
"]",
",",
"[",
"q",
"[",
"1",
",",
"2",
"]",
"+",
"q",
"[",
"3",
",",
"0",
"]",
",",
"1.0",
"-",
"q",
"[",
"1",
",",
"1",
"]",
"-",
"q",
"[",
"3",
",",
"3",
"]",
",",
"q",
"[",
"2",
",",
"3",
"]",
"-",
"q",
"[",
"1",
",",
"0",
"]",
",",
"0.0",
"]",
",",
"[",
"q",
"[",
"1",
",",
"3",
"]",
"-",
"q",
"[",
"2",
",",
"0",
"]",
",",
"q",
"[",
"2",
",",
"3",
"]",
"+",
"q",
"[",
"1",
",",
"0",
"]",
",",
"1.0",
"-",
"q",
"[",
"1",
",",
"1",
"]",
"-",
"q",
"[",
"2",
",",
"2",
"]",
",",
"0.0",
"]",
",",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"1.0",
"]",
"]",
")"
] | Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> numpy.allclose(M, numpy.diag([1, -1, -1, 1]))
True | [
"Return",
"homogeneous",
"rotation",
"matrix",
"from",
"quaternion",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1295-L1319 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | quaternion_multiply | def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> numpy.allclose(q, [28, -44, -14, 48])
True
"""
w0, x0, y0, z0 = quaternion0
w1, x1, y1, z1 = quaternion1
return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0,
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64) | python | def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> numpy.allclose(q, [28, -44, -14, 48])
True
"""
w0, x0, y0, z0 = quaternion0
w1, x1, y1, z1 = quaternion1
return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0,
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64) | [
"def",
"quaternion_multiply",
"(",
"quaternion1",
",",
"quaternion0",
")",
":",
"w0",
",",
"x0",
",",
"y0",
",",
"z0",
"=",
"quaternion0",
"w1",
",",
"x1",
",",
"y1",
",",
"z1",
"=",
"quaternion1",
"return",
"numpy",
".",
"array",
"(",
"[",
"-",
"x1",
"*",
"x0",
"-",
"y1",
"*",
"y0",
"-",
"z1",
"*",
"z0",
"+",
"w1",
"*",
"w0",
",",
"x1",
"*",
"w0",
"+",
"y1",
"*",
"z0",
"-",
"z1",
"*",
"y0",
"+",
"w1",
"*",
"x0",
",",
"-",
"x1",
"*",
"z0",
"+",
"y1",
"*",
"w0",
"+",
"z1",
"*",
"x0",
"+",
"w1",
"*",
"y0",
",",
"x1",
"*",
"y0",
"-",
"y1",
"*",
"x0",
"+",
"z1",
"*",
"w0",
"+",
"w1",
"*",
"z0",
"]",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")"
] | Return multiplication of two quaternions.
>>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> numpy.allclose(q, [28, -44, -14, 48])
True | [
"Return",
"multiplication",
"of",
"two",
"quaternions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1399-L1412 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | angle_between_vectors | def angle_between_vectors(v0, v1, directed=True, axis=0):
"""Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> numpy.allclose(a, math.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> numpy.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)
dot = numpy.sum(v0 * v1, axis=axis)
dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis)
return numpy.arccos(dot if directed else numpy.fabs(dot)) | python | def angle_between_vectors(v0, v1, directed=True, axis=0):
"""Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> numpy.allclose(a, math.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> numpy.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)
dot = numpy.sum(v0 * v1, axis=axis)
dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis)
return numpy.arccos(dot if directed else numpy.fabs(dot)) | [
"def",
"angle_between_vectors",
"(",
"v0",
",",
"v1",
",",
"directed",
"=",
"True",
",",
"axis",
"=",
"0",
")",
":",
"v0",
"=",
"numpy",
".",
"array",
"(",
"v0",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"v1",
"=",
"numpy",
".",
"array",
"(",
"v1",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"False",
")",
"dot",
"=",
"numpy",
".",
"sum",
"(",
"v0",
"*",
"v1",
",",
"axis",
"=",
"axis",
")",
"dot",
"/=",
"vector_norm",
"(",
"v0",
",",
"axis",
"=",
"axis",
")",
"*",
"vector_norm",
"(",
"v1",
",",
"axis",
"=",
"axis",
")",
"return",
"numpy",
".",
"arccos",
"(",
"dot",
"if",
"directed",
"else",
"numpy",
".",
"fabs",
"(",
"dot",
")",
")"
] | Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> numpy.allclose(a, math.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> numpy.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True | [
"Return",
"angle",
"between",
"vectors",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1846-L1874 | train |
chemlab/chemlab | chemlab/graphics/transformations.py | Arcball.drag | def drag(self, point):
"""Update current cursor window coordinates."""
vnow = arcball_map_to_sphere(point, self._center, self._radius)
if self._axis is not None:
vnow = arcball_constrain_to_axis(vnow, self._axis)
self._qpre = self._qnow
t = numpy.cross(self._vdown, vnow)
if numpy.dot(t, t) < _EPS:
self._qnow = self._qdown
else:
q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]]
self._qnow = quaternion_multiply(q, self._qdown) | python | def drag(self, point):
"""Update current cursor window coordinates."""
vnow = arcball_map_to_sphere(point, self._center, self._radius)
if self._axis is not None:
vnow = arcball_constrain_to_axis(vnow, self._axis)
self._qpre = self._qnow
t = numpy.cross(self._vdown, vnow)
if numpy.dot(t, t) < _EPS:
self._qnow = self._qdown
else:
q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]]
self._qnow = quaternion_multiply(q, self._qdown) | [
"def",
"drag",
"(",
"self",
",",
"point",
")",
":",
"vnow",
"=",
"arcball_map_to_sphere",
"(",
"point",
",",
"self",
".",
"_center",
",",
"self",
".",
"_radius",
")",
"if",
"self",
".",
"_axis",
"is",
"not",
"None",
":",
"vnow",
"=",
"arcball_constrain_to_axis",
"(",
"vnow",
",",
"self",
".",
"_axis",
")",
"self",
".",
"_qpre",
"=",
"self",
".",
"_qnow",
"t",
"=",
"numpy",
".",
"cross",
"(",
"self",
".",
"_vdown",
",",
"vnow",
")",
"if",
"numpy",
".",
"dot",
"(",
"t",
",",
"t",
")",
"<",
"_EPS",
":",
"self",
".",
"_qnow",
"=",
"self",
".",
"_qdown",
"else",
":",
"q",
"=",
"[",
"numpy",
".",
"dot",
"(",
"self",
".",
"_vdown",
",",
"vnow",
")",
",",
"t",
"[",
"0",
"]",
",",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"2",
"]",
"]",
"self",
".",
"_qnow",
"=",
"quaternion_multiply",
"(",
"q",
",",
"self",
".",
"_qdown",
")"
] | Update current cursor window coordinates. | [
"Update",
"current",
"cursor",
"window",
"coordinates",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1633-L1644 | train |
chemlab/chemlab | chemlab/notebook/__init__.py | load_trajectory | def load_trajectory(name, format=None, skip=1):
'''Read a trajectory from a file.
.. seealso:: `chemlab.io.datafile`
'''
df = datafile(name, format=format)
ret = {}
t, coords = df.read('trajectory', skip=skip)
boxes = df.read('boxes')
ret['t'] = t
ret['coords'] = coords
ret['boxes'] = boxes
return ret | python | def load_trajectory(name, format=None, skip=1):
'''Read a trajectory from a file.
.. seealso:: `chemlab.io.datafile`
'''
df = datafile(name, format=format)
ret = {}
t, coords = df.read('trajectory', skip=skip)
boxes = df.read('boxes')
ret['t'] = t
ret['coords'] = coords
ret['boxes'] = boxes
return ret | [
"def",
"load_trajectory",
"(",
"name",
",",
"format",
"=",
"None",
",",
"skip",
"=",
"1",
")",
":",
"df",
"=",
"datafile",
"(",
"name",
",",
"format",
"=",
"format",
")",
"ret",
"=",
"{",
"}",
"t",
",",
"coords",
"=",
"df",
".",
"read",
"(",
"'trajectory'",
",",
"skip",
"=",
"skip",
")",
"boxes",
"=",
"df",
".",
"read",
"(",
"'boxes'",
")",
"ret",
"[",
"'t'",
"]",
"=",
"t",
"ret",
"[",
"'coords'",
"]",
"=",
"coords",
"ret",
"[",
"'boxes'",
"]",
"=",
"boxes",
"return",
"ret"
] | Read a trajectory from a file.
.. seealso:: `chemlab.io.datafile` | [
"Read",
"a",
"trajectory",
"from",
"a",
"file",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/notebook/__init__.py#L78-L93 | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | select_atoms | def select_atoms(indices):
'''Select atoms by their indices.
You can select the first 3 atoms as follows::
select_atoms([0, 1, 2])
Return the current selection dictionary.
'''
rep = current_representation()
rep.select({'atoms': Selection(indices, current_system().n_atoms)})
return rep.selection_state | python | def select_atoms(indices):
'''Select atoms by their indices.
You can select the first 3 atoms as follows::
select_atoms([0, 1, 2])
Return the current selection dictionary.
'''
rep = current_representation()
rep.select({'atoms': Selection(indices, current_system().n_atoms)})
return rep.selection_state | [
"def",
"select_atoms",
"(",
"indices",
")",
":",
"rep",
"=",
"current_representation",
"(",
")",
"rep",
".",
"select",
"(",
"{",
"'atoms'",
":",
"Selection",
"(",
"indices",
",",
"current_system",
"(",
")",
".",
"n_atoms",
")",
"}",
")",
"return",
"rep",
".",
"selection_state"
] | Select atoms by their indices.
You can select the first 3 atoms as follows::
select_atoms([0, 1, 2])
Return the current selection dictionary. | [
"Select",
"atoms",
"by",
"their",
"indices",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L20-L32 | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | select_connected_bonds | def select_connected_bonds():
'''Select the bonds connected to the currently selected atoms.'''
s = current_system()
start, end = s.bonds.transpose()
selected = np.zeros(s.n_bonds, 'bool')
for i in selected_atoms():
selected |= (i == start) | (i == end)
csel = current_selection()
bsel = csel['bonds'].add(
Selection(selected.nonzero()[0], s.n_bonds))
ret = csel.copy()
ret['bonds'] = bsel
return select_selection(ret) | python | def select_connected_bonds():
'''Select the bonds connected to the currently selected atoms.'''
s = current_system()
start, end = s.bonds.transpose()
selected = np.zeros(s.n_bonds, 'bool')
for i in selected_atoms():
selected |= (i == start) | (i == end)
csel = current_selection()
bsel = csel['bonds'].add(
Selection(selected.nonzero()[0], s.n_bonds))
ret = csel.copy()
ret['bonds'] = bsel
return select_selection(ret) | [
"def",
"select_connected_bonds",
"(",
")",
":",
"s",
"=",
"current_system",
"(",
")",
"start",
",",
"end",
"=",
"s",
".",
"bonds",
".",
"transpose",
"(",
")",
"selected",
"=",
"np",
".",
"zeros",
"(",
"s",
".",
"n_bonds",
",",
"'bool'",
")",
"for",
"i",
"in",
"selected_atoms",
"(",
")",
":",
"selected",
"|=",
"(",
"i",
"==",
"start",
")",
"|",
"(",
"i",
"==",
"end",
")",
"csel",
"=",
"current_selection",
"(",
")",
"bsel",
"=",
"csel",
"[",
"'bonds'",
"]",
".",
"add",
"(",
"Selection",
"(",
"selected",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
",",
"s",
".",
"n_bonds",
")",
")",
"ret",
"=",
"csel",
".",
"copy",
"(",
")",
"ret",
"[",
"'bonds'",
"]",
"=",
"bsel",
"return",
"select_selection",
"(",
"ret",
")"
] | Select the bonds connected to the currently selected atoms. | [
"Select",
"the",
"bonds",
"connected",
"to",
"the",
"currently",
"selected",
"atoms",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L54-L69 | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | select_molecules | def select_molecules(name):
'''Select all the molecules corresponding to the formulas.'''
mol_formula = current_system().get_derived_molecule_array('formula')
mask = mol_formula == name
ind = current_system().mol_to_atom_indices(mask.nonzero()[0])
selection = {'atoms': Selection(ind, current_system().n_atoms)}
# Need to find the bonds between the atoms
b = current_system().bonds
if len(b) == 0:
selection['bonds'] = Selection([], 0)
else:
molbonds = np.zeros(len(b), 'bool')
for i in ind:
matching = (i == b).sum(axis=1).astype('bool')
molbonds[matching] = True
selection['bonds'] = Selection(molbonds.nonzero()[0], len(b))
return select_selection(selection) | python | def select_molecules(name):
'''Select all the molecules corresponding to the formulas.'''
mol_formula = current_system().get_derived_molecule_array('formula')
mask = mol_formula == name
ind = current_system().mol_to_atom_indices(mask.nonzero()[0])
selection = {'atoms': Selection(ind, current_system().n_atoms)}
# Need to find the bonds between the atoms
b = current_system().bonds
if len(b) == 0:
selection['bonds'] = Selection([], 0)
else:
molbonds = np.zeros(len(b), 'bool')
for i in ind:
matching = (i == b).sum(axis=1).astype('bool')
molbonds[matching] = True
selection['bonds'] = Selection(molbonds.nonzero()[0], len(b))
return select_selection(selection) | [
"def",
"select_molecules",
"(",
"name",
")",
":",
"mol_formula",
"=",
"current_system",
"(",
")",
".",
"get_derived_molecule_array",
"(",
"'formula'",
")",
"mask",
"=",
"mol_formula",
"==",
"name",
"ind",
"=",
"current_system",
"(",
")",
".",
"mol_to_atom_indices",
"(",
"mask",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
")",
"selection",
"=",
"{",
"'atoms'",
":",
"Selection",
"(",
"ind",
",",
"current_system",
"(",
")",
".",
"n_atoms",
")",
"}",
"# Need to find the bonds between the atoms",
"b",
"=",
"current_system",
"(",
")",
".",
"bonds",
"if",
"len",
"(",
"b",
")",
"==",
"0",
":",
"selection",
"[",
"'bonds'",
"]",
"=",
"Selection",
"(",
"[",
"]",
",",
"0",
")",
"else",
":",
"molbonds",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"b",
")",
",",
"'bool'",
")",
"for",
"i",
"in",
"ind",
":",
"matching",
"=",
"(",
"i",
"==",
"b",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
".",
"astype",
"(",
"'bool'",
")",
"molbonds",
"[",
"matching",
"]",
"=",
"True",
"selection",
"[",
"'bonds'",
"]",
"=",
"Selection",
"(",
"molbonds",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
",",
"len",
"(",
"b",
")",
")",
"return",
"select_selection",
"(",
"selection",
")"
] | Select all the molecules corresponding to the formulas. | [
"Select",
"all",
"the",
"molecules",
"corresponding",
"to",
"the",
"formulas",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L85-L105 | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | hide_selected | def hide_selected():
'''Hide the selected objects.'''
ss = current_representation().selection_state
hs = current_representation().hidden_state
res = {}
for k in ss:
res[k] = hs[k].add(ss[k])
current_representation().hide(res) | python | def hide_selected():
'''Hide the selected objects.'''
ss = current_representation().selection_state
hs = current_representation().hidden_state
res = {}
for k in ss:
res[k] = hs[k].add(ss[k])
current_representation().hide(res) | [
"def",
"hide_selected",
"(",
")",
":",
"ss",
"=",
"current_representation",
"(",
")",
".",
"selection_state",
"hs",
"=",
"current_representation",
"(",
")",
".",
"hidden_state",
"res",
"=",
"{",
"}",
"for",
"k",
"in",
"ss",
":",
"res",
"[",
"k",
"]",
"=",
"hs",
"[",
"k",
"]",
".",
"add",
"(",
"ss",
"[",
"k",
"]",
")",
"current_representation",
"(",
")",
".",
"hide",
"(",
"res",
")"
] | Hide the selected objects. | [
"Hide",
"the",
"selected",
"objects",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L113-L122 | train |
chemlab/chemlab | chemlab/mviewer/api/selections.py | unhide_selected | def unhide_selected():
'''Unhide the selected objects'''
hidden_state = current_representation().hidden_state
selection_state = current_representation().selection_state
res = {}
# Take the hidden state and flip the selected atoms bits.
for k in selection_state:
visible = hidden_state[k].invert()
visible_and_selected = visible.add(selection_state[k]) # Add some atoms to be visible
res[k] = visible_and_selected.invert()
current_representation().hide(res) | python | def unhide_selected():
'''Unhide the selected objects'''
hidden_state = current_representation().hidden_state
selection_state = current_representation().selection_state
res = {}
# Take the hidden state and flip the selected atoms bits.
for k in selection_state:
visible = hidden_state[k].invert()
visible_and_selected = visible.add(selection_state[k]) # Add some atoms to be visible
res[k] = visible_and_selected.invert()
current_representation().hide(res) | [
"def",
"unhide_selected",
"(",
")",
":",
"hidden_state",
"=",
"current_representation",
"(",
")",
".",
"hidden_state",
"selection_state",
"=",
"current_representation",
"(",
")",
".",
"selection_state",
"res",
"=",
"{",
"}",
"# Take the hidden state and flip the selected atoms bits.",
"for",
"k",
"in",
"selection_state",
":",
"visible",
"=",
"hidden_state",
"[",
"k",
"]",
".",
"invert",
"(",
")",
"visible_and_selected",
"=",
"visible",
".",
"add",
"(",
"selection_state",
"[",
"k",
"]",
")",
"# Add some atoms to be visible",
"res",
"[",
"k",
"]",
"=",
"visible_and_selected",
".",
"invert",
"(",
")",
"current_representation",
"(",
")",
".",
"hide",
"(",
"res",
")"
] | Unhide the selected objects | [
"Unhide",
"the",
"selected",
"objects"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/mviewer/api/selections.py#L137-L150 | train |
chemlab/chemlab | chemlab/graphics/camera.py | Camera.mouse_rotate | def mouse_rotate(self, dx, dy):
'''Convenience function to implement the mouse rotation by
giving two displacements in the x and y directions.
'''
fact = 1.5
self.orbit_y(-dx*fact)
self.orbit_x(dy*fact) | python | def mouse_rotate(self, dx, dy):
'''Convenience function to implement the mouse rotation by
giving two displacements in the x and y directions.
'''
fact = 1.5
self.orbit_y(-dx*fact)
self.orbit_x(dy*fact) | [
"def",
"mouse_rotate",
"(",
"self",
",",
"dx",
",",
"dy",
")",
":",
"fact",
"=",
"1.5",
"self",
".",
"orbit_y",
"(",
"-",
"dx",
"*",
"fact",
")",
"self",
".",
"orbit_x",
"(",
"dy",
"*",
"fact",
")"
] | Convenience function to implement the mouse rotation by
giving two displacements in the x and y directions. | [
"Convenience",
"function",
"to",
"implement",
"the",
"mouse",
"rotation",
"by",
"giving",
"two",
"displacements",
"in",
"the",
"x",
"and",
"y",
"directions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L148-L155 | train |
chemlab/chemlab | chemlab/graphics/camera.py | Camera.mouse_zoom | def mouse_zoom(self, inc):
'''Convenience function to implement a zoom function.
This is achieved by moving ``Camera.position`` in the
direction of the ``Camera.c`` vector.
'''
# Square Distance from pivot
dsq = np.linalg.norm(self.position - self.pivot)
minsq = 1.0**2 # How near can we be to the pivot
maxsq = 7.0**2 # How far can we go
scalefac = 0.25
if dsq > maxsq and inc < 0:
# We're going too far
pass
elif dsq < minsq and inc > 0:
# We're going too close
pass
else:
# We're golden
self.position += self.c*inc*scalefac | python | def mouse_zoom(self, inc):
'''Convenience function to implement a zoom function.
This is achieved by moving ``Camera.position`` in the
direction of the ``Camera.c`` vector.
'''
# Square Distance from pivot
dsq = np.linalg.norm(self.position - self.pivot)
minsq = 1.0**2 # How near can we be to the pivot
maxsq = 7.0**2 # How far can we go
scalefac = 0.25
if dsq > maxsq and inc < 0:
# We're going too far
pass
elif dsq < minsq and inc > 0:
# We're going too close
pass
else:
# We're golden
self.position += self.c*inc*scalefac | [
"def",
"mouse_zoom",
"(",
"self",
",",
"inc",
")",
":",
"# Square Distance from pivot",
"dsq",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"position",
"-",
"self",
".",
"pivot",
")",
"minsq",
"=",
"1.0",
"**",
"2",
"# How near can we be to the pivot",
"maxsq",
"=",
"7.0",
"**",
"2",
"# How far can we go ",
"scalefac",
"=",
"0.25",
"if",
"dsq",
">",
"maxsq",
"and",
"inc",
"<",
"0",
":",
"# We're going too far",
"pass",
"elif",
"dsq",
"<",
"minsq",
"and",
"inc",
">",
"0",
":",
"# We're going too close",
"pass",
"else",
":",
"# We're golden",
"self",
".",
"position",
"+=",
"self",
".",
"c",
"*",
"inc",
"*",
"scalefac"
] | Convenience function to implement a zoom function.
This is achieved by moving ``Camera.position`` in the
direction of the ``Camera.c`` vector. | [
"Convenience",
"function",
"to",
"implement",
"a",
"zoom",
"function",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L157-L179 | train |
chemlab/chemlab | chemlab/graphics/camera.py | Camera.unproject | def unproject(self, x, y, z=-1.0):
"""Receive x and y as screen coordinates and returns a point
in world coordinates.
This function comes in handy each time we have to convert a 2d
mouse click to a 3d point in our space.
**Parameters**
x: float in the interval [-1.0, 1.0]
Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost.
y: float in the interval [1.0, -1.0]
Vertical coordinate, -1.0 is down, 1.0 is up.
z: float in the interval [1.0, -1.0]
Depth, -1.0 is the near plane, that is exactly behind our
screen, 1.0 is the far clipping plane.
:rtype: np.ndarray(3,dtype=float)
:return: The point in 3d coordinates (world coordinates).
"""
source = np.array([x,y,z,1.0])
# Invert the combined matrix
matrix = self.projection.dot(self.matrix)
IM = LA.inv(matrix)
res = np.dot(IM, source)
return res[0:3]/res[3] | python | def unproject(self, x, y, z=-1.0):
"""Receive x and y as screen coordinates and returns a point
in world coordinates.
This function comes in handy each time we have to convert a 2d
mouse click to a 3d point in our space.
**Parameters**
x: float in the interval [-1.0, 1.0]
Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost.
y: float in the interval [1.0, -1.0]
Vertical coordinate, -1.0 is down, 1.0 is up.
z: float in the interval [1.0, -1.0]
Depth, -1.0 is the near plane, that is exactly behind our
screen, 1.0 is the far clipping plane.
:rtype: np.ndarray(3,dtype=float)
:return: The point in 3d coordinates (world coordinates).
"""
source = np.array([x,y,z,1.0])
# Invert the combined matrix
matrix = self.projection.dot(self.matrix)
IM = LA.inv(matrix)
res = np.dot(IM, source)
return res[0:3]/res[3] | [
"def",
"unproject",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
"=",
"-",
"1.0",
")",
":",
"source",
"=",
"np",
".",
"array",
"(",
"[",
"x",
",",
"y",
",",
"z",
",",
"1.0",
"]",
")",
"# Invert the combined matrix",
"matrix",
"=",
"self",
".",
"projection",
".",
"dot",
"(",
"self",
".",
"matrix",
")",
"IM",
"=",
"LA",
".",
"inv",
"(",
"matrix",
")",
"res",
"=",
"np",
".",
"dot",
"(",
"IM",
",",
"source",
")",
"return",
"res",
"[",
"0",
":",
"3",
"]",
"/",
"res",
"[",
"3",
"]"
] | Receive x and y as screen coordinates and returns a point
in world coordinates.
This function comes in handy each time we have to convert a 2d
mouse click to a 3d point in our space.
**Parameters**
x: float in the interval [-1.0, 1.0]
Horizontal coordinate, -1.0 is leftmost, 1.0 is rightmost.
y: float in the interval [1.0, -1.0]
Vertical coordinate, -1.0 is down, 1.0 is up.
z: float in the interval [1.0, -1.0]
Depth, -1.0 is the near plane, that is exactly behind our
screen, 1.0 is the far clipping plane.
:rtype: np.ndarray(3,dtype=float)
:return: The point in 3d coordinates (world coordinates). | [
"Receive",
"x",
"and",
"y",
"as",
"screen",
"coordinates",
"and",
"returns",
"a",
"point",
"in",
"world",
"coordinates",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L230-L261 | train |
chemlab/chemlab | chemlab/graphics/camera.py | Camera.state | def state(self):
'''Return the current camera state as a dictionary, it can be
restored with `Camera.restore`.
'''
return dict(a=self.a.tolist(), b=self.b.tolist(), c=self.c.tolist(),
pivot=self.pivot.tolist(), position=self.position.tolist()) | python | def state(self):
'''Return the current camera state as a dictionary, it can be
restored with `Camera.restore`.
'''
return dict(a=self.a.tolist(), b=self.b.tolist(), c=self.c.tolist(),
pivot=self.pivot.tolist(), position=self.position.tolist()) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"a",
"=",
"self",
".",
"a",
".",
"tolist",
"(",
")",
",",
"b",
"=",
"self",
".",
"b",
".",
"tolist",
"(",
")",
",",
"c",
"=",
"self",
".",
"c",
".",
"tolist",
"(",
")",
",",
"pivot",
"=",
"self",
".",
"pivot",
".",
"tolist",
"(",
")",
",",
"position",
"=",
"self",
".",
"position",
".",
"tolist",
"(",
")",
")"
] | Return the current camera state as a dictionary, it can be
restored with `Camera.restore`. | [
"Return",
"the",
"current",
"camera",
"state",
"as",
"a",
"dictionary",
"it",
"can",
"be",
"restored",
"with",
"Camera",
".",
"restore",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/camera.py#L316-L322 | train |
chemlab/chemlab | chemlab/graphics/pickers.py | ray_spheres_intersection | def ray_spheres_intersection(origin, direction, centers, radii):
"""Calculate the intersection points between a ray and multiple
spheres.
**Returns**
intersections
distances
Ordered by closest to farther
"""
b_v = 2.0 * ((origin - centers) * direction).sum(axis=1)
c_v = ((origin - centers)**2).sum(axis=1) - radii ** 2
det_v = b_v * b_v - 4.0 * c_v
inters_mask = det_v >= 0
intersections = (inters_mask).nonzero()[0]
distances = (-b_v[inters_mask] - np.sqrt(det_v[inters_mask])) / 2.0
# We need only the thing in front of us, that corresponts to
# positive distances.
dist_mask = distances > 0.0
# We correct this aspect to get an absolute distance
distances = distances[dist_mask]
intersections = intersections[dist_mask].tolist()
if intersections:
distances, intersections = zip(*sorted(zip(distances, intersections)))
return list(intersections), list(distances)
else:
return [], [] | python | def ray_spheres_intersection(origin, direction, centers, radii):
"""Calculate the intersection points between a ray and multiple
spheres.
**Returns**
intersections
distances
Ordered by closest to farther
"""
b_v = 2.0 * ((origin - centers) * direction).sum(axis=1)
c_v = ((origin - centers)**2).sum(axis=1) - radii ** 2
det_v = b_v * b_v - 4.0 * c_v
inters_mask = det_v >= 0
intersections = (inters_mask).nonzero()[0]
distances = (-b_v[inters_mask] - np.sqrt(det_v[inters_mask])) / 2.0
# We need only the thing in front of us, that corresponts to
# positive distances.
dist_mask = distances > 0.0
# We correct this aspect to get an absolute distance
distances = distances[dist_mask]
intersections = intersections[dist_mask].tolist()
if intersections:
distances, intersections = zip(*sorted(zip(distances, intersections)))
return list(intersections), list(distances)
else:
return [], [] | [
"def",
"ray_spheres_intersection",
"(",
"origin",
",",
"direction",
",",
"centers",
",",
"radii",
")",
":",
"b_v",
"=",
"2.0",
"*",
"(",
"(",
"origin",
"-",
"centers",
")",
"*",
"direction",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"c_v",
"=",
"(",
"(",
"origin",
"-",
"centers",
")",
"**",
"2",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"-",
"radii",
"**",
"2",
"det_v",
"=",
"b_v",
"*",
"b_v",
"-",
"4.0",
"*",
"c_v",
"inters_mask",
"=",
"det_v",
">=",
"0",
"intersections",
"=",
"(",
"inters_mask",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"distances",
"=",
"(",
"-",
"b_v",
"[",
"inters_mask",
"]",
"-",
"np",
".",
"sqrt",
"(",
"det_v",
"[",
"inters_mask",
"]",
")",
")",
"/",
"2.0",
"# We need only the thing in front of us, that corresponts to",
"# positive distances.",
"dist_mask",
"=",
"distances",
">",
"0.0",
"# We correct this aspect to get an absolute distance",
"distances",
"=",
"distances",
"[",
"dist_mask",
"]",
"intersections",
"=",
"intersections",
"[",
"dist_mask",
"]",
".",
"tolist",
"(",
")",
"if",
"intersections",
":",
"distances",
",",
"intersections",
"=",
"zip",
"(",
"*",
"sorted",
"(",
"zip",
"(",
"distances",
",",
"intersections",
")",
")",
")",
"return",
"list",
"(",
"intersections",
")",
",",
"list",
"(",
"distances",
")",
"else",
":",
"return",
"[",
"]",
",",
"[",
"]"
] | Calculate the intersection points between a ray and multiple
spheres.
**Returns**
intersections
distances
Ordered by closest to farther | [
"Calculate",
"the",
"intersection",
"points",
"between",
"a",
"ray",
"and",
"multiple",
"spheres",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/pickers.py#L8-L40 | train |
chemlab/chemlab | chemlab/graphics/colors.py | any_to_rgb | def any_to_rgb(color):
'''If color is an rgb tuple return it, if it is a string, parse it
and return the respective rgb tuple.
'''
if isinstance(color, tuple):
if len(color) == 3:
color = color + (255,)
return color
if isinstance(color, str):
return parse_color(color)
raise ValueError("Color not recognized: {}".format(color)) | python | def any_to_rgb(color):
'''If color is an rgb tuple return it, if it is a string, parse it
and return the respective rgb tuple.
'''
if isinstance(color, tuple):
if len(color) == 3:
color = color + (255,)
return color
if isinstance(color, str):
return parse_color(color)
raise ValueError("Color not recognized: {}".format(color)) | [
"def",
"any_to_rgb",
"(",
"color",
")",
":",
"if",
"isinstance",
"(",
"color",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"color",
")",
"==",
"3",
":",
"color",
"=",
"color",
"+",
"(",
"255",
",",
")",
"return",
"color",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"return",
"parse_color",
"(",
"color",
")",
"raise",
"ValueError",
"(",
"\"Color not recognized: {}\"",
".",
"format",
"(",
"color",
")",
")"
] | If color is an rgb tuple return it, if it is a string, parse it
and return the respective rgb tuple. | [
"If",
"color",
"is",
"an",
"rgb",
"tuple",
"return",
"it",
"if",
"it",
"is",
"a",
"string",
"parse",
"it",
"and",
"return",
"the",
"respective",
"rgb",
"tuple",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L167-L180 | train |
chemlab/chemlab | chemlab/graphics/colors.py | parse_color | def parse_color(color):
'''Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names.
'''
# Let's parse the color string
if isinstance(color, str):
# Try dvi names
try:
col = get(color)
except ValueError:
# String is not present
pass
# Try html names
try:
col = html_to_rgb(color)
except ValueError:
raise ValueError("Can't parse color string: {}'".format(color))
return col | python | def parse_color(color):
'''Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names.
'''
# Let's parse the color string
if isinstance(color, str):
# Try dvi names
try:
col = get(color)
except ValueError:
# String is not present
pass
# Try html names
try:
col = html_to_rgb(color)
except ValueError:
raise ValueError("Can't parse color string: {}'".format(color))
return col | [
"def",
"parse_color",
"(",
"color",
")",
":",
"# Let's parse the color string",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"# Try dvi names",
"try",
":",
"col",
"=",
"get",
"(",
"color",
")",
"except",
"ValueError",
":",
"# String is not present",
"pass",
"# Try html names",
"try",
":",
"col",
"=",
"html_to_rgb",
"(",
"color",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Can't parse color string: {}'\"",
".",
"format",
"(",
"color",
")",
")",
"return",
"col"
] | Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names. | [
"Return",
"the",
"RGB",
"0",
"-",
"255",
"representation",
"of",
"the",
"current",
"string",
"passed",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L197-L220 | train |
chemlab/chemlab | chemlab/graphics/colors.py | hsl_to_rgb | def hsl_to_rgb(arr):
"""
Converts HSL color array to RGB array
H = [0..360]
S = [0..1]
l = [0..1]
http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
Returns R,G,B in [0..255]
"""
H, S, L = arr.T
H = (H.copy()/255.0) * 360
S = S.copy()/255.0
L = L.copy()/255.0
C = (1 - np.absolute(2 * L - 1)) * S
Hp = H / 60.0
X = C * (1 - np.absolute(np.mod(Hp, 2) - 1))
# initilize with zero
R = np.zeros(H.shape, float)
G = np.zeros(H.shape, float)
B = np.zeros(H.shape, float)
# handle each case:
mask = (Hp >= 0) == ( Hp < 1)
R[mask] = C[mask]
G[mask] = X[mask]
mask = (Hp >= 1) == ( Hp < 2)
R[mask] = X[mask]
G[mask] = C[mask]
mask = (Hp >= 2) == ( Hp < 3)
G[mask] = C[mask]
B[mask] = X[mask]
mask = (Hp >= 3) == ( Hp < 4)
G[mask] = X[mask]
B[mask] = C[mask]
mask = (Hp >= 4) == ( Hp < 5)
R[mask] = X[mask]
B[mask] = C[mask]
mask = (Hp >= 5) == ( Hp < 6)
R[mask] = C[mask]
B[mask] = X[mask]
m = L - 0.5*C
R += m
G += m
B += m
R *= 255.0
G *= 255.0
B *= 255.0
return np.array((R.astype(int),G.astype(int),B.astype(int))).T | python | def hsl_to_rgb(arr):
"""
Converts HSL color array to RGB array
H = [0..360]
S = [0..1]
l = [0..1]
http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
Returns R,G,B in [0..255]
"""
H, S, L = arr.T
H = (H.copy()/255.0) * 360
S = S.copy()/255.0
L = L.copy()/255.0
C = (1 - np.absolute(2 * L - 1)) * S
Hp = H / 60.0
X = C * (1 - np.absolute(np.mod(Hp, 2) - 1))
# initilize with zero
R = np.zeros(H.shape, float)
G = np.zeros(H.shape, float)
B = np.zeros(H.shape, float)
# handle each case:
mask = (Hp >= 0) == ( Hp < 1)
R[mask] = C[mask]
G[mask] = X[mask]
mask = (Hp >= 1) == ( Hp < 2)
R[mask] = X[mask]
G[mask] = C[mask]
mask = (Hp >= 2) == ( Hp < 3)
G[mask] = C[mask]
B[mask] = X[mask]
mask = (Hp >= 3) == ( Hp < 4)
G[mask] = X[mask]
B[mask] = C[mask]
mask = (Hp >= 4) == ( Hp < 5)
R[mask] = X[mask]
B[mask] = C[mask]
mask = (Hp >= 5) == ( Hp < 6)
R[mask] = C[mask]
B[mask] = X[mask]
m = L - 0.5*C
R += m
G += m
B += m
R *= 255.0
G *= 255.0
B *= 255.0
return np.array((R.astype(int),G.astype(int),B.astype(int))).T | [
"def",
"hsl_to_rgb",
"(",
"arr",
")",
":",
"H",
",",
"S",
",",
"L",
"=",
"arr",
".",
"T",
"H",
"=",
"(",
"H",
".",
"copy",
"(",
")",
"/",
"255.0",
")",
"*",
"360",
"S",
"=",
"S",
".",
"copy",
"(",
")",
"/",
"255.0",
"L",
"=",
"L",
".",
"copy",
"(",
")",
"/",
"255.0",
"C",
"=",
"(",
"1",
"-",
"np",
".",
"absolute",
"(",
"2",
"*",
"L",
"-",
"1",
")",
")",
"*",
"S",
"Hp",
"=",
"H",
"/",
"60.0",
"X",
"=",
"C",
"*",
"(",
"1",
"-",
"np",
".",
"absolute",
"(",
"np",
".",
"mod",
"(",
"Hp",
",",
"2",
")",
"-",
"1",
")",
")",
"# initilize with zero",
"R",
"=",
"np",
".",
"zeros",
"(",
"H",
".",
"shape",
",",
"float",
")",
"G",
"=",
"np",
".",
"zeros",
"(",
"H",
".",
"shape",
",",
"float",
")",
"B",
"=",
"np",
".",
"zeros",
"(",
"H",
".",
"shape",
",",
"float",
")",
"# handle each case:",
"mask",
"=",
"(",
"Hp",
">=",
"0",
")",
"==",
"(",
"Hp",
"<",
"1",
")",
"R",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"G",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"mask",
"=",
"(",
"Hp",
">=",
"1",
")",
"==",
"(",
"Hp",
"<",
"2",
")",
"R",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"G",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"mask",
"=",
"(",
"Hp",
">=",
"2",
")",
"==",
"(",
"Hp",
"<",
"3",
")",
"G",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"B",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"mask",
"=",
"(",
"Hp",
">=",
"3",
")",
"==",
"(",
"Hp",
"<",
"4",
")",
"G",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"B",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"mask",
"=",
"(",
"Hp",
">=",
"4",
")",
"==",
"(",
"Hp",
"<",
"5",
")",
"R",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"B",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"mask",
"=",
"(",
"Hp",
">=",
"5",
")",
"==",
"(",
"Hp",
"<",
"6",
")",
"R",
"[",
"mask",
"]",
"=",
"C",
"[",
"mask",
"]",
"B",
"[",
"mask",
"]",
"=",
"X",
"[",
"mask",
"]",
"m",
"=",
"L",
"-",
"0.5",
"*",
"C",
"R",
"+=",
"m",
"G",
"+=",
"m",
"B",
"+=",
"m",
"R",
"*=",
"255.0",
"G",
"*=",
"255.0",
"B",
"*=",
"255.0",
"return",
"np",
".",
"array",
"(",
"(",
"R",
".",
"astype",
"(",
"int",
")",
",",
"G",
".",
"astype",
"(",
"int",
")",
",",
"B",
".",
"astype",
"(",
"int",
")",
")",
")",
".",
"T"
] | Converts HSL color array to RGB array
H = [0..360]
S = [0..1]
l = [0..1]
http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
Returns R,G,B in [0..255] | [
"Converts",
"HSL",
"color",
"array",
"to",
"RGB",
"array"
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/colors.py#L309-L372 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | format_symbol | def format_symbol(symbol):
"""Returns well formatted Hermann-Mauguin symbol as extected by
the database, by correcting the case and adding missing or
removing dublicated spaces."""
fixed = []
s = symbol.strip()
s = s[0].upper() + s[1:].lower()
for c in s:
if c.isalpha():
fixed.append(' ' + c + ' ')
elif c.isspace():
fixed.append(' ')
elif c.isdigit():
fixed.append(c)
elif c == '-':
fixed.append(' ' + c)
elif c == '/':
fixed.append(' ' + c)
s = ''.join(fixed).strip()
return ' '.join(s.split()) | python | def format_symbol(symbol):
"""Returns well formatted Hermann-Mauguin symbol as extected by
the database, by correcting the case and adding missing or
removing dublicated spaces."""
fixed = []
s = symbol.strip()
s = s[0].upper() + s[1:].lower()
for c in s:
if c.isalpha():
fixed.append(' ' + c + ' ')
elif c.isspace():
fixed.append(' ')
elif c.isdigit():
fixed.append(c)
elif c == '-':
fixed.append(' ' + c)
elif c == '/':
fixed.append(' ' + c)
s = ''.join(fixed).strip()
return ' '.join(s.split()) | [
"def",
"format_symbol",
"(",
"symbol",
")",
":",
"fixed",
"=",
"[",
"]",
"s",
"=",
"symbol",
".",
"strip",
"(",
")",
"s",
"=",
"s",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"s",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"s",
":",
"if",
"c",
".",
"isalpha",
"(",
")",
":",
"fixed",
".",
"append",
"(",
"' '",
"+",
"c",
"+",
"' '",
")",
"elif",
"c",
".",
"isspace",
"(",
")",
":",
"fixed",
".",
"append",
"(",
"' '",
")",
"elif",
"c",
".",
"isdigit",
"(",
")",
":",
"fixed",
".",
"append",
"(",
"c",
")",
"elif",
"c",
"==",
"'-'",
":",
"fixed",
".",
"append",
"(",
"' '",
"+",
"c",
")",
"elif",
"c",
"==",
"'/'",
":",
"fixed",
".",
"append",
"(",
"' '",
"+",
"c",
")",
"s",
"=",
"''",
".",
"join",
"(",
"fixed",
")",
".",
"strip",
"(",
")",
"return",
"' '",
".",
"join",
"(",
"s",
".",
"split",
"(",
")",
")"
] | Returns well formatted Hermann-Mauguin symbol as extected by
the database, by correcting the case and adding missing or
removing dublicated spaces. | [
"Returns",
"well",
"formatted",
"Hermann",
"-",
"Mauguin",
"symbol",
"as",
"extected",
"by",
"the",
"database",
"by",
"correcting",
"the",
"case",
"and",
"adding",
"missing",
"or",
"removing",
"dublicated",
"spaces",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L484-L503 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | _skip_to_blank | def _skip_to_blank(f, spacegroup, setting):
"""Read lines from f until a blank line is encountered."""
while True:
line = f.readline()
if not line:
raise SpacegroupNotFoundError(
'invalid spacegroup %s, setting %i not found in data base' %
( spacegroup, setting ) )
if not line.strip():
break | python | def _skip_to_blank(f, spacegroup, setting):
"""Read lines from f until a blank line is encountered."""
while True:
line = f.readline()
if not line:
raise SpacegroupNotFoundError(
'invalid spacegroup %s, setting %i not found in data base' %
( spacegroup, setting ) )
if not line.strip():
break | [
"def",
"_skip_to_blank",
"(",
"f",
",",
"spacegroup",
",",
"setting",
")",
":",
"while",
"True",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"raise",
"SpacegroupNotFoundError",
"(",
"'invalid spacegroup %s, setting %i not found in data base'",
"%",
"(",
"spacegroup",
",",
"setting",
")",
")",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"break"
] | Read lines from f until a blank line is encountered. | [
"Read",
"lines",
"from",
"f",
"until",
"a",
"blank",
"line",
"is",
"encountered",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L513-L522 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | _read_datafile_entry | def _read_datafile_entry(spg, no, symbol, setting, f):
"""Read space group data from f to spg."""
spg._no = no
spg._symbol = symbol.strip()
spg._setting = setting
spg._centrosymmetric = bool(int(f.readline().split()[1]))
# primitive vectors
f.readline()
spg._scaled_primitive_cell = np.array([
list(map(float, f.readline().split()))
for i in range(3)],
dtype='float')
# primitive reciprocal vectors
f.readline()
spg._reciprocal_cell = np.array([list(map(int, f.readline().split()))
for i in range(3)],
dtype=np.int)
# subtranslations
spg._nsubtrans = int(f.readline().split()[0])
spg._subtrans = np.array([list(map(float, f.readline().split()))
for i in range(spg._nsubtrans)],
dtype=np.float)
# symmetry operations
nsym = int(f.readline().split()[0])
symop = np.array([list(map(float, f.readline().split())) for i in range(nsym)],
dtype=np.float)
spg._nsymop = nsym
spg._rotations = np.array(symop[:,:9].reshape((nsym,3,3)), dtype=np.int)
spg._translations = symop[:,9:] | python | def _read_datafile_entry(spg, no, symbol, setting, f):
"""Read space group data from f to spg."""
spg._no = no
spg._symbol = symbol.strip()
spg._setting = setting
spg._centrosymmetric = bool(int(f.readline().split()[1]))
# primitive vectors
f.readline()
spg._scaled_primitive_cell = np.array([
list(map(float, f.readline().split()))
for i in range(3)],
dtype='float')
# primitive reciprocal vectors
f.readline()
spg._reciprocal_cell = np.array([list(map(int, f.readline().split()))
for i in range(3)],
dtype=np.int)
# subtranslations
spg._nsubtrans = int(f.readline().split()[0])
spg._subtrans = np.array([list(map(float, f.readline().split()))
for i in range(spg._nsubtrans)],
dtype=np.float)
# symmetry operations
nsym = int(f.readline().split()[0])
symop = np.array([list(map(float, f.readline().split())) for i in range(nsym)],
dtype=np.float)
spg._nsymop = nsym
spg._rotations = np.array(symop[:,:9].reshape((nsym,3,3)), dtype=np.int)
spg._translations = symop[:,9:] | [
"def",
"_read_datafile_entry",
"(",
"spg",
",",
"no",
",",
"symbol",
",",
"setting",
",",
"f",
")",
":",
"spg",
".",
"_no",
"=",
"no",
"spg",
".",
"_symbol",
"=",
"symbol",
".",
"strip",
"(",
")",
"spg",
".",
"_setting",
"=",
"setting",
"spg",
".",
"_centrosymmetric",
"=",
"bool",
"(",
"int",
"(",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
")",
"# primitive vectors",
"f",
".",
"readline",
"(",
")",
"spg",
".",
"_scaled_primitive_cell",
"=",
"np",
".",
"array",
"(",
"[",
"list",
"(",
"map",
"(",
"float",
",",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
",",
"dtype",
"=",
"'float'",
")",
"# primitive reciprocal vectors",
"f",
".",
"readline",
"(",
")",
"spg",
".",
"_reciprocal_cell",
"=",
"np",
".",
"array",
"(",
"[",
"list",
"(",
"map",
"(",
"int",
",",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"# subtranslations",
"spg",
".",
"_nsubtrans",
"=",
"int",
"(",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"spg",
".",
"_subtrans",
"=",
"np",
".",
"array",
"(",
"[",
"list",
"(",
"map",
"(",
"float",
",",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"spg",
".",
"_nsubtrans",
")",
"]",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"# symmetry operations",
"nsym",
"=",
"int",
"(",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"symop",
"=",
"np",
".",
"array",
"(",
"[",
"list",
"(",
"map",
"(",
"float",
",",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nsym",
")",
"]",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"spg",
".",
"_nsymop",
"=",
"nsym",
"spg",
".",
"_rotations",
"=",
"np",
".",
"array",
"(",
"symop",
"[",
":",
",",
":",
"9",
"]",
".",
"reshape",
"(",
"(",
"nsym",
",",
"3",
",",
"3",
")",
")",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"spg",
".",
"_translations",
"=",
"symop",
"[",
":",
",",
"9",
":",
"]"
] | Read space group data from f to spg. | [
"Read",
"space",
"group",
"data",
"from",
"f",
"to",
"spg",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L541-L570 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | parse_sitesym | def parse_sitesym(symlist, sep=','):
"""Parses a sequence of site symmetries in the form used by
International Tables and returns corresponding rotation and
translation arrays.
Example:
>>> symlist = [
... 'x,y,z',
... '-y+1/2,x+1/2,z',
... '-y,-x,-z',
... ]
>>> rot, trans = parse_sitesym(symlist)
>>> rot
array([[[ 1, 0, 0],
[ 0, 1, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[ 1, 0, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[-1, 0, 0],
[ 0, 0, -1]]])
>>> trans
array([[ 0. , 0. , 0. ],
[ 0.5, 0.5, 0. ],
[ 0. , 0. , 0. ]])
"""
nsym = len(symlist)
rot = np.zeros((nsym, 3, 3), dtype='int')
trans = np.zeros((nsym, 3))
for i, sym in enumerate(symlist):
for j, s in enumerate (sym.split(sep)):
s = s.lower().strip()
while s:
sign = 1
if s[0] in '+-':
if s[0] == '-':
sign = -1
s = s[1:]
if s[0] in 'xyz':
k = ord(s[0]) - ord('x')
rot[i, j, k] = sign
s = s[1:]
elif s[0].isdigit() or s[0] == '.':
n = 0
while n < len(s) and (s[n].isdigit() or s[n] in '/.'):
n += 1
t = s[:n]
s = s[n:]
if '/' in t:
q, r = t.split('/')
trans[i,j] = float(q)/float(r)
else:
trans[i,j] = float(t)
else:
raise SpacegroupValueError(
'Error parsing %r. Invalid site symmetry: %s' %
(s, sym))
return rot, trans | python | def parse_sitesym(symlist, sep=','):
"""Parses a sequence of site symmetries in the form used by
International Tables and returns corresponding rotation and
translation arrays.
Example:
>>> symlist = [
... 'x,y,z',
... '-y+1/2,x+1/2,z',
... '-y,-x,-z',
... ]
>>> rot, trans = parse_sitesym(symlist)
>>> rot
array([[[ 1, 0, 0],
[ 0, 1, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[ 1, 0, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[-1, 0, 0],
[ 0, 0, -1]]])
>>> trans
array([[ 0. , 0. , 0. ],
[ 0.5, 0.5, 0. ],
[ 0. , 0. , 0. ]])
"""
nsym = len(symlist)
rot = np.zeros((nsym, 3, 3), dtype='int')
trans = np.zeros((nsym, 3))
for i, sym in enumerate(symlist):
for j, s in enumerate (sym.split(sep)):
s = s.lower().strip()
while s:
sign = 1
if s[0] in '+-':
if s[0] == '-':
sign = -1
s = s[1:]
if s[0] in 'xyz':
k = ord(s[0]) - ord('x')
rot[i, j, k] = sign
s = s[1:]
elif s[0].isdigit() or s[0] == '.':
n = 0
while n < len(s) and (s[n].isdigit() or s[n] in '/.'):
n += 1
t = s[:n]
s = s[n:]
if '/' in t:
q, r = t.split('/')
trans[i,j] = float(q)/float(r)
else:
trans[i,j] = float(t)
else:
raise SpacegroupValueError(
'Error parsing %r. Invalid site symmetry: %s' %
(s, sym))
return rot, trans | [
"def",
"parse_sitesym",
"(",
"symlist",
",",
"sep",
"=",
"','",
")",
":",
"nsym",
"=",
"len",
"(",
"symlist",
")",
"rot",
"=",
"np",
".",
"zeros",
"(",
"(",
"nsym",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'int'",
")",
"trans",
"=",
"np",
".",
"zeros",
"(",
"(",
"nsym",
",",
"3",
")",
")",
"for",
"i",
",",
"sym",
"in",
"enumerate",
"(",
"symlist",
")",
":",
"for",
"j",
",",
"s",
"in",
"enumerate",
"(",
"sym",
".",
"split",
"(",
"sep",
")",
")",
":",
"s",
"=",
"s",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"while",
"s",
":",
"sign",
"=",
"1",
"if",
"s",
"[",
"0",
"]",
"in",
"'+-'",
":",
"if",
"s",
"[",
"0",
"]",
"==",
"'-'",
":",
"sign",
"=",
"-",
"1",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"if",
"s",
"[",
"0",
"]",
"in",
"'xyz'",
":",
"k",
"=",
"ord",
"(",
"s",
"[",
"0",
"]",
")",
"-",
"ord",
"(",
"'x'",
")",
"rot",
"[",
"i",
",",
"j",
",",
"k",
"]",
"=",
"sign",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"elif",
"s",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"or",
"s",
"[",
"0",
"]",
"==",
"'.'",
":",
"n",
"=",
"0",
"while",
"n",
"<",
"len",
"(",
"s",
")",
"and",
"(",
"s",
"[",
"n",
"]",
".",
"isdigit",
"(",
")",
"or",
"s",
"[",
"n",
"]",
"in",
"'/.'",
")",
":",
"n",
"+=",
"1",
"t",
"=",
"s",
"[",
":",
"n",
"]",
"s",
"=",
"s",
"[",
"n",
":",
"]",
"if",
"'/'",
"in",
"t",
":",
"q",
",",
"r",
"=",
"t",
".",
"split",
"(",
"'/'",
")",
"trans",
"[",
"i",
",",
"j",
"]",
"=",
"float",
"(",
"q",
")",
"/",
"float",
"(",
"r",
")",
"else",
":",
"trans",
"[",
"i",
",",
"j",
"]",
"=",
"float",
"(",
"t",
")",
"else",
":",
"raise",
"SpacegroupValueError",
"(",
"'Error parsing %r. Invalid site symmetry: %s'",
"%",
"(",
"s",
",",
"sym",
")",
")",
"return",
"rot",
",",
"trans"
] | Parses a sequence of site symmetries in the form used by
International Tables and returns corresponding rotation and
translation arrays.
Example:
>>> symlist = [
... 'x,y,z',
... '-y+1/2,x+1/2,z',
... '-y,-x,-z',
... ]
>>> rot, trans = parse_sitesym(symlist)
>>> rot
array([[[ 1, 0, 0],
[ 0, 1, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[ 1, 0, 0],
[ 0, 0, 1]],
<BLANKLINE>
[[ 0, -1, 0],
[-1, 0, 0],
[ 0, 0, -1]]])
>>> trans
array([[ 0. , 0. , 0. ],
[ 0.5, 0.5, 0. ],
[ 0. , 0. , 0. ]]) | [
"Parses",
"a",
"sequence",
"of",
"site",
"symmetries",
"in",
"the",
"form",
"used",
"by",
"International",
"Tables",
"and",
"returns",
"corresponding",
"rotation",
"and",
"translation",
"arrays",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L596-L657 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | spacegroup_from_data | def spacegroup_from_data(no=None, symbol=None, setting=1,
centrosymmetric=None, scaled_primitive_cell=None,
reciprocal_cell=None, subtrans=None, sitesym=None,
rotations=None, translations=None, datafile=None):
"""Manually create a new space group instance. This might be
usefull when reading crystal data with its own spacegroup
definitions."""
if no is not None:
spg = Spacegroup(no, setting, datafile)
elif symbol is not None:
spg = Spacegroup(symbol, setting, datafile)
else:
raise SpacegroupValueError('either *no* or *symbol* must be given')
have_sym = False
if centrosymmetric is not None:
spg._centrosymmetric = bool(centrosymmetric)
if scaled_primitive_cell is not None:
spg._scaled_primitive_cell = np.array(scaled_primitive_cell)
if reciprocal_cell is not None:
spg._reciprocal_cell = np.array(reciprocal_cell)
if subtrans is not None:
spg._subtrans = np.atleast_2d(subtrans)
spg._nsubtrans = spg._subtrans.shape[0]
if sitesym is not None:
spg._rotations, spg._translations = parse_sitesym(sitesym)
have_sym = True
if rotations is not None:
spg._rotations = np.atleast_3d(rotations)
have_sym = True
if translations is not None:
spg._translations = np.atleast_2d(translations)
have_sym = True
if have_sym:
if spg._rotations.shape[0] != spg._translations.shape[0]:
raise SpacegroupValueError('inconsistent number of rotations and '
'translations')
spg._nsymop = spg._rotations.shape[0]
return spg | python | def spacegroup_from_data(no=None, symbol=None, setting=1,
centrosymmetric=None, scaled_primitive_cell=None,
reciprocal_cell=None, subtrans=None, sitesym=None,
rotations=None, translations=None, datafile=None):
"""Manually create a new space group instance. This might be
usefull when reading crystal data with its own spacegroup
definitions."""
if no is not None:
spg = Spacegroup(no, setting, datafile)
elif symbol is not None:
spg = Spacegroup(symbol, setting, datafile)
else:
raise SpacegroupValueError('either *no* or *symbol* must be given')
have_sym = False
if centrosymmetric is not None:
spg._centrosymmetric = bool(centrosymmetric)
if scaled_primitive_cell is not None:
spg._scaled_primitive_cell = np.array(scaled_primitive_cell)
if reciprocal_cell is not None:
spg._reciprocal_cell = np.array(reciprocal_cell)
if subtrans is not None:
spg._subtrans = np.atleast_2d(subtrans)
spg._nsubtrans = spg._subtrans.shape[0]
if sitesym is not None:
spg._rotations, spg._translations = parse_sitesym(sitesym)
have_sym = True
if rotations is not None:
spg._rotations = np.atleast_3d(rotations)
have_sym = True
if translations is not None:
spg._translations = np.atleast_2d(translations)
have_sym = True
if have_sym:
if spg._rotations.shape[0] != spg._translations.shape[0]:
raise SpacegroupValueError('inconsistent number of rotations and '
'translations')
spg._nsymop = spg._rotations.shape[0]
return spg | [
"def",
"spacegroup_from_data",
"(",
"no",
"=",
"None",
",",
"symbol",
"=",
"None",
",",
"setting",
"=",
"1",
",",
"centrosymmetric",
"=",
"None",
",",
"scaled_primitive_cell",
"=",
"None",
",",
"reciprocal_cell",
"=",
"None",
",",
"subtrans",
"=",
"None",
",",
"sitesym",
"=",
"None",
",",
"rotations",
"=",
"None",
",",
"translations",
"=",
"None",
",",
"datafile",
"=",
"None",
")",
":",
"if",
"no",
"is",
"not",
"None",
":",
"spg",
"=",
"Spacegroup",
"(",
"no",
",",
"setting",
",",
"datafile",
")",
"elif",
"symbol",
"is",
"not",
"None",
":",
"spg",
"=",
"Spacegroup",
"(",
"symbol",
",",
"setting",
",",
"datafile",
")",
"else",
":",
"raise",
"SpacegroupValueError",
"(",
"'either *no* or *symbol* must be given'",
")",
"have_sym",
"=",
"False",
"if",
"centrosymmetric",
"is",
"not",
"None",
":",
"spg",
".",
"_centrosymmetric",
"=",
"bool",
"(",
"centrosymmetric",
")",
"if",
"scaled_primitive_cell",
"is",
"not",
"None",
":",
"spg",
".",
"_scaled_primitive_cell",
"=",
"np",
".",
"array",
"(",
"scaled_primitive_cell",
")",
"if",
"reciprocal_cell",
"is",
"not",
"None",
":",
"spg",
".",
"_reciprocal_cell",
"=",
"np",
".",
"array",
"(",
"reciprocal_cell",
")",
"if",
"subtrans",
"is",
"not",
"None",
":",
"spg",
".",
"_subtrans",
"=",
"np",
".",
"atleast_2d",
"(",
"subtrans",
")",
"spg",
".",
"_nsubtrans",
"=",
"spg",
".",
"_subtrans",
".",
"shape",
"[",
"0",
"]",
"if",
"sitesym",
"is",
"not",
"None",
":",
"spg",
".",
"_rotations",
",",
"spg",
".",
"_translations",
"=",
"parse_sitesym",
"(",
"sitesym",
")",
"have_sym",
"=",
"True",
"if",
"rotations",
"is",
"not",
"None",
":",
"spg",
".",
"_rotations",
"=",
"np",
".",
"atleast_3d",
"(",
"rotations",
")",
"have_sym",
"=",
"True",
"if",
"translations",
"is",
"not",
"None",
":",
"spg",
".",
"_translations",
"=",
"np",
".",
"atleast_2d",
"(",
"translations",
")",
"have_sym",
"=",
"True",
"if",
"have_sym",
":",
"if",
"spg",
".",
"_rotations",
".",
"shape",
"[",
"0",
"]",
"!=",
"spg",
".",
"_translations",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"SpacegroupValueError",
"(",
"'inconsistent number of rotations and '",
"'translations'",
")",
"spg",
".",
"_nsymop",
"=",
"spg",
".",
"_rotations",
".",
"shape",
"[",
"0",
"]",
"return",
"spg"
] | Manually create a new space group instance. This might be
usefull when reading crystal data with its own spacegroup
definitions. | [
"Manually",
"create",
"a",
"new",
"space",
"group",
"instance",
".",
"This",
"might",
"be",
"usefull",
"when",
"reading",
"crystal",
"data",
"with",
"its",
"own",
"spacegroup",
"definitions",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L660-L698 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | Spacegroup._get_nsymop | def _get_nsymop(self):
"""Returns total number of symmetry operations."""
if self.centrosymmetric:
return 2 * len(self._rotations) * len(self._subtrans)
else:
return len(self._rotations) * len(self._subtrans) | python | def _get_nsymop(self):
"""Returns total number of symmetry operations."""
if self.centrosymmetric:
return 2 * len(self._rotations) * len(self._subtrans)
else:
return len(self._rotations) * len(self._subtrans) | [
"def",
"_get_nsymop",
"(",
"self",
")",
":",
"if",
"self",
".",
"centrosymmetric",
":",
"return",
"2",
"*",
"len",
"(",
"self",
".",
"_rotations",
")",
"*",
"len",
"(",
"self",
".",
"_subtrans",
")",
"else",
":",
"return",
"len",
"(",
"self",
".",
"_rotations",
")",
"*",
"len",
"(",
"self",
".",
"_subtrans",
")"
] | Returns total number of symmetry operations. | [
"Returns",
"total",
"number",
"of",
"symmetry",
"operations",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L86-L91 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | Spacegroup.get_rotations | def get_rotations(self):
"""Return all rotations, including inversions for
centrosymmetric crystals."""
if self.centrosymmetric:
return np.vstack((self.rotations, -self.rotations))
else:
return self.rotations | python | def get_rotations(self):
"""Return all rotations, including inversions for
centrosymmetric crystals."""
if self.centrosymmetric:
return np.vstack((self.rotations, -self.rotations))
else:
return self.rotations | [
"def",
"get_rotations",
"(",
"self",
")",
":",
"if",
"self",
".",
"centrosymmetric",
":",
"return",
"np",
".",
"vstack",
"(",
"(",
"self",
".",
"rotations",
",",
"-",
"self",
".",
"rotations",
")",
")",
"else",
":",
"return",
"self",
".",
"rotations"
] | Return all rotations, including inversions for
centrosymmetric crystals. | [
"Return",
"all",
"rotations",
"including",
"inversions",
"for",
"centrosymmetric",
"crystals",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L221-L227 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | Spacegroup.equivalent_reflections | def equivalent_reflections(self, hkl):
"""Return all equivalent reflections to the list of Miller indices
in hkl.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.equivalent_reflections([[0, 0, 2]])
array([[ 0, 0, -2],
[ 0, -2, 0],
[-2, 0, 0],
[ 2, 0, 0],
[ 0, 2, 0],
[ 0, 0, 2]])
"""
hkl = np.array(hkl, dtype='int', ndmin=2)
rot = self.get_rotations()
n, nrot = len(hkl), len(rot)
R = rot.transpose(0, 2, 1).reshape((3*nrot, 3)).T
refl = np.dot(hkl, R).reshape((n*nrot, 3))
ind = np.lexsort(refl.T)
refl = refl[ind]
diff = np.diff(refl, axis=0)
mask = np.any(diff, axis=1)
return np.vstack((refl[mask], refl[-1,:])) | python | def equivalent_reflections(self, hkl):
"""Return all equivalent reflections to the list of Miller indices
in hkl.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.equivalent_reflections([[0, 0, 2]])
array([[ 0, 0, -2],
[ 0, -2, 0],
[-2, 0, 0],
[ 2, 0, 0],
[ 0, 2, 0],
[ 0, 0, 2]])
"""
hkl = np.array(hkl, dtype='int', ndmin=2)
rot = self.get_rotations()
n, nrot = len(hkl), len(rot)
R = rot.transpose(0, 2, 1).reshape((3*nrot, 3)).T
refl = np.dot(hkl, R).reshape((n*nrot, 3))
ind = np.lexsort(refl.T)
refl = refl[ind]
diff = np.diff(refl, axis=0)
mask = np.any(diff, axis=1)
return np.vstack((refl[mask], refl[-1,:])) | [
"def",
"equivalent_reflections",
"(",
"self",
",",
"hkl",
")",
":",
"hkl",
"=",
"np",
".",
"array",
"(",
"hkl",
",",
"dtype",
"=",
"'int'",
",",
"ndmin",
"=",
"2",
")",
"rot",
"=",
"self",
".",
"get_rotations",
"(",
")",
"n",
",",
"nrot",
"=",
"len",
"(",
"hkl",
")",
",",
"len",
"(",
"rot",
")",
"R",
"=",
"rot",
".",
"transpose",
"(",
"0",
",",
"2",
",",
"1",
")",
".",
"reshape",
"(",
"(",
"3",
"*",
"nrot",
",",
"3",
")",
")",
".",
"T",
"refl",
"=",
"np",
".",
"dot",
"(",
"hkl",
",",
"R",
")",
".",
"reshape",
"(",
"(",
"n",
"*",
"nrot",
",",
"3",
")",
")",
"ind",
"=",
"np",
".",
"lexsort",
"(",
"refl",
".",
"T",
")",
"refl",
"=",
"refl",
"[",
"ind",
"]",
"diff",
"=",
"np",
".",
"diff",
"(",
"refl",
",",
"axis",
"=",
"0",
")",
"mask",
"=",
"np",
".",
"any",
"(",
"diff",
",",
"axis",
"=",
"1",
")",
"return",
"np",
".",
"vstack",
"(",
"(",
"refl",
"[",
"mask",
"]",
",",
"refl",
"[",
"-",
"1",
",",
":",
"]",
")",
")"
] | Return all equivalent reflections to the list of Miller indices
in hkl.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sg.equivalent_reflections([[0, 0, 2]])
array([[ 0, 0, -2],
[ 0, -2, 0],
[-2, 0, 0],
[ 2, 0, 0],
[ 0, 2, 0],
[ 0, 0, 2]]) | [
"Return",
"all",
"equivalent",
"reflections",
"to",
"the",
"list",
"of",
"Miller",
"indices",
"in",
"hkl",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L229-L254 | train |
chemlab/chemlab | chemlab/core/spacegroup/spacegroup.py | Spacegroup.equivalent_sites | def equivalent_sites(self, scaled_positions, ondublicates='error',
symprec=1e-3):
"""Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
ondublicates : 'keep' | 'replace' | 'warn' | 'error'
Action if `scaled_positions` contain symmetry-equivalent
positions:
'keep'
ignore additional symmetry-equivalent positions
'replace'
replace
'warn'
like 'keep', but issue an UserWarning
'error'
raises a SpacegroupValueError
symprec: float
Minimum "distance" betweed two sites in scaled coordinates
before they are counted as the same site.
Returns:
sites: array
A NumPy array of equivalent sites.
kinds: list
A list of integer indices specifying which input site is
equivalent to the corresponding returned site.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]])
>>> sites
array([[ 0. , 0. , 0. ],
[ 0. , 0.5, 0.5],
[ 0.5, 0. , 0.5],
[ 0.5, 0.5, 0. ],
[ 0.5, 0. , 0. ],
[ 0. , 0.5, 0. ],
[ 0. , 0. , 0.5],
[ 0.5, 0.5, 0.5]])
>>> kinds
[0, 0, 0, 0, 1, 1, 1, 1]
"""
kinds = []
sites = []
symprec2 = symprec**2
scaled = np.array(scaled_positions, ndmin=2)
for kind, pos in enumerate(scaled):
for rot, trans in self.get_symop():
site = np.mod(np.dot(rot, pos) + trans, 1.)
if not sites:
sites.append(site)
kinds.append(kind)
continue
t = site - sites
mask = np.sum(t*t, 1) < symprec2
if np.any(mask):
ind = np.argwhere(mask)[0][0]
if kinds[ind] == kind:
pass
elif ondublicates == 'keep':
pass
elif ondublicates == 'replace':
kinds[ind] = kind
elif ondublicates == 'warn':
warnings.warn('scaled_positions %d and %d '
'are equivalent'%(kinds[ind], kind))
elif ondublicates == 'error':
raise SpacegroupValueError(
'scaled_positions %d and %d are equivalent'%(
kinds[ind], kind))
else:
raise SpacegroupValueError(
'Argument "ondublicates" must be one of: '
'"keep", "replace", "warn" or "error".')
else:
sites.append(site)
kinds.append(kind)
return np.array(sites), kinds | python | def equivalent_sites(self, scaled_positions, ondublicates='error',
symprec=1e-3):
"""Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
ondublicates : 'keep' | 'replace' | 'warn' | 'error'
Action if `scaled_positions` contain symmetry-equivalent
positions:
'keep'
ignore additional symmetry-equivalent positions
'replace'
replace
'warn'
like 'keep', but issue an UserWarning
'error'
raises a SpacegroupValueError
symprec: float
Minimum "distance" betweed two sites in scaled coordinates
before they are counted as the same site.
Returns:
sites: array
A NumPy array of equivalent sites.
kinds: list
A list of integer indices specifying which input site is
equivalent to the corresponding returned site.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]])
>>> sites
array([[ 0. , 0. , 0. ],
[ 0. , 0.5, 0.5],
[ 0.5, 0. , 0.5],
[ 0.5, 0.5, 0. ],
[ 0.5, 0. , 0. ],
[ 0. , 0.5, 0. ],
[ 0. , 0. , 0.5],
[ 0.5, 0.5, 0.5]])
>>> kinds
[0, 0, 0, 0, 1, 1, 1, 1]
"""
kinds = []
sites = []
symprec2 = symprec**2
scaled = np.array(scaled_positions, ndmin=2)
for kind, pos in enumerate(scaled):
for rot, trans in self.get_symop():
site = np.mod(np.dot(rot, pos) + trans, 1.)
if not sites:
sites.append(site)
kinds.append(kind)
continue
t = site - sites
mask = np.sum(t*t, 1) < symprec2
if np.any(mask):
ind = np.argwhere(mask)[0][0]
if kinds[ind] == kind:
pass
elif ondublicates == 'keep':
pass
elif ondublicates == 'replace':
kinds[ind] = kind
elif ondublicates == 'warn':
warnings.warn('scaled_positions %d and %d '
'are equivalent'%(kinds[ind], kind))
elif ondublicates == 'error':
raise SpacegroupValueError(
'scaled_positions %d and %d are equivalent'%(
kinds[ind], kind))
else:
raise SpacegroupValueError(
'Argument "ondublicates" must be one of: '
'"keep", "replace", "warn" or "error".')
else:
sites.append(site)
kinds.append(kind)
return np.array(sites), kinds | [
"def",
"equivalent_sites",
"(",
"self",
",",
"scaled_positions",
",",
"ondublicates",
"=",
"'error'",
",",
"symprec",
"=",
"1e-3",
")",
":",
"kinds",
"=",
"[",
"]",
"sites",
"=",
"[",
"]",
"symprec2",
"=",
"symprec",
"**",
"2",
"scaled",
"=",
"np",
".",
"array",
"(",
"scaled_positions",
",",
"ndmin",
"=",
"2",
")",
"for",
"kind",
",",
"pos",
"in",
"enumerate",
"(",
"scaled",
")",
":",
"for",
"rot",
",",
"trans",
"in",
"self",
".",
"get_symop",
"(",
")",
":",
"site",
"=",
"np",
".",
"mod",
"(",
"np",
".",
"dot",
"(",
"rot",
",",
"pos",
")",
"+",
"trans",
",",
"1.",
")",
"if",
"not",
"sites",
":",
"sites",
".",
"append",
"(",
"site",
")",
"kinds",
".",
"append",
"(",
"kind",
")",
"continue",
"t",
"=",
"site",
"-",
"sites",
"mask",
"=",
"np",
".",
"sum",
"(",
"t",
"*",
"t",
",",
"1",
")",
"<",
"symprec2",
"if",
"np",
".",
"any",
"(",
"mask",
")",
":",
"ind",
"=",
"np",
".",
"argwhere",
"(",
"mask",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"kinds",
"[",
"ind",
"]",
"==",
"kind",
":",
"pass",
"elif",
"ondublicates",
"==",
"'keep'",
":",
"pass",
"elif",
"ondublicates",
"==",
"'replace'",
":",
"kinds",
"[",
"ind",
"]",
"=",
"kind",
"elif",
"ondublicates",
"==",
"'warn'",
":",
"warnings",
".",
"warn",
"(",
"'scaled_positions %d and %d '",
"'are equivalent'",
"%",
"(",
"kinds",
"[",
"ind",
"]",
",",
"kind",
")",
")",
"elif",
"ondublicates",
"==",
"'error'",
":",
"raise",
"SpacegroupValueError",
"(",
"'scaled_positions %d and %d are equivalent'",
"%",
"(",
"kinds",
"[",
"ind",
"]",
",",
"kind",
")",
")",
"else",
":",
"raise",
"SpacegroupValueError",
"(",
"'Argument \"ondublicates\" must be one of: '",
"'\"keep\", \"replace\", \"warn\" or \"error\".'",
")",
"else",
":",
"sites",
".",
"append",
"(",
"site",
")",
"kinds",
".",
"append",
"(",
"kind",
")",
"return",
"np",
".",
"array",
"(",
"sites",
")",
",",
"kinds"
] | Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
ondublicates : 'keep' | 'replace' | 'warn' | 'error'
Action if `scaled_positions` contain symmetry-equivalent
positions:
'keep'
ignore additional symmetry-equivalent positions
'replace'
replace
'warn'
like 'keep', but issue an UserWarning
'error'
raises a SpacegroupValueError
symprec: float
Minimum "distance" betweed two sites in scaled coordinates
before they are counted as the same site.
Returns:
sites: array
A NumPy array of equivalent sites.
kinds: list
A list of integer indices specifying which input site is
equivalent to the corresponding returned site.
Example:
>>> from ase.lattice.spacegroup import Spacegroup
>>> sg = Spacegroup(225) # fcc
>>> sites, kinds = sg.equivalent_sites([[0, 0, 0], [0.5, 0.0, 0.0]])
>>> sites
array([[ 0. , 0. , 0. ],
[ 0. , 0.5, 0.5],
[ 0.5, 0. , 0.5],
[ 0.5, 0.5, 0. ],
[ 0.5, 0. , 0. ],
[ 0. , 0.5, 0. ],
[ 0. , 0. , 0.5],
[ 0.5, 0.5, 0.5]])
>>> kinds
[0, 0, 0, 0, 1, 1, 1, 1] | [
"Returns",
"the",
"scaled",
"positions",
"and",
"all",
"their",
"equivalent",
"sites",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/spacegroup.py#L302-L387 | train |
chemlab/chemlab | chemlab/io/handlers/utils.py | guess_type | def guess_type(typ):
'''Guess the atom type from purely heuristic considerations.'''
# Strip useless numbers
match = re.match("([a-zA-Z]+)\d*", typ)
if match:
typ = match.groups()[0]
return typ | python | def guess_type(typ):
'''Guess the atom type from purely heuristic considerations.'''
# Strip useless numbers
match = re.match("([a-zA-Z]+)\d*", typ)
if match:
typ = match.groups()[0]
return typ | [
"def",
"guess_type",
"(",
"typ",
")",
":",
"# Strip useless numbers",
"match",
"=",
"re",
".",
"match",
"(",
"\"([a-zA-Z]+)\\d*\"",
",",
"typ",
")",
"if",
"match",
":",
"typ",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"return",
"typ"
] | Guess the atom type from purely heuristic considerations. | [
"Guess",
"the",
"atom",
"type",
"from",
"purely",
"heuristic",
"considerations",
"."
] | c8730966316d101e24f39ac3b96b51282aba0abe | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/io/handlers/utils.py#L3-L9 | train |
janpipek/physt | physt/plotting/matplotlib.py | register | def register(*dim: List[int], use_3d: bool = False, use_polar: bool = False, collection: bool = False):
"""Decorator to wrap common plotting functionality.
Parameters
----------
dim : Dimensionality of histogram for which it is applicable
use_3d : If True, the figure will be 3D.
use_polar : If True, the figure will be in polar coordinates.
collection : Whether to allow histogram collections to be used
"""
if use_3d and use_polar:
raise RuntimeError("Cannot have polar and 3d coordinates simultaneously.")
# TODO: Add some kind of class parameter
def decorate(function):
types.append(function.__name__)
dims[function.__name__] = dim
@wraps(function)
def f(hist, write_to: Optional[str] = None, dpi:Optional[float] = None, **kwargs):
fig, ax = _get_axes(kwargs, use_3d=use_3d, use_polar=use_polar)
from physt.histogram_collection import HistogramCollection
if collection and isinstance(hist, HistogramCollection):
title = kwargs.pop("title", hist.title)
if not hist:
raise ValueError("Cannot plot empty histogram collection")
for i, h in enumerate(hist):
# TODO: Add some mechanism for argument maps (like sklearn?)
function(h, ax=ax, **kwargs)
ax.legend()
ax.set_title(title)
else:
function(hist, ax=ax, **kwargs)
if write_to:
fig = ax.figure
fig.tight_layout()
fig.savefig(write_to, dpi=dpi or default_dpi)
return ax
return f
return decorate | python | def register(*dim: List[int], use_3d: bool = False, use_polar: bool = False, collection: bool = False):
"""Decorator to wrap common plotting functionality.
Parameters
----------
dim : Dimensionality of histogram for which it is applicable
use_3d : If True, the figure will be 3D.
use_polar : If True, the figure will be in polar coordinates.
collection : Whether to allow histogram collections to be used
"""
if use_3d and use_polar:
raise RuntimeError("Cannot have polar and 3d coordinates simultaneously.")
# TODO: Add some kind of class parameter
def decorate(function):
types.append(function.__name__)
dims[function.__name__] = dim
@wraps(function)
def f(hist, write_to: Optional[str] = None, dpi:Optional[float] = None, **kwargs):
fig, ax = _get_axes(kwargs, use_3d=use_3d, use_polar=use_polar)
from physt.histogram_collection import HistogramCollection
if collection and isinstance(hist, HistogramCollection):
title = kwargs.pop("title", hist.title)
if not hist:
raise ValueError("Cannot plot empty histogram collection")
for i, h in enumerate(hist):
# TODO: Add some mechanism for argument maps (like sklearn?)
function(h, ax=ax, **kwargs)
ax.legend()
ax.set_title(title)
else:
function(hist, ax=ax, **kwargs)
if write_to:
fig = ax.figure
fig.tight_layout()
fig.savefig(write_to, dpi=dpi or default_dpi)
return ax
return f
return decorate | [
"def",
"register",
"(",
"*",
"dim",
":",
"List",
"[",
"int",
"]",
",",
"use_3d",
":",
"bool",
"=",
"False",
",",
"use_polar",
":",
"bool",
"=",
"False",
",",
"collection",
":",
"bool",
"=",
"False",
")",
":",
"if",
"use_3d",
"and",
"use_polar",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot have polar and 3d coordinates simultaneously.\"",
")",
"# TODO: Add some kind of class parameter",
"def",
"decorate",
"(",
"function",
")",
":",
"types",
".",
"append",
"(",
"function",
".",
"__name__",
")",
"dims",
"[",
"function",
".",
"__name__",
"]",
"=",
"dim",
"@",
"wraps",
"(",
"function",
")",
"def",
"f",
"(",
"hist",
",",
"write_to",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"dpi",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"fig",
",",
"ax",
"=",
"_get_axes",
"(",
"kwargs",
",",
"use_3d",
"=",
"use_3d",
",",
"use_polar",
"=",
"use_polar",
")",
"from",
"physt",
".",
"histogram_collection",
"import",
"HistogramCollection",
"if",
"collection",
"and",
"isinstance",
"(",
"hist",
",",
"HistogramCollection",
")",
":",
"title",
"=",
"kwargs",
".",
"pop",
"(",
"\"title\"",
",",
"hist",
".",
"title",
")",
"if",
"not",
"hist",
":",
"raise",
"ValueError",
"(",
"\"Cannot plot empty histogram collection\"",
")",
"for",
"i",
",",
"h",
"in",
"enumerate",
"(",
"hist",
")",
":",
"# TODO: Add some mechanism for argument maps (like sklearn?)",
"function",
"(",
"h",
",",
"ax",
"=",
"ax",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"legend",
"(",
")",
"ax",
".",
"set_title",
"(",
"title",
")",
"else",
":",
"function",
"(",
"hist",
",",
"ax",
"=",
"ax",
",",
"*",
"*",
"kwargs",
")",
"if",
"write_to",
":",
"fig",
"=",
"ax",
".",
"figure",
"fig",
".",
"tight_layout",
"(",
")",
"fig",
".",
"savefig",
"(",
"write_to",
",",
"dpi",
"=",
"dpi",
"or",
"default_dpi",
")",
"return",
"ax",
"return",
"f",
"return",
"decorate"
] | Decorator to wrap common plotting functionality.
Parameters
----------
dim : Dimensionality of histogram for which it is applicable
use_3d : If True, the figure will be 3D.
use_polar : If True, the figure will be in polar coordinates.
collection : Whether to allow histogram collections to be used | [
"Decorator",
"to",
"wrap",
"common",
"plotting",
"functionality",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L63-L105 | train |
janpipek/physt | physt/plotting/matplotlib.py | bar | def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Bar plot of 1D histograms."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
value_format = kwargs.pop("value_format", None)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
label = kwargs.pop("label", h1.name)
lw = kwargs.pop("linewidth", kwargs.pop("lw", 0.5))
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
data = get_data(h1, cumulative=cumulative, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
else:
colors = kwargs.pop("color", None)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
kwargs["yerr"] = err_data
if "ecolor" not in kwargs:
kwargs["ecolor"] = "black"
_add_labels(ax, h1, kwargs)
ax.bar(h1.bin_left_edges, data, h1.bin_widths, align="edge",
label=label, color=colors, linewidth=lw, **kwargs)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats) | python | def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Bar plot of 1D histograms."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
value_format = kwargs.pop("value_format", None)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
label = kwargs.pop("label", h1.name)
lw = kwargs.pop("linewidth", kwargs.pop("lw", 0.5))
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
data = get_data(h1, cumulative=cumulative, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
else:
colors = kwargs.pop("color", None)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
kwargs["yerr"] = err_data
if "ecolor" not in kwargs:
kwargs["ecolor"] = "black"
_add_labels(ax, h1, kwargs)
ax.bar(h1.bin_left_edges, data, h1.bin_widths, align="edge",
label=label, color=colors, linewidth=lw, **kwargs)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats) | [
"def",
"bar",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"errors",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"show_values",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_values\"",
",",
"False",
")",
"value_format",
"=",
"kwargs",
".",
"pop",
"(",
"\"value_format\"",
",",
"None",
")",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"cumulative",
"=",
"kwargs",
".",
"pop",
"(",
"\"cumulative\"",
",",
"False",
")",
"label",
"=",
"kwargs",
".",
"pop",
"(",
"\"label\"",
",",
"h1",
".",
"name",
")",
"lw",
"=",
"kwargs",
".",
"pop",
"(",
"\"linewidth\"",
",",
"kwargs",
".",
"pop",
"(",
"\"lw\"",
",",
"0.5",
")",
")",
"text_kwargs",
"=",
"pop_kwargs_with_prefix",
"(",
"\"text_\"",
",",
"kwargs",
")",
"data",
"=",
"get_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"if",
"\"cmap\"",
"in",
"kwargs",
":",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"_",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"colors",
"=",
"cmap",
"(",
"cmap_data",
")",
"else",
":",
"colors",
"=",
"kwargs",
".",
"pop",
"(",
"\"color\"",
",",
"None",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"kwargs",
")",
"_add_ticks",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"if",
"errors",
":",
"err_data",
"=",
"get_err_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"kwargs",
"[",
"\"yerr\"",
"]",
"=",
"err_data",
"if",
"\"ecolor\"",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"ecolor\"",
"]",
"=",
"\"black\"",
"_add_labels",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"ax",
".",
"bar",
"(",
"h1",
".",
"bin_left_edges",
",",
"data",
",",
"h1",
".",
"bin_widths",
",",
"align",
"=",
"\"edge\"",
",",
"label",
"=",
"label",
",",
"color",
"=",
"colors",
",",
"linewidth",
"=",
"lw",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_values",
":",
"_add_values",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"value_format",
"=",
"value_format",
",",
"*",
"*",
"text_kwargs",
")",
"if",
"show_stats",
":",
"_add_stats_box",
"(",
"h1",
",",
"ax",
",",
"stats",
"=",
"show_stats",
")"
] | Bar plot of 1D histograms. | [
"Bar",
"plot",
"of",
"1D",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L109-L145 | train |
janpipek/physt | physt/plotting/matplotlib.py | scatter | def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Scatter plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
data = get_data(h1, cumulative=cumulative, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
kwargs["color"] = cmap(cmap_data)
else:
kwargs["color"] = kwargs.pop("color", "blue")
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"),
ecolor=kwargs.pop("ecolor", "black"), ms=0)
ax.scatter(h1.bin_centers, data, **kwargs)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats) | python | def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs):
"""Scatter plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
data = get_data(h1, cumulative=cumulative, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
kwargs["color"] = cmap(cmap_data)
else:
kwargs["color"] = kwargs.pop("color", "blue")
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"),
ecolor=kwargs.pop("ecolor", "black"), ms=0)
ax.scatter(h1.bin_centers, data, **kwargs)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats) | [
"def",
"scatter",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"errors",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"show_values",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_values\"",
",",
"False",
")",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"cumulative",
"=",
"kwargs",
".",
"pop",
"(",
"\"cumulative\"",
",",
"False",
")",
"value_format",
"=",
"kwargs",
".",
"pop",
"(",
"\"value_format\"",
",",
"None",
")",
"text_kwargs",
"=",
"pop_kwargs_with_prefix",
"(",
"\"text_\"",
",",
"kwargs",
")",
"data",
"=",
"get_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"if",
"\"cmap\"",
"in",
"kwargs",
":",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"_",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"kwargs",
"[",
"\"color\"",
"]",
"=",
"cmap",
"(",
"cmap_data",
")",
"else",
":",
"kwargs",
"[",
"\"color\"",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"\"color\"",
",",
"\"blue\"",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"kwargs",
")",
"_add_ticks",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"_add_labels",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"if",
"errors",
":",
"err_data",
"=",
"get_err_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"ax",
".",
"errorbar",
"(",
"h1",
".",
"bin_centers",
",",
"data",
",",
"yerr",
"=",
"err_data",
",",
"fmt",
"=",
"kwargs",
".",
"pop",
"(",
"\"fmt\"",
",",
"\"o\"",
")",
",",
"ecolor",
"=",
"kwargs",
".",
"pop",
"(",
"\"ecolor\"",
",",
"\"black\"",
")",
",",
"ms",
"=",
"0",
")",
"ax",
".",
"scatter",
"(",
"h1",
".",
"bin_centers",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_values",
":",
"_add_values",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"value_format",
"=",
"value_format",
",",
"*",
"*",
"text_kwargs",
")",
"if",
"show_stats",
":",
"_add_stats_box",
"(",
"h1",
",",
"ax",
",",
"stats",
"=",
"show_stats",
")"
] | Scatter plot of 1D histogram. | [
"Scatter",
"plot",
"of",
"1D",
"histogram",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L149-L180 | train |
janpipek/physt | physt/plotting/matplotlib.py | line | def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs):
"""Line plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop(
"fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs)
else:
ax.plot(h1.bin_centers, data, **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs) | python | def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs):
"""Line plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
if errors:
err_data = get_err_data(h1, cumulative=cumulative, density=density)
ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop(
"fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs)
else:
ax.plot(h1.bin_centers, data, **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs) | [
"def",
"line",
"(",
"h1",
":",
"Union",
"[",
"Histogram1D",
",",
"\"HistogramCollection\"",
"]",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"errors",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"show_values",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_values\"",
",",
"False",
")",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"cumulative",
"=",
"kwargs",
".",
"pop",
"(",
"\"cumulative\"",
",",
"False",
")",
"value_format",
"=",
"kwargs",
".",
"pop",
"(",
"\"value_format\"",
",",
"None",
")",
"text_kwargs",
"=",
"pop_kwargs_with_prefix",
"(",
"\"text_\"",
",",
"kwargs",
")",
"kwargs",
"[",
"\"label\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"label\"",
",",
"h1",
".",
"name",
")",
"data",
"=",
"get_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"kwargs",
")",
"_add_ticks",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"_add_labels",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"if",
"errors",
":",
"err_data",
"=",
"get_err_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"ax",
".",
"errorbar",
"(",
"h1",
".",
"bin_centers",
",",
"data",
",",
"yerr",
"=",
"err_data",
",",
"fmt",
"=",
"kwargs",
".",
"pop",
"(",
"\"fmt\"",
",",
"\"-\"",
")",
",",
"ecolor",
"=",
"kwargs",
".",
"pop",
"(",
"\"ecolor\"",
",",
"\"black\"",
")",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"ax",
".",
"plot",
"(",
"h1",
".",
"bin_centers",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_stats",
":",
"_add_stats_box",
"(",
"h1",
",",
"ax",
",",
"stats",
"=",
"show_stats",
")",
"if",
"show_values",
":",
"_add_values",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"value_format",
"=",
"value_format",
",",
"*",
"*",
"text_kwargs",
")"
] | Line plot of 1D histogram. | [
"Line",
"plot",
"of",
"1D",
"histogram",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L184-L211 | train |
janpipek/physt | physt/plotting/matplotlib.py | fill | def fill(h1: Histogram1D, ax: Axes, **kwargs):
"""Fill plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
# show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
ax.fill_between(h1.bin_centers, 0, data, **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
# if show_values:
# _add_values(ax, h1, data)
return ax | python | def fill(h1: Histogram1D, ax: Axes, **kwargs):
"""Fill plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
# show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
ax.fill_between(h1.bin_centers, 0, data, **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
# if show_values:
# _add_values(ax, h1, data)
return ax | [
"def",
"fill",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"# show_values = kwargs.pop(\"show_values\", False)",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"cumulative",
"=",
"kwargs",
".",
"pop",
"(",
"\"cumulative\"",
",",
"False",
")",
"kwargs",
"[",
"\"label\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"label\"",
",",
"h1",
".",
"name",
")",
"data",
"=",
"get_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"kwargs",
")",
"_add_ticks",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"_add_labels",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"ax",
".",
"fill_between",
"(",
"h1",
".",
"bin_centers",
",",
"0",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_stats",
":",
"_add_stats_box",
"(",
"h1",
",",
"ax",
",",
"stats",
"=",
"show_stats",
")",
"# if show_values:",
"# _add_values(ax, h1, data)",
"return",
"ax"
] | Fill plot of 1D histogram. | [
"Fill",
"plot",
"of",
"1D",
"histogram",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L215-L234 | train |
janpipek/physt | physt/plotting/matplotlib.py | step | def step(h1: Histogram1D, ax: Axes, **kwargs):
"""Step line-plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
ax.step(h1.numpy_bins, np.concatenate([data[:1], data]), **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs) | python | def step(h1: Histogram1D, ax: Axes, **kwargs):
"""Step line-plot of 1D histogram."""
show_stats = kwargs.pop("show_stats", False)
show_values = kwargs.pop("show_values", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
value_format = kwargs.pop("value_format", None)
text_kwargs = pop_kwargs_with_prefix("text_", kwargs)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lims(ax, h1, data, kwargs)
_add_ticks(ax, h1, kwargs)
_add_labels(ax, h1, kwargs)
ax.step(h1.numpy_bins, np.concatenate([data[:1], data]), **kwargs)
if show_stats:
_add_stats_box(h1, ax, stats=show_stats)
if show_values:
_add_values(ax, h1, data, value_format=value_format, **text_kwargs) | [
"def",
"step",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"*",
"*",
"kwargs",
")",
":",
"show_stats",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_stats\"",
",",
"False",
")",
"show_values",
"=",
"kwargs",
".",
"pop",
"(",
"\"show_values\"",
",",
"False",
")",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"cumulative",
"=",
"kwargs",
".",
"pop",
"(",
"\"cumulative\"",
",",
"False",
")",
"value_format",
"=",
"kwargs",
".",
"pop",
"(",
"\"value_format\"",
",",
"None",
")",
"text_kwargs",
"=",
"pop_kwargs_with_prefix",
"(",
"\"text_\"",
",",
"kwargs",
")",
"kwargs",
"[",
"\"label\"",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"label\"",
",",
"h1",
".",
"name",
")",
"data",
"=",
"get_data",
"(",
"h1",
",",
"cumulative",
"=",
"cumulative",
",",
"density",
"=",
"density",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"kwargs",
")",
"_add_ticks",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"_add_labels",
"(",
"ax",
",",
"h1",
",",
"kwargs",
")",
"ax",
".",
"step",
"(",
"h1",
".",
"numpy_bins",
",",
"np",
".",
"concatenate",
"(",
"[",
"data",
"[",
":",
"1",
"]",
",",
"data",
"]",
")",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_stats",
":",
"_add_stats_box",
"(",
"h1",
",",
"ax",
",",
"stats",
"=",
"show_stats",
")",
"if",
"show_values",
":",
"_add_values",
"(",
"ax",
",",
"h1",
",",
"data",
",",
"value_format",
"=",
"value_format",
",",
"*",
"*",
"text_kwargs",
")"
] | Step line-plot of 1D histogram. | [
"Step",
"line",
"-",
"plot",
"of",
"1D",
"histogram",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L238-L258 | train |
janpipek/physt | physt/plotting/matplotlib.py | bar3d | def bar3d(h2: Histogram2D, ax: Axes3D, **kwargs):
"""Plot of 2D histograms as 3D boxes."""
density = kwargs.pop("density", False)
data = get_data(h2, cumulative=False, flatten=True, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
else:
colors = kwargs.pop("color", "blue")
xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers())
zpos = np.zeros_like(ypos)
dx, dy = (arr.flatten() for arr in h2.get_bin_widths())
_add_labels(ax, h2, kwargs)
ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs)
ax.set_zlabel("density" if density else "frequency") | python | def bar3d(h2: Histogram2D, ax: Axes3D, **kwargs):
"""Plot of 2D histograms as 3D boxes."""
density = kwargs.pop("density", False)
data = get_data(h2, cumulative=False, flatten=True, density=density)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
else:
colors = kwargs.pop("color", "blue")
xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers())
zpos = np.zeros_like(ypos)
dx, dy = (arr.flatten() for arr in h2.get_bin_widths())
_add_labels(ax, h2, kwargs)
ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs)
ax.set_zlabel("density" if density else "frequency") | [
"def",
"bar3d",
"(",
"h2",
":",
"Histogram2D",
",",
"ax",
":",
"Axes3D",
",",
"*",
"*",
"kwargs",
")",
":",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
"data",
"=",
"get_data",
"(",
"h2",
",",
"cumulative",
"=",
"False",
",",
"flatten",
"=",
"True",
",",
"density",
"=",
"density",
")",
"if",
"\"cmap\"",
"in",
"kwargs",
":",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"_",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"colors",
"=",
"cmap",
"(",
"cmap_data",
")",
"else",
":",
"colors",
"=",
"kwargs",
".",
"pop",
"(",
"\"color\"",
",",
"\"blue\"",
")",
"xpos",
",",
"ypos",
"=",
"(",
"arr",
".",
"flatten",
"(",
")",
"for",
"arr",
"in",
"h2",
".",
"get_bin_centers",
"(",
")",
")",
"zpos",
"=",
"np",
".",
"zeros_like",
"(",
"ypos",
")",
"dx",
",",
"dy",
"=",
"(",
"arr",
".",
"flatten",
"(",
")",
"for",
"arr",
"in",
"h2",
".",
"get_bin_widths",
"(",
")",
")",
"_add_labels",
"(",
"ax",
",",
"h2",
",",
"kwargs",
")",
"ax",
".",
"bar3d",
"(",
"xpos",
",",
"ypos",
",",
"zpos",
",",
"dx",
",",
"dy",
",",
"data",
",",
"color",
"=",
"colors",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"set_zlabel",
"(",
"\"density\"",
"if",
"density",
"else",
"\"frequency\"",
")"
] | Plot of 2D histograms as 3D boxes. | [
"Plot",
"of",
"2D",
"histograms",
"as",
"3D",
"boxes",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L393-L411 | train |
janpipek/physt | physt/plotting/matplotlib.py | image | def image(h2: Histogram2D, ax: Axes, *, show_colorbar: bool = True, interpolation: str = "nearest", **kwargs):
"""Plot of 2D histograms based on pixmaps.
Similar to map, but it:
- has fewer options
- is much more effective (enables thousands)
- does not support irregular bins
Parameters
----------
interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles)
"""
cmap = _get_cmap(kwargs) # h2 as well?
data = get_data(h2, cumulative=False, density=kwargs.pop("density", False))
norm, cmap_data = _get_cmap_data(data, kwargs)
# zorder = kwargs.pop("zorder", None)
for binning in h2._binnings:
if not binning.is_regular():
raise RuntimeError(
"Histograms with irregular bins cannot be plotted using image method.")
kwargs["interpolation"] = interpolation
if kwargs.get("xscale") == "log" or kwargs.get("yscale") == "log":
raise RuntimeError("Cannot use logarithmic axes with image plots.")
_apply_xy_lims(ax, h2, data=data, kwargs=kwargs)
_add_labels(ax, h2, kwargs)
ax.imshow(data.T[::-1, :], cmap=cmap, norm=norm,
extent=(h2.bins[0][0, 0], h2.bins[0][-1, 1],
h2.bins[1][0, 0], h2.bins[1][-1, 1]),
aspect="auto", **kwargs)
if show_colorbar:
_add_colorbar(ax, cmap, cmap_data, norm) | python | def image(h2: Histogram2D, ax: Axes, *, show_colorbar: bool = True, interpolation: str = "nearest", **kwargs):
"""Plot of 2D histograms based on pixmaps.
Similar to map, but it:
- has fewer options
- is much more effective (enables thousands)
- does not support irregular bins
Parameters
----------
interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles)
"""
cmap = _get_cmap(kwargs) # h2 as well?
data = get_data(h2, cumulative=False, density=kwargs.pop("density", False))
norm, cmap_data = _get_cmap_data(data, kwargs)
# zorder = kwargs.pop("zorder", None)
for binning in h2._binnings:
if not binning.is_regular():
raise RuntimeError(
"Histograms with irregular bins cannot be plotted using image method.")
kwargs["interpolation"] = interpolation
if kwargs.get("xscale") == "log" or kwargs.get("yscale") == "log":
raise RuntimeError("Cannot use logarithmic axes with image plots.")
_apply_xy_lims(ax, h2, data=data, kwargs=kwargs)
_add_labels(ax, h2, kwargs)
ax.imshow(data.T[::-1, :], cmap=cmap, norm=norm,
extent=(h2.bins[0][0, 0], h2.bins[0][-1, 1],
h2.bins[1][0, 0], h2.bins[1][-1, 1]),
aspect="auto", **kwargs)
if show_colorbar:
_add_colorbar(ax, cmap, cmap_data, norm) | [
"def",
"image",
"(",
"h2",
":",
"Histogram2D",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"show_colorbar",
":",
"bool",
"=",
"True",
",",
"interpolation",
":",
"str",
"=",
"\"nearest\"",
",",
"*",
"*",
"kwargs",
")",
":",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"# h2 as well?",
"data",
"=",
"get_data",
"(",
"h2",
",",
"cumulative",
"=",
"False",
",",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
")",
"norm",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"# zorder = kwargs.pop(\"zorder\", None)",
"for",
"binning",
"in",
"h2",
".",
"_binnings",
":",
"if",
"not",
"binning",
".",
"is_regular",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Histograms with irregular bins cannot be plotted using image method.\"",
")",
"kwargs",
"[",
"\"interpolation\"",
"]",
"=",
"interpolation",
"if",
"kwargs",
".",
"get",
"(",
"\"xscale\"",
")",
"==",
"\"log\"",
"or",
"kwargs",
".",
"get",
"(",
"\"yscale\"",
")",
"==",
"\"log\"",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot use logarithmic axes with image plots.\"",
")",
"_apply_xy_lims",
"(",
"ax",
",",
"h2",
",",
"data",
"=",
"data",
",",
"kwargs",
"=",
"kwargs",
")",
"_add_labels",
"(",
"ax",
",",
"h2",
",",
"kwargs",
")",
"ax",
".",
"imshow",
"(",
"data",
".",
"T",
"[",
":",
":",
"-",
"1",
",",
":",
"]",
",",
"cmap",
"=",
"cmap",
",",
"norm",
"=",
"norm",
",",
"extent",
"=",
"(",
"h2",
".",
"bins",
"[",
"0",
"]",
"[",
"0",
",",
"0",
"]",
",",
"h2",
".",
"bins",
"[",
"0",
"]",
"[",
"-",
"1",
",",
"1",
"]",
",",
"h2",
".",
"bins",
"[",
"1",
"]",
"[",
"0",
",",
"0",
"]",
",",
"h2",
".",
"bins",
"[",
"1",
"]",
"[",
"-",
"1",
",",
"1",
"]",
")",
",",
"aspect",
"=",
"\"auto\"",
",",
"*",
"*",
"kwargs",
")",
"if",
"show_colorbar",
":",
"_add_colorbar",
"(",
"ax",
",",
"cmap",
",",
"cmap_data",
",",
"norm",
")"
] | Plot of 2D histograms based on pixmaps.
Similar to map, but it:
- has fewer options
- is much more effective (enables thousands)
- does not support irregular bins
Parameters
----------
interpolation: interpolation parameter passed to imshow, default: "nearest" (creates rectangles) | [
"Plot",
"of",
"2D",
"histograms",
"based",
"on",
"pixmaps",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L415-L450 | train |
janpipek/physt | physt/plotting/matplotlib.py | polar_map | def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs):
"""Polar map of polar histograms.
Similar to map, but supports less parameters."""
data = get_data(hist, cumulative=False, flatten=True,
density=kwargs.pop("density", False))
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges())
dr, dphi = (arr.flatten() for arr in hist.get_bin_widths())
rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges())
bar_args = {}
if "zorder" in kwargs:
bar_args["zorder"] = kwargs.pop("zorder")
alphas = _get_alpha_data(cmap_data, kwargs)
if np.isscalar(alphas):
alphas = np.ones_like(data) * alphas
for i in range(len(rpos)):
if data[i] > 0 or show_zero:
bin_color = colors[i]
# TODO: align = "edge"
bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], align='edge', color=bin_color,
edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5),
alpha=alphas[i], **bar_args)
ax.set_rmax(rmax.max())
if show_colorbar:
_add_colorbar(ax, cmap, cmap_data, norm) | python | def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs):
"""Polar map of polar histograms.
Similar to map, but supports less parameters."""
data = get_data(hist, cumulative=False, flatten=True,
density=kwargs.pop("density", False))
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges())
dr, dphi = (arr.flatten() for arr in hist.get_bin_widths())
rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges())
bar_args = {}
if "zorder" in kwargs:
bar_args["zorder"] = kwargs.pop("zorder")
alphas = _get_alpha_data(cmap_data, kwargs)
if np.isscalar(alphas):
alphas = np.ones_like(data) * alphas
for i in range(len(rpos)):
if data[i] > 0 or show_zero:
bin_color = colors[i]
# TODO: align = "edge"
bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], align='edge', color=bin_color,
edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5),
alpha=alphas[i], **bar_args)
ax.set_rmax(rmax.max())
if show_colorbar:
_add_colorbar(ax, cmap, cmap_data, norm) | [
"def",
"polar_map",
"(",
"hist",
":",
"Histogram2D",
",",
"ax",
":",
"Axes",
",",
"*",
",",
"show_zero",
":",
"bool",
"=",
"True",
",",
"show_colorbar",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"get_data",
"(",
"hist",
",",
"cumulative",
"=",
"False",
",",
"flatten",
"=",
"True",
",",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
")",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"norm",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"colors",
"=",
"cmap",
"(",
"cmap_data",
")",
"rpos",
",",
"phipos",
"=",
"(",
"arr",
".",
"flatten",
"(",
")",
"for",
"arr",
"in",
"hist",
".",
"get_bin_left_edges",
"(",
")",
")",
"dr",
",",
"dphi",
"=",
"(",
"arr",
".",
"flatten",
"(",
")",
"for",
"arr",
"in",
"hist",
".",
"get_bin_widths",
"(",
")",
")",
"rmax",
",",
"_",
"=",
"(",
"arr",
".",
"flatten",
"(",
")",
"for",
"arr",
"in",
"hist",
".",
"get_bin_right_edges",
"(",
")",
")",
"bar_args",
"=",
"{",
"}",
"if",
"\"zorder\"",
"in",
"kwargs",
":",
"bar_args",
"[",
"\"zorder\"",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"\"zorder\"",
")",
"alphas",
"=",
"_get_alpha_data",
"(",
"cmap_data",
",",
"kwargs",
")",
"if",
"np",
".",
"isscalar",
"(",
"alphas",
")",
":",
"alphas",
"=",
"np",
".",
"ones_like",
"(",
"data",
")",
"*",
"alphas",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rpos",
")",
")",
":",
"if",
"data",
"[",
"i",
"]",
">",
"0",
"or",
"show_zero",
":",
"bin_color",
"=",
"colors",
"[",
"i",
"]",
"# TODO: align = \"edge\"",
"bars",
"=",
"ax",
".",
"bar",
"(",
"phipos",
"[",
"i",
"]",
",",
"dr",
"[",
"i",
"]",
",",
"width",
"=",
"dphi",
"[",
"i",
"]",
",",
"bottom",
"=",
"rpos",
"[",
"i",
"]",
",",
"align",
"=",
"'edge'",
",",
"color",
"=",
"bin_color",
",",
"edgecolor",
"=",
"kwargs",
".",
"get",
"(",
"\"grid_color\"",
",",
"cmap",
"(",
"0.5",
")",
")",
",",
"lw",
"=",
"kwargs",
".",
"get",
"(",
"\"lw\"",
",",
"0.5",
")",
",",
"alpha",
"=",
"alphas",
"[",
"i",
"]",
",",
"*",
"*",
"bar_args",
")",
"ax",
".",
"set_rmax",
"(",
"rmax",
".",
"max",
"(",
")",
")",
"if",
"show_colorbar",
":",
"_add_colorbar",
"(",
"ax",
",",
"cmap",
",",
"cmap_data",
",",
"norm",
")"
] | Polar map of polar histograms.
Similar to map, but supports less parameters. | [
"Polar",
"map",
"of",
"polar",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L454-L487 | train |
janpipek/physt | physt/plotting/matplotlib.py | globe_map | def globe_map(hist: Union[Histogram2D, DirectionalHistogram], ax: Axes3D, *, show_zero: bool = True, **kwargs):
"""Heat map plotted on the surface of a sphere."""
data = get_data(hist, cumulative=False, flatten=False,
density=kwargs.pop("density", False))
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
lw = kwargs.pop("lw", 1)
r = 1
xs = r * np.outer(np.sin(hist.numpy_bins[0]), np.cos(hist.numpy_bins[1]))
ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.sin(hist.numpy_bins[1]))
zs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1))
for i in range(hist.shape[0]):
for j in range(hist.shape[1]):
if not show_zero and not data[i, j]:
continue
x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j]
y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j]
z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j]
verts = [list(zip(x, y, z))]
col = Poly3DCollection(verts)
col.set_facecolor(colors[i, j])
col.set_edgecolor("black")
col.set_linewidth(lw)
ax.add_collection3d(col)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
if matplotlib.__version__ < "2":
ax.plot_surface([], [], [], color="b")
ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-1.1, 1.1)
ax.set_zlim(-1.1, 1.1)
return ax | python | def globe_map(hist: Union[Histogram2D, DirectionalHistogram], ax: Axes3D, *, show_zero: bool = True, **kwargs):
"""Heat map plotted on the surface of a sphere."""
data = get_data(hist, cumulative=False, flatten=False,
density=kwargs.pop("density", False))
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
lw = kwargs.pop("lw", 1)
r = 1
xs = r * np.outer(np.sin(hist.numpy_bins[0]), np.cos(hist.numpy_bins[1]))
ys = r * np.outer(np.sin(hist.numpy_bins[0]), np.sin(hist.numpy_bins[1]))
zs = r * np.outer(np.cos(hist.numpy_bins[0]), np.ones(hist.shape[1] + 1))
for i in range(hist.shape[0]):
for j in range(hist.shape[1]):
if not show_zero and not data[i, j]:
continue
x = xs[i, j], xs[i, j + 1], xs[i + 1, j + 1], xs[i + 1, j]
y = ys[i, j], ys[i, j + 1], ys[i + 1, j + 1], ys[i + 1, j]
z = zs[i, j], zs[i, j + 1], zs[i + 1, j + 1], zs[i + 1, j]
verts = [list(zip(x, y, z))]
col = Poly3DCollection(verts)
col.set_facecolor(colors[i, j])
col.set_edgecolor("black")
col.set_linewidth(lw)
ax.add_collection3d(col)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
if matplotlib.__version__ < "2":
ax.plot_surface([], [], [], color="b")
ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-1.1, 1.1)
ax.set_zlim(-1.1, 1.1)
return ax | [
"def",
"globe_map",
"(",
"hist",
":",
"Union",
"[",
"Histogram2D",
",",
"DirectionalHistogram",
"]",
",",
"ax",
":",
"Axes3D",
",",
"*",
",",
"show_zero",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"get_data",
"(",
"hist",
",",
"cumulative",
"=",
"False",
",",
"flatten",
"=",
"False",
",",
"density",
"=",
"kwargs",
".",
"pop",
"(",
"\"density\"",
",",
"False",
")",
")",
"cmap",
"=",
"_get_cmap",
"(",
"kwargs",
")",
"norm",
",",
"cmap_data",
"=",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"colors",
"=",
"cmap",
"(",
"cmap_data",
")",
"lw",
"=",
"kwargs",
".",
"pop",
"(",
"\"lw\"",
",",
"1",
")",
"r",
"=",
"1",
"xs",
"=",
"r",
"*",
"np",
".",
"outer",
"(",
"np",
".",
"sin",
"(",
"hist",
".",
"numpy_bins",
"[",
"0",
"]",
")",
",",
"np",
".",
"cos",
"(",
"hist",
".",
"numpy_bins",
"[",
"1",
"]",
")",
")",
"ys",
"=",
"r",
"*",
"np",
".",
"outer",
"(",
"np",
".",
"sin",
"(",
"hist",
".",
"numpy_bins",
"[",
"0",
"]",
")",
",",
"np",
".",
"sin",
"(",
"hist",
".",
"numpy_bins",
"[",
"1",
"]",
")",
")",
"zs",
"=",
"r",
"*",
"np",
".",
"outer",
"(",
"np",
".",
"cos",
"(",
"hist",
".",
"numpy_bins",
"[",
"0",
"]",
")",
",",
"np",
".",
"ones",
"(",
"hist",
".",
"shape",
"[",
"1",
"]",
"+",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"hist",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"hist",
".",
"shape",
"[",
"1",
"]",
")",
":",
"if",
"not",
"show_zero",
"and",
"not",
"data",
"[",
"i",
",",
"j",
"]",
":",
"continue",
"x",
"=",
"xs",
"[",
"i",
",",
"j",
"]",
",",
"xs",
"[",
"i",
",",
"j",
"+",
"1",
"]",
",",
"xs",
"[",
"i",
"+",
"1",
",",
"j",
"+",
"1",
"]",
",",
"xs",
"[",
"i",
"+",
"1",
",",
"j",
"]",
"y",
"=",
"ys",
"[",
"i",
",",
"j",
"]",
",",
"ys",
"[",
"i",
",",
"j",
"+",
"1",
"]",
",",
"ys",
"[",
"i",
"+",
"1",
",",
"j",
"+",
"1",
"]",
",",
"ys",
"[",
"i",
"+",
"1",
",",
"j",
"]",
"z",
"=",
"zs",
"[",
"i",
",",
"j",
"]",
",",
"zs",
"[",
"i",
",",
"j",
"+",
"1",
"]",
",",
"zs",
"[",
"i",
"+",
"1",
",",
"j",
"+",
"1",
"]",
",",
"zs",
"[",
"i",
"+",
"1",
",",
"j",
"]",
"verts",
"=",
"[",
"list",
"(",
"zip",
"(",
"x",
",",
"y",
",",
"z",
")",
")",
"]",
"col",
"=",
"Poly3DCollection",
"(",
"verts",
")",
"col",
".",
"set_facecolor",
"(",
"colors",
"[",
"i",
",",
"j",
"]",
")",
"col",
".",
"set_edgecolor",
"(",
"\"black\"",
")",
"col",
".",
"set_linewidth",
"(",
"lw",
")",
"ax",
".",
"add_collection3d",
"(",
"col",
")",
"ax",
".",
"set_xlabel",
"(",
"\"x\"",
")",
"ax",
".",
"set_ylabel",
"(",
"\"y\"",
")",
"ax",
".",
"set_zlabel",
"(",
"\"z\"",
")",
"if",
"matplotlib",
".",
"__version__",
"<",
"\"2\"",
":",
"ax",
".",
"plot_surface",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"color",
"=",
"\"b\"",
")",
"ax",
".",
"set_xlim",
"(",
"-",
"1.1",
",",
"1.1",
")",
"ax",
".",
"set_ylim",
"(",
"-",
"1.1",
",",
"1.1",
")",
"ax",
".",
"set_zlim",
"(",
"-",
"1.1",
",",
"1.1",
")",
"return",
"ax"
] | Heat map plotted on the surface of a sphere. | [
"Heat",
"map",
"plotted",
"on",
"the",
"surface",
"of",
"a",
"sphere",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L491-L529 | train |
janpipek/physt | physt/plotting/matplotlib.py | pair_bars | def pair_bars(first: Histogram1D, second: Histogram2D, *, orientation: str = "vertical", kind: str = "bar", **kwargs):
"""Draw two different histograms mirrored in one figure.
Parameters
----------
first: Histogram1D
second: Histogram1D
color1:
color2:
orientation: str
Returns
-------
plt.Axes
"""
# TODO: enable vertical as well as horizontal
_, ax = _get_axes(kwargs)
color1 = kwargs.pop("color1", "red")
color2 = kwargs.pop("color2", "blue")
title = kwargs.pop("title", "{0} - {1}".format(first.name, second.name))
xlim = kwargs.pop("xlim", (min(first.bin_left_edges[0], first.bin_left_edges[
0]), max(first.bin_right_edges[-1], second.bin_right_edges[-1])))
bar(first * (-1), color=color1, ax=ax, ylim="keep", **kwargs)
bar(second, color=color2, ax=ax, ylim="keep", **kwargs)
ax.set_title(title)
ticks = np.abs(ax.get_yticks())
if np.allclose(np.rint(ticks), ticks):
ax.set_yticklabels(ticks.astype(int))
else:
ax.set_yticklabels(ticks)
ax.set_xlim(xlim)
ax.legend()
return ax | python | def pair_bars(first: Histogram1D, second: Histogram2D, *, orientation: str = "vertical", kind: str = "bar", **kwargs):
"""Draw two different histograms mirrored in one figure.
Parameters
----------
first: Histogram1D
second: Histogram1D
color1:
color2:
orientation: str
Returns
-------
plt.Axes
"""
# TODO: enable vertical as well as horizontal
_, ax = _get_axes(kwargs)
color1 = kwargs.pop("color1", "red")
color2 = kwargs.pop("color2", "blue")
title = kwargs.pop("title", "{0} - {1}".format(first.name, second.name))
xlim = kwargs.pop("xlim", (min(first.bin_left_edges[0], first.bin_left_edges[
0]), max(first.bin_right_edges[-1], second.bin_right_edges[-1])))
bar(first * (-1), color=color1, ax=ax, ylim="keep", **kwargs)
bar(second, color=color2, ax=ax, ylim="keep", **kwargs)
ax.set_title(title)
ticks = np.abs(ax.get_yticks())
if np.allclose(np.rint(ticks), ticks):
ax.set_yticklabels(ticks.astype(int))
else:
ax.set_yticklabels(ticks)
ax.set_xlim(xlim)
ax.legend()
return ax | [
"def",
"pair_bars",
"(",
"first",
":",
"Histogram1D",
",",
"second",
":",
"Histogram2D",
",",
"*",
",",
"orientation",
":",
"str",
"=",
"\"vertical\"",
",",
"kind",
":",
"str",
"=",
"\"bar\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: enable vertical as well as horizontal",
"_",
",",
"ax",
"=",
"_get_axes",
"(",
"kwargs",
")",
"color1",
"=",
"kwargs",
".",
"pop",
"(",
"\"color1\"",
",",
"\"red\"",
")",
"color2",
"=",
"kwargs",
".",
"pop",
"(",
"\"color2\"",
",",
"\"blue\"",
")",
"title",
"=",
"kwargs",
".",
"pop",
"(",
"\"title\"",
",",
"\"{0} - {1}\"",
".",
"format",
"(",
"first",
".",
"name",
",",
"second",
".",
"name",
")",
")",
"xlim",
"=",
"kwargs",
".",
"pop",
"(",
"\"xlim\"",
",",
"(",
"min",
"(",
"first",
".",
"bin_left_edges",
"[",
"0",
"]",
",",
"first",
".",
"bin_left_edges",
"[",
"0",
"]",
")",
",",
"max",
"(",
"first",
".",
"bin_right_edges",
"[",
"-",
"1",
"]",
",",
"second",
".",
"bin_right_edges",
"[",
"-",
"1",
"]",
")",
")",
")",
"bar",
"(",
"first",
"*",
"(",
"-",
"1",
")",
",",
"color",
"=",
"color1",
",",
"ax",
"=",
"ax",
",",
"ylim",
"=",
"\"keep\"",
",",
"*",
"*",
"kwargs",
")",
"bar",
"(",
"second",
",",
"color",
"=",
"color2",
",",
"ax",
"=",
"ax",
",",
"ylim",
"=",
"\"keep\"",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"set_title",
"(",
"title",
")",
"ticks",
"=",
"np",
".",
"abs",
"(",
"ax",
".",
"get_yticks",
"(",
")",
")",
"if",
"np",
".",
"allclose",
"(",
"np",
".",
"rint",
"(",
"ticks",
")",
",",
"ticks",
")",
":",
"ax",
".",
"set_yticklabels",
"(",
"ticks",
".",
"astype",
"(",
"int",
")",
")",
"else",
":",
"ax",
".",
"set_yticklabels",
"(",
"ticks",
")",
"ax",
".",
"set_xlim",
"(",
"xlim",
")",
"ax",
".",
"legend",
"(",
")",
"return",
"ax"
] | Draw two different histograms mirrored in one figure.
Parameters
----------
first: Histogram1D
second: Histogram1D
color1:
color2:
orientation: str
Returns
-------
plt.Axes | [
"Draw",
"two",
"different",
"histograms",
"mirrored",
"in",
"one",
"figure",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L648-L681 | train |
janpipek/physt | physt/plotting/matplotlib.py | _get_axes | def _get_axes(kwargs: Dict[str, Any], *, use_3d: bool = False, use_polar: bool = False) -> Tuple[Figure, Union[Axes, Axes3D]]:
"""Prepare the axis to draw into.
Parameters
----------
use_3d: If True, an axis with 3D projection is created.
use_polar: If True, the plot will have polar coordinates.
Kwargs
------
ax: Optional[plt.Axes]
An already existing axis to be used.
figsize: Optional[tuple]
Size of the new figure (if no axis is given).
Returns
------
fig : plt.Figure
ax : plt.Axes | Axes3D
"""
figsize = kwargs.pop("figsize", default_figsize)
if "ax" in kwargs:
ax = kwargs.pop("ax")
fig = ax.get_figure()
elif use_3d:
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
elif use_polar:
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='polar')
else:
fig, ax = plt.subplots(figsize=figsize)
return fig, ax | python | def _get_axes(kwargs: Dict[str, Any], *, use_3d: bool = False, use_polar: bool = False) -> Tuple[Figure, Union[Axes, Axes3D]]:
"""Prepare the axis to draw into.
Parameters
----------
use_3d: If True, an axis with 3D projection is created.
use_polar: If True, the plot will have polar coordinates.
Kwargs
------
ax: Optional[plt.Axes]
An already existing axis to be used.
figsize: Optional[tuple]
Size of the new figure (if no axis is given).
Returns
------
fig : plt.Figure
ax : plt.Axes | Axes3D
"""
figsize = kwargs.pop("figsize", default_figsize)
if "ax" in kwargs:
ax = kwargs.pop("ax")
fig = ax.get_figure()
elif use_3d:
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
elif use_polar:
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='polar')
else:
fig, ax = plt.subplots(figsize=figsize)
return fig, ax | [
"def",
"_get_axes",
"(",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"*",
",",
"use_3d",
":",
"bool",
"=",
"False",
",",
"use_polar",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"Figure",
",",
"Union",
"[",
"Axes",
",",
"Axes3D",
"]",
"]",
":",
"figsize",
"=",
"kwargs",
".",
"pop",
"(",
"\"figsize\"",
",",
"default_figsize",
")",
"if",
"\"ax\"",
"in",
"kwargs",
":",
"ax",
"=",
"kwargs",
".",
"pop",
"(",
"\"ax\"",
")",
"fig",
"=",
"ax",
".",
"get_figure",
"(",
")",
"elif",
"use_3d",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
",",
"projection",
"=",
"'3d'",
")",
"elif",
"use_polar",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
",",
"projection",
"=",
"'polar'",
")",
"else",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figsize",
")",
"return",
"fig",
",",
"ax"
] | Prepare the axis to draw into.
Parameters
----------
use_3d: If True, an axis with 3D projection is created.
use_polar: If True, the plot will have polar coordinates.
Kwargs
------
ax: Optional[plt.Axes]
An already existing axis to be used.
figsize: Optional[tuple]
Size of the new figure (if no axis is given).
Returns
------
fig : plt.Figure
ax : plt.Axes | Axes3D | [
"Prepare",
"the",
"axis",
"to",
"draw",
"into",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L684-L716 | train |
janpipek/physt | physt/plotting/matplotlib.py | _get_cmap | def _get_cmap(kwargs: dict) -> colors.Colormap:
"""Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed).
"""
from matplotlib.colors import ListedColormap
cmap = kwargs.pop("cmap", default_cmap)
if isinstance(cmap, list):
return ListedColormap(cmap)
if isinstance(cmap, str):
try:
cmap = plt.get_cmap(cmap)
except BaseException as exc:
try:
# Try to use seaborn palette
import seaborn as sns
sns_palette = sns.color_palette(cmap, n_colors=256)
cmap = ListedColormap(sns_palette, name=cmap)
except ImportError:
raise exc
return cmap | python | def _get_cmap(kwargs: dict) -> colors.Colormap:
"""Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed).
"""
from matplotlib.colors import ListedColormap
cmap = kwargs.pop("cmap", default_cmap)
if isinstance(cmap, list):
return ListedColormap(cmap)
if isinstance(cmap, str):
try:
cmap = plt.get_cmap(cmap)
except BaseException as exc:
try:
# Try to use seaborn palette
import seaborn as sns
sns_palette = sns.color_palette(cmap, n_colors=256)
cmap = ListedColormap(sns_palette, name=cmap)
except ImportError:
raise exc
return cmap | [
"def",
"_get_cmap",
"(",
"kwargs",
":",
"dict",
")",
"->",
"colors",
".",
"Colormap",
":",
"from",
"matplotlib",
".",
"colors",
"import",
"ListedColormap",
"cmap",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap\"",
",",
"default_cmap",
")",
"if",
"isinstance",
"(",
"cmap",
",",
"list",
")",
":",
"return",
"ListedColormap",
"(",
"cmap",
")",
"if",
"isinstance",
"(",
"cmap",
",",
"str",
")",
":",
"try",
":",
"cmap",
"=",
"plt",
".",
"get_cmap",
"(",
"cmap",
")",
"except",
"BaseException",
"as",
"exc",
":",
"try",
":",
"# Try to use seaborn palette",
"import",
"seaborn",
"as",
"sns",
"sns_palette",
"=",
"sns",
".",
"color_palette",
"(",
"cmap",
",",
"n_colors",
"=",
"256",
")",
"cmap",
"=",
"ListedColormap",
"(",
"sns_palette",
",",
"name",
"=",
"cmap",
")",
"except",
"ImportError",
":",
"raise",
"exc",
"return",
"cmap"
] | Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed). | [
"Get",
"the",
"colour",
"map",
"for",
"plots",
"that",
"support",
"it",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L719-L744 | train |
janpipek/physt | physt/plotting/matplotlib.py | _get_cmap_data | def _get_cmap_data(data, kwargs) -> Tuple[colors.Normalize, np.ndarray]:
"""Get normalized values to be used with a colormap.
Parameters
----------
data : array_like
cmap_min : Optional[float] or "min"
By default 0. If "min", minimum value of the data.
cmap_max : Optional[float]
By default, maximum value of the data
cmap_normalize : str or colors.Normalize
Returns
-------
normalizer : colors.Normalize
normalized_data : array_like
"""
norm = kwargs.pop("cmap_normalize", None)
if norm == "log":
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", data[data > 0].min())
norm = colors.LogNorm(cmap_min, cmap_max)
elif not norm:
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", 0)
if cmap_min == "min":
cmap_min = data.min()
norm = colors.Normalize(cmap_min, cmap_max, clip=True)
return norm, norm(data) | python | def _get_cmap_data(data, kwargs) -> Tuple[colors.Normalize, np.ndarray]:
"""Get normalized values to be used with a colormap.
Parameters
----------
data : array_like
cmap_min : Optional[float] or "min"
By default 0. If "min", minimum value of the data.
cmap_max : Optional[float]
By default, maximum value of the data
cmap_normalize : str or colors.Normalize
Returns
-------
normalizer : colors.Normalize
normalized_data : array_like
"""
norm = kwargs.pop("cmap_normalize", None)
if norm == "log":
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", data[data > 0].min())
norm = colors.LogNorm(cmap_min, cmap_max)
elif not norm:
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", 0)
if cmap_min == "min":
cmap_min = data.min()
norm = colors.Normalize(cmap_min, cmap_max, clip=True)
return norm, norm(data) | [
"def",
"_get_cmap_data",
"(",
"data",
",",
"kwargs",
")",
"->",
"Tuple",
"[",
"colors",
".",
"Normalize",
",",
"np",
".",
"ndarray",
"]",
":",
"norm",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap_normalize\"",
",",
"None",
")",
"if",
"norm",
"==",
"\"log\"",
":",
"cmap_max",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap_max\"",
",",
"data",
".",
"max",
"(",
")",
")",
"cmap_min",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap_min\"",
",",
"data",
"[",
"data",
">",
"0",
"]",
".",
"min",
"(",
")",
")",
"norm",
"=",
"colors",
".",
"LogNorm",
"(",
"cmap_min",
",",
"cmap_max",
")",
"elif",
"not",
"norm",
":",
"cmap_max",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap_max\"",
",",
"data",
".",
"max",
"(",
")",
")",
"cmap_min",
"=",
"kwargs",
".",
"pop",
"(",
"\"cmap_min\"",
",",
"0",
")",
"if",
"cmap_min",
"==",
"\"min\"",
":",
"cmap_min",
"=",
"data",
".",
"min",
"(",
")",
"norm",
"=",
"colors",
".",
"Normalize",
"(",
"cmap_min",
",",
"cmap_max",
",",
"clip",
"=",
"True",
")",
"return",
"norm",
",",
"norm",
"(",
"data",
")"
] | Get normalized values to be used with a colormap.
Parameters
----------
data : array_like
cmap_min : Optional[float] or "min"
By default 0. If "min", minimum value of the data.
cmap_max : Optional[float]
By default, maximum value of the data
cmap_normalize : str or colors.Normalize
Returns
-------
normalizer : colors.Normalize
normalized_data : array_like | [
"Get",
"normalized",
"values",
"to",
"be",
"used",
"with",
"a",
"colormap",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L747-L775 | train |
janpipek/physt | physt/plotting/matplotlib.py | _get_alpha_data | def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]:
"""Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data.
"""
alpha = kwargs.pop("alpha", 1)
if hasattr(alpha, "__call__"):
return np.vectorize(alpha)(data)
return alpha | python | def _get_alpha_data(data: np.ndarray, kwargs) -> Union[float, np.ndarray]:
"""Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data.
"""
alpha = kwargs.pop("alpha", 1)
if hasattr(alpha, "__call__"):
return np.vectorize(alpha)(data)
return alpha | [
"def",
"_get_alpha_data",
"(",
"data",
":",
"np",
".",
"ndarray",
",",
"kwargs",
")",
"->",
"Union",
"[",
"float",
",",
"np",
".",
"ndarray",
"]",
":",
"alpha",
"=",
"kwargs",
".",
"pop",
"(",
"\"alpha\"",
",",
"1",
")",
"if",
"hasattr",
"(",
"alpha",
",",
"\"__call__\"",
")",
":",
"return",
"np",
".",
"vectorize",
"(",
"alpha",
")",
"(",
"data",
")",
"return",
"alpha"
] | Get alpha values for all data points.
Parameters
----------
alpha: Callable or float
This can be a fixed value or a function of the data. | [
"Get",
"alpha",
"values",
"for",
"all",
"data",
"points",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L778-L789 | train |
janpipek/physt | physt/plotting/matplotlib.py | _add_values | def _add_values(ax: Axes, h1: Histogram1D, data, *, value_format=lambda x: x, **kwargs):
"""Show values next to each bin in a 1D plot.
Parameters
----------
ax : plt.Axes
h1 : physt.histogram1d.Histogram1D
data : array_like
The values to be displayed
kwargs : dict
Parameters to be passed to matplotlib to override standard text params.
"""
from .common import get_value_format
value_format = get_value_format(value_format)
text_kwargs = {"ha": "center", "va": "bottom", "clip_on" : True}
text_kwargs.update(kwargs)
for x, y in zip(h1.bin_centers, data):
ax.text(x, y, str(value_format(y)), **text_kwargs) | python | def _add_values(ax: Axes, h1: Histogram1D, data, *, value_format=lambda x: x, **kwargs):
"""Show values next to each bin in a 1D plot.
Parameters
----------
ax : plt.Axes
h1 : physt.histogram1d.Histogram1D
data : array_like
The values to be displayed
kwargs : dict
Parameters to be passed to matplotlib to override standard text params.
"""
from .common import get_value_format
value_format = get_value_format(value_format)
text_kwargs = {"ha": "center", "va": "bottom", "clip_on" : True}
text_kwargs.update(kwargs)
for x, y in zip(h1.bin_centers, data):
ax.text(x, y, str(value_format(y)), **text_kwargs) | [
"def",
"_add_values",
"(",
"ax",
":",
"Axes",
",",
"h1",
":",
"Histogram1D",
",",
"data",
",",
"*",
",",
"value_format",
"=",
"lambda",
"x",
":",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"common",
"import",
"get_value_format",
"value_format",
"=",
"get_value_format",
"(",
"value_format",
")",
"text_kwargs",
"=",
"{",
"\"ha\"",
":",
"\"center\"",
",",
"\"va\"",
":",
"\"bottom\"",
",",
"\"clip_on\"",
":",
"True",
"}",
"text_kwargs",
".",
"update",
"(",
"kwargs",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"h1",
".",
"bin_centers",
",",
"data",
")",
":",
"ax",
".",
"text",
"(",
"x",
",",
"y",
",",
"str",
"(",
"value_format",
"(",
"y",
")",
")",
",",
"*",
"*",
"text_kwargs",
")"
] | Show values next to each bin in a 1D plot.
Parameters
----------
ax : plt.Axes
h1 : physt.histogram1d.Histogram1D
data : array_like
The values to be displayed
kwargs : dict
Parameters to be passed to matplotlib to override standard text params. | [
"Show",
"values",
"next",
"to",
"each",
"bin",
"in",
"a",
"1D",
"plot",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L810-L828 | train |
janpipek/physt | physt/plotting/matplotlib.py | _add_colorbar | def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize):
"""Show a colorbar right of the plot."""
fig = ax.get_figure()
mappable = cm.ScalarMappable(cmap=cmap, norm=norm)
mappable.set_array(cmap_data) # TODO: Or what???
fig.colorbar(mappable, ax=ax) | python | def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize):
"""Show a colorbar right of the plot."""
fig = ax.get_figure()
mappable = cm.ScalarMappable(cmap=cmap, norm=norm)
mappable.set_array(cmap_data) # TODO: Or what???
fig.colorbar(mappable, ax=ax) | [
"def",
"_add_colorbar",
"(",
"ax",
":",
"Axes",
",",
"cmap",
":",
"colors",
".",
"Colormap",
",",
"cmap_data",
":",
"np",
".",
"ndarray",
",",
"norm",
":",
"colors",
".",
"Normalize",
")",
":",
"fig",
"=",
"ax",
".",
"get_figure",
"(",
")",
"mappable",
"=",
"cm",
".",
"ScalarMappable",
"(",
"cmap",
"=",
"cmap",
",",
"norm",
"=",
"norm",
")",
"mappable",
".",
"set_array",
"(",
"cmap_data",
")",
"# TODO: Or what???",
"fig",
".",
"colorbar",
"(",
"mappable",
",",
"ax",
"=",
"ax",
")"
] | Show a colorbar right of the plot. | [
"Show",
"a",
"colorbar",
"right",
"of",
"the",
"plot",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L831-L836 | train |
janpipek/physt | physt/plotting/matplotlib.py | _add_stats_box | def _add_stats_box(h1: Histogram1D, ax: Axes, stats: Union[str, bool] = "all"):
"""Insert a small legend-like box with statistical information.
Parameters
----------
stats : "all" | "total" | True
What info to display
Note
----
Very basic implementation.
"""
# place a text box in upper left in axes coords
if stats in ["all", True]:
text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}".format(
h1.total, h1.mean(), h1.std())
elif stats == "total":
text = "Total: {0}".format(h1.total)
else:
raise ValueError("Invalid stats specification")
ax.text(0.05, 0.95, text, transform=ax.transAxes,
verticalalignment='top', horizontalalignment='left') | python | def _add_stats_box(h1: Histogram1D, ax: Axes, stats: Union[str, bool] = "all"):
"""Insert a small legend-like box with statistical information.
Parameters
----------
stats : "all" | "total" | True
What info to display
Note
----
Very basic implementation.
"""
# place a text box in upper left in axes coords
if stats in ["all", True]:
text = "Total: {0}\nMean: {1:.2f}\nStd.dev: {2:.2f}".format(
h1.total, h1.mean(), h1.std())
elif stats == "total":
text = "Total: {0}".format(h1.total)
else:
raise ValueError("Invalid stats specification")
ax.text(0.05, 0.95, text, transform=ax.transAxes,
verticalalignment='top', horizontalalignment='left') | [
"def",
"_add_stats_box",
"(",
"h1",
":",
"Histogram1D",
",",
"ax",
":",
"Axes",
",",
"stats",
":",
"Union",
"[",
"str",
",",
"bool",
"]",
"=",
"\"all\"",
")",
":",
"# place a text box in upper left in axes coords",
"if",
"stats",
"in",
"[",
"\"all\"",
",",
"True",
"]",
":",
"text",
"=",
"\"Total: {0}\\nMean: {1:.2f}\\nStd.dev: {2:.2f}\"",
".",
"format",
"(",
"h1",
".",
"total",
",",
"h1",
".",
"mean",
"(",
")",
",",
"h1",
".",
"std",
"(",
")",
")",
"elif",
"stats",
"==",
"\"total\"",
":",
"text",
"=",
"\"Total: {0}\"",
".",
"format",
"(",
"h1",
".",
"total",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid stats specification\"",
")",
"ax",
".",
"text",
"(",
"0.05",
",",
"0.95",
",",
"text",
",",
"transform",
"=",
"ax",
".",
"transAxes",
",",
"verticalalignment",
"=",
"'top'",
",",
"horizontalalignment",
"=",
"'left'",
")"
] | Insert a small legend-like box with statistical information.
Parameters
----------
stats : "all" | "total" | True
What info to display
Note
----
Very basic implementation. | [
"Insert",
"a",
"small",
"legend",
"-",
"like",
"box",
"with",
"statistical",
"information",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L839-L862 | train |
janpipek/physt | physt/examples/__init__.py | normal_h1 | def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D:
"""A simple 1D histogram with normal distribution.
Parameters
----------
size : Number of points
mean : Mean of the distribution
sigma : Sigma of the distribution
"""
data = np.random.normal(mean, sigma, (size,))
return h1(data, name="normal", axis_name="x", title="1D normal distribution") | python | def normal_h1(size: int = 10000, mean: float = 0, sigma: float = 1) -> Histogram1D:
"""A simple 1D histogram with normal distribution.
Parameters
----------
size : Number of points
mean : Mean of the distribution
sigma : Sigma of the distribution
"""
data = np.random.normal(mean, sigma, (size,))
return h1(data, name="normal", axis_name="x", title="1D normal distribution") | [
"def",
"normal_h1",
"(",
"size",
":",
"int",
"=",
"10000",
",",
"mean",
":",
"float",
"=",
"0",
",",
"sigma",
":",
"float",
"=",
"1",
")",
"->",
"Histogram1D",
":",
"data",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"mean",
",",
"sigma",
",",
"(",
"size",
",",
")",
")",
"return",
"h1",
"(",
"data",
",",
"name",
"=",
"\"normal\"",
",",
"axis_name",
"=",
"\"x\"",
",",
"title",
"=",
"\"1D normal distribution\"",
")"
] | A simple 1D histogram with normal distribution.
Parameters
----------
size : Number of points
mean : Mean of the distribution
sigma : Sigma of the distribution | [
"A",
"simple",
"1D",
"histogram",
"with",
"normal",
"distribution",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L12-L22 | train |
janpipek/physt | physt/examples/__init__.py | normal_h2 | def normal_h2(size: int = 10000) -> Histogram2D:
"""A simple 2D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
return h2(data1, data2, name="normal", axis_names=tuple("xy"), title="2D normal distribution") | python | def normal_h2(size: int = 10000) -> Histogram2D:
"""A simple 2D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
return h2(data1, data2, name="normal", axis_names=tuple("xy"), title="2D normal distribution") | [
"def",
"normal_h2",
"(",
"size",
":",
"int",
"=",
"10000",
")",
"->",
"Histogram2D",
":",
"data1",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"data2",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"return",
"h2",
"(",
"data1",
",",
"data2",
",",
"name",
"=",
"\"normal\"",
",",
"axis_names",
"=",
"tuple",
"(",
"\"xy\"",
")",
",",
"title",
"=",
"\"2D normal distribution\"",
")"
] | A simple 2D histogram with normal distribution.
Parameters
----------
size : Number of points | [
"A",
"simple",
"2D",
"histogram",
"with",
"normal",
"distribution",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L25-L34 | train |
janpipek/physt | physt/examples/__init__.py | normal_h3 | def normal_h3(size: int = 10000) -> HistogramND:
"""A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
data3 = np.random.normal(0, 1, (size,))
return h3([data1, data2, data3], name="normal", axis_names=tuple("xyz"), title="3D normal distribution") | python | def normal_h3(size: int = 10000) -> HistogramND:
"""A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
data3 = np.random.normal(0, 1, (size,))
return h3([data1, data2, data3], name="normal", axis_names=tuple("xyz"), title="3D normal distribution") | [
"def",
"normal_h3",
"(",
"size",
":",
"int",
"=",
"10000",
")",
"->",
"HistogramND",
":",
"data1",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"data2",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"data3",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"return",
"h3",
"(",
"[",
"data1",
",",
"data2",
",",
"data3",
"]",
",",
"name",
"=",
"\"normal\"",
",",
"axis_names",
"=",
"tuple",
"(",
"\"xyz\"",
")",
",",
"title",
"=",
"\"3D normal distribution\"",
")"
] | A simple 3D histogram with normal distribution.
Parameters
----------
size : Number of points | [
"A",
"simple",
"3D",
"histogram",
"with",
"normal",
"distribution",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L37-L47 | train |
janpipek/physt | physt/examples/__init__.py | fist | def fist() -> Histogram1D:
"""A simple histogram in the shape of a fist."""
import numpy as np
from ..histogram1d import Histogram1D
widths = [0, 1.2, 0.2, 1, 0.1, 1, 0.1, 0.9, 0.1, 0.8]
edges = np.cumsum(widths)
heights = np.asarray([4, 1, 7.5, 6, 7.6, 6, 7.5, 6, 7.2]) + 5
return Histogram1D(edges, heights, axis_name="Is this a fist?", title="Physt \"logo\"") | python | def fist() -> Histogram1D:
"""A simple histogram in the shape of a fist."""
import numpy as np
from ..histogram1d import Histogram1D
widths = [0, 1.2, 0.2, 1, 0.1, 1, 0.1, 0.9, 0.1, 0.8]
edges = np.cumsum(widths)
heights = np.asarray([4, 1, 7.5, 6, 7.6, 6, 7.5, 6, 7.2]) + 5
return Histogram1D(edges, heights, axis_name="Is this a fist?", title="Physt \"logo\"") | [
"def",
"fist",
"(",
")",
"->",
"Histogram1D",
":",
"import",
"numpy",
"as",
"np",
"from",
".",
".",
"histogram1d",
"import",
"Histogram1D",
"widths",
"=",
"[",
"0",
",",
"1.2",
",",
"0.2",
",",
"1",
",",
"0.1",
",",
"1",
",",
"0.1",
",",
"0.9",
",",
"0.1",
",",
"0.8",
"]",
"edges",
"=",
"np",
".",
"cumsum",
"(",
"widths",
")",
"heights",
"=",
"np",
".",
"asarray",
"(",
"[",
"4",
",",
"1",
",",
"7.5",
",",
"6",
",",
"7.6",
",",
"6",
",",
"7.5",
",",
"6",
",",
"7.2",
"]",
")",
"+",
"5",
"return",
"Histogram1D",
"(",
"edges",
",",
"heights",
",",
"axis_name",
"=",
"\"Is this a fist?\"",
",",
"title",
"=",
"\"Physt \\\"logo\\\"\"",
")"
] | A simple histogram in the shape of a fist. | [
"A",
"simple",
"histogram",
"in",
"the",
"shape",
"of",
"a",
"fist",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L50-L57 | train |
janpipek/physt | physt/io/__init__.py | require_compatible_version | def require_compatible_version(compatible_version, word="File"):
"""Check that compatible version of input data is not too new."""
if isinstance(compatible_version, str):
compatible_version = parse_version(compatible_version)
elif not isinstance(compatible_version, Version):
raise ValueError("Type of `compatible_version` not understood.")
current_version = parse_version(CURRENT_VERSION)
if current_version < compatible_version:
raise VersionError("{0} written for version >= {1}, this is {2}.".format(
word, str(compatible_version), CURRENT_VERSION
)) | python | def require_compatible_version(compatible_version, word="File"):
"""Check that compatible version of input data is not too new."""
if isinstance(compatible_version, str):
compatible_version = parse_version(compatible_version)
elif not isinstance(compatible_version, Version):
raise ValueError("Type of `compatible_version` not understood.")
current_version = parse_version(CURRENT_VERSION)
if current_version < compatible_version:
raise VersionError("{0} written for version >= {1}, this is {2}.".format(
word, str(compatible_version), CURRENT_VERSION
)) | [
"def",
"require_compatible_version",
"(",
"compatible_version",
",",
"word",
"=",
"\"File\"",
")",
":",
"if",
"isinstance",
"(",
"compatible_version",
",",
"str",
")",
":",
"compatible_version",
"=",
"parse_version",
"(",
"compatible_version",
")",
"elif",
"not",
"isinstance",
"(",
"compatible_version",
",",
"Version",
")",
":",
"raise",
"ValueError",
"(",
"\"Type of `compatible_version` not understood.\"",
")",
"current_version",
"=",
"parse_version",
"(",
"CURRENT_VERSION",
")",
"if",
"current_version",
"<",
"compatible_version",
":",
"raise",
"VersionError",
"(",
"\"{0} written for version >= {1}, this is {2}.\"",
".",
"format",
"(",
"word",
",",
"str",
"(",
"compatible_version",
")",
",",
"CURRENT_VERSION",
")",
")"
] | Check that compatible version of input data is not too new. | [
"Check",
"that",
"compatible",
"version",
"of",
"input",
"data",
"is",
"not",
"too",
"new",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/__init__.py#L52-L63 | train |
janpipek/physt | physt/io/json.py | save_json | def save_json(histogram: Union[HistogramBase, HistogramCollection], path: Optional[str] = None, **kwargs) -> str:
"""Save histogram to JSON format.
Parameters
----------
histogram : Any histogram
path : If set, also writes to the path.
Returns
-------
json : The JSON representation of the histogram
"""
# TODO: Implement multiple histograms in one file?
data = histogram.to_dict()
data["physt_version"] = CURRENT_VERSION
if isinstance(histogram, HistogramBase):
data["physt_compatible"] = COMPATIBLE_VERSION
elif isinstance(histogram, HistogramCollection):
data["physt_compatible"] = COLLECTION_COMPATIBLE_VERSION
else:
raise TypeError("Cannot save unknown type: {0}".format(type(histogram)))
text = json.dumps(data, **kwargs)
if path:
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return text | python | def save_json(histogram: Union[HistogramBase, HistogramCollection], path: Optional[str] = None, **kwargs) -> str:
"""Save histogram to JSON format.
Parameters
----------
histogram : Any histogram
path : If set, also writes to the path.
Returns
-------
json : The JSON representation of the histogram
"""
# TODO: Implement multiple histograms in one file?
data = histogram.to_dict()
data["physt_version"] = CURRENT_VERSION
if isinstance(histogram, HistogramBase):
data["physt_compatible"] = COMPATIBLE_VERSION
elif isinstance(histogram, HistogramCollection):
data["physt_compatible"] = COLLECTION_COMPATIBLE_VERSION
else:
raise TypeError("Cannot save unknown type: {0}".format(type(histogram)))
text = json.dumps(data, **kwargs)
if path:
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return text | [
"def",
"save_json",
"(",
"histogram",
":",
"Union",
"[",
"HistogramBase",
",",
"HistogramCollection",
"]",
",",
"path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"# TODO: Implement multiple histograms in one file?",
"data",
"=",
"histogram",
".",
"to_dict",
"(",
")",
"data",
"[",
"\"physt_version\"",
"]",
"=",
"CURRENT_VERSION",
"if",
"isinstance",
"(",
"histogram",
",",
"HistogramBase",
")",
":",
"data",
"[",
"\"physt_compatible\"",
"]",
"=",
"COMPATIBLE_VERSION",
"elif",
"isinstance",
"(",
"histogram",
",",
"HistogramCollection",
")",
":",
"data",
"[",
"\"physt_compatible\"",
"]",
"=",
"COLLECTION_COMPATIBLE_VERSION",
"else",
":",
"raise",
"TypeError",
"(",
"\"Cannot save unknown type: {0}\"",
".",
"format",
"(",
"type",
"(",
"histogram",
")",
")",
")",
"text",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
"if",
"path",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"text",
")",
"return",
"text"
] | Save histogram to JSON format.
Parameters
----------
histogram : Any histogram
path : If set, also writes to the path.
Returns
-------
json : The JSON representation of the histogram | [
"Save",
"histogram",
"to",
"JSON",
"format",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L13-L40 | train |
janpipek/physt | physt/io/json.py | load_json | def load_json(path: str, encoding: str = "utf-8") -> HistogramBase:
"""Load histogram from a JSON file."""
with open(path, "r", encoding=encoding) as f:
text = f.read()
return parse_json(text) | python | def load_json(path: str, encoding: str = "utf-8") -> HistogramBase:
"""Load histogram from a JSON file."""
with open(path, "r", encoding=encoding) as f:
text = f.read()
return parse_json(text) | [
"def",
"load_json",
"(",
"path",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
")",
"->",
"HistogramBase",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"return",
"parse_json",
"(",
"text",
")"
] | Load histogram from a JSON file. | [
"Load",
"histogram",
"from",
"a",
"JSON",
"file",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L43-L47 | train |
janpipek/physt | physt/io/json.py | parse_json | def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase:
"""Create histogram from a JSON string."""
data = json.loads(text, encoding=encoding)
return create_from_dict(data, format_name="JSON") | python | def parse_json(text: str, encoding: str = "utf-8") -> HistogramBase:
"""Create histogram from a JSON string."""
data = json.loads(text, encoding=encoding)
return create_from_dict(data, format_name="JSON") | [
"def",
"parse_json",
"(",
"text",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"\"utf-8\"",
")",
"->",
"HistogramBase",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"text",
",",
"encoding",
"=",
"encoding",
")",
"return",
"create_from_dict",
"(",
"data",
",",
"format_name",
"=",
"\"JSON\"",
")"
] | Create histogram from a JSON string. | [
"Create",
"histogram",
"from",
"a",
"JSON",
"string",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/json.py#L50-L53 | train |
janpipek/physt | physt/__init__.py | histogram | def histogram(data, bins=None, *args, **kwargs):
"""Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* parameters understood by numpy.histogram should be
understood also by physt.histogram as well and should result in a Histogram1D
object with (h.numpy_bins, h.frequencies) same as the numpy.histogram
output. Additional functionality is a bonus.
This function is also aliased as "h1".
Parameters
----------
data : array_like, optional
Container of all the values (tuple, list, np.ndarray, pd.Series)
bins: int or sequence of scalars or callable or str, optional
If iterable => the bins themselves
If int => number of bins for default binning
If callable => use binning method (+ args, kwargs)
If string => use named binning method (+ args, kwargs)
weights: array_like, optional
(as numpy.histogram)
keep_missed: Optional[bool]
store statistics about how many values were lower than limits
and how many higher than limits (default: True)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_name: str
name of the variable on x axis
adaptive: bool
whether we want the bins to be modifiable
(useful for continuous filling of a priori unknown data)
dtype: type
customize underlying data type: default int64 (without weight) or float (with weights)
Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself.
Returns
-------
physt.histogram1d.Histogram1D
See Also
--------
numpy.histogram
"""
import numpy as np
from .histogram1d import Histogram1D, calculate_frequencies
from .binnings import calculate_bins
adaptive = kwargs.pop("adaptive", False)
dtype = kwargs.pop("dtype", None)
if isinstance(data, tuple) and isinstance(data[0], str): # Works for groupby DataSeries
return histogram(data[1], bins, *args, name=data[0], **kwargs)
elif type(data).__name__ == "DataFrame":
raise RuntimeError("Cannot create histogram from a pandas DataFrame. Use Series.")
# Collect arguments (not to send them to binning algorithms)
dropna = kwargs.pop("dropna", True)
weights = kwargs.pop("weights", None)
keep_missed = kwargs.pop("keep_missed", True)
name = kwargs.pop("name", None)
axis_name = kwargs.pop("axis_name", None)
title = kwargs.pop("title", None)
# Convert to array
if data is not None:
array = np.asarray(data) #.flatten()
if dropna:
array = array[~np.isnan(array)]
else:
array = None
# Get binning
binning = calculate_bins(array, bins, *args,
check_nan=not dropna and array is not None,
adaptive=adaptive, **kwargs)
# bins = binning.bins
# Get frequencies
if array is not None:
(frequencies, errors2, underflow, overflow, stats) =\
calculate_frequencies(array, binning=binning,
weights=weights, dtype=dtype)
else:
frequencies = None
errors2 = None
underflow = 0
overflow = 0
stats = {"sum": 0.0, "sum2": 0.0}
# Construct the object
if not keep_missed:
underflow = 0
overflow = 0
if not axis_name:
if hasattr(data, "name"):
axis_name = data.name
elif hasattr(data, "fields") and len(data.fields) == 1 and isinstance(data.fields[0], str):
# Case of dask fields (examples)
axis_name = data.fields[0]
return Histogram1D(binning=binning, frequencies=frequencies,
errors2=errors2, overflow=overflow,
underflow=underflow, stats=stats, dtype=dtype,
keep_missed=keep_missed, name=name, axis_name=axis_name,
title=title) | python | def histogram(data, bins=None, *args, **kwargs):
"""Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* parameters understood by numpy.histogram should be
understood also by physt.histogram as well and should result in a Histogram1D
object with (h.numpy_bins, h.frequencies) same as the numpy.histogram
output. Additional functionality is a bonus.
This function is also aliased as "h1".
Parameters
----------
data : array_like, optional
Container of all the values (tuple, list, np.ndarray, pd.Series)
bins: int or sequence of scalars or callable or str, optional
If iterable => the bins themselves
If int => number of bins for default binning
If callable => use binning method (+ args, kwargs)
If string => use named binning method (+ args, kwargs)
weights: array_like, optional
(as numpy.histogram)
keep_missed: Optional[bool]
store statistics about how many values were lower than limits
and how many higher than limits (default: True)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_name: str
name of the variable on x axis
adaptive: bool
whether we want the bins to be modifiable
(useful for continuous filling of a priori unknown data)
dtype: type
customize underlying data type: default int64 (without weight) or float (with weights)
Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself.
Returns
-------
physt.histogram1d.Histogram1D
See Also
--------
numpy.histogram
"""
import numpy as np
from .histogram1d import Histogram1D, calculate_frequencies
from .binnings import calculate_bins
adaptive = kwargs.pop("adaptive", False)
dtype = kwargs.pop("dtype", None)
if isinstance(data, tuple) and isinstance(data[0], str): # Works for groupby DataSeries
return histogram(data[1], bins, *args, name=data[0], **kwargs)
elif type(data).__name__ == "DataFrame":
raise RuntimeError("Cannot create histogram from a pandas DataFrame. Use Series.")
# Collect arguments (not to send them to binning algorithms)
dropna = kwargs.pop("dropna", True)
weights = kwargs.pop("weights", None)
keep_missed = kwargs.pop("keep_missed", True)
name = kwargs.pop("name", None)
axis_name = kwargs.pop("axis_name", None)
title = kwargs.pop("title", None)
# Convert to array
if data is not None:
array = np.asarray(data) #.flatten()
if dropna:
array = array[~np.isnan(array)]
else:
array = None
# Get binning
binning = calculate_bins(array, bins, *args,
check_nan=not dropna and array is not None,
adaptive=adaptive, **kwargs)
# bins = binning.bins
# Get frequencies
if array is not None:
(frequencies, errors2, underflow, overflow, stats) =\
calculate_frequencies(array, binning=binning,
weights=weights, dtype=dtype)
else:
frequencies = None
errors2 = None
underflow = 0
overflow = 0
stats = {"sum": 0.0, "sum2": 0.0}
# Construct the object
if not keep_missed:
underflow = 0
overflow = 0
if not axis_name:
if hasattr(data, "name"):
axis_name = data.name
elif hasattr(data, "fields") and len(data.fields) == 1 and isinstance(data.fields[0], str):
# Case of dask fields (examples)
axis_name = data.fields[0]
return Histogram1D(binning=binning, frequencies=frequencies,
errors2=errors2, overflow=overflow,
underflow=underflow, stats=stats, dtype=dtype,
keep_missed=keep_missed, name=name, axis_name=axis_name,
title=title) | [
"def",
"histogram",
"(",
"data",
",",
"bins",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"numpy",
"as",
"np",
"from",
".",
"histogram1d",
"import",
"Histogram1D",
",",
"calculate_frequencies",
"from",
".",
"binnings",
"import",
"calculate_bins",
"adaptive",
"=",
"kwargs",
".",
"pop",
"(",
"\"adaptive\"",
",",
"False",
")",
"dtype",
"=",
"kwargs",
".",
"pop",
"(",
"\"dtype\"",
",",
"None",
")",
"if",
"isinstance",
"(",
"data",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"data",
"[",
"0",
"]",
",",
"str",
")",
":",
"# Works for groupby DataSeries",
"return",
"histogram",
"(",
"data",
"[",
"1",
"]",
",",
"bins",
",",
"*",
"args",
",",
"name",
"=",
"data",
"[",
"0",
"]",
",",
"*",
"*",
"kwargs",
")",
"elif",
"type",
"(",
"data",
")",
".",
"__name__",
"==",
"\"DataFrame\"",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot create histogram from a pandas DataFrame. Use Series.\"",
")",
"# Collect arguments (not to send them to binning algorithms)",
"dropna",
"=",
"kwargs",
".",
"pop",
"(",
"\"dropna\"",
",",
"True",
")",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"\"weights\"",
",",
"None",
")",
"keep_missed",
"=",
"kwargs",
".",
"pop",
"(",
"\"keep_missed\"",
",",
"True",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"\"name\"",
",",
"None",
")",
"axis_name",
"=",
"kwargs",
".",
"pop",
"(",
"\"axis_name\"",
",",
"None",
")",
"title",
"=",
"kwargs",
".",
"pop",
"(",
"\"title\"",
",",
"None",
")",
"# Convert to array",
"if",
"data",
"is",
"not",
"None",
":",
"array",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"#.flatten()",
"if",
"dropna",
":",
"array",
"=",
"array",
"[",
"~",
"np",
".",
"isnan",
"(",
"array",
")",
"]",
"else",
":",
"array",
"=",
"None",
"# Get binning",
"binning",
"=",
"calculate_bins",
"(",
"array",
",",
"bins",
",",
"*",
"args",
",",
"check_nan",
"=",
"not",
"dropna",
"and",
"array",
"is",
"not",
"None",
",",
"adaptive",
"=",
"adaptive",
",",
"*",
"*",
"kwargs",
")",
"# bins = binning.bins",
"# Get frequencies",
"if",
"array",
"is",
"not",
"None",
":",
"(",
"frequencies",
",",
"errors2",
",",
"underflow",
",",
"overflow",
",",
"stats",
")",
"=",
"calculate_frequencies",
"(",
"array",
",",
"binning",
"=",
"binning",
",",
"weights",
"=",
"weights",
",",
"dtype",
"=",
"dtype",
")",
"else",
":",
"frequencies",
"=",
"None",
"errors2",
"=",
"None",
"underflow",
"=",
"0",
"overflow",
"=",
"0",
"stats",
"=",
"{",
"\"sum\"",
":",
"0.0",
",",
"\"sum2\"",
":",
"0.0",
"}",
"# Construct the object",
"if",
"not",
"keep_missed",
":",
"underflow",
"=",
"0",
"overflow",
"=",
"0",
"if",
"not",
"axis_name",
":",
"if",
"hasattr",
"(",
"data",
",",
"\"name\"",
")",
":",
"axis_name",
"=",
"data",
".",
"name",
"elif",
"hasattr",
"(",
"data",
",",
"\"fields\"",
")",
"and",
"len",
"(",
"data",
".",
"fields",
")",
"==",
"1",
"and",
"isinstance",
"(",
"data",
".",
"fields",
"[",
"0",
"]",
",",
"str",
")",
":",
"# Case of dask fields (examples)",
"axis_name",
"=",
"data",
".",
"fields",
"[",
"0",
"]",
"return",
"Histogram1D",
"(",
"binning",
"=",
"binning",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"overflow",
"=",
"overflow",
",",
"underflow",
"=",
"underflow",
",",
"stats",
"=",
"stats",
",",
"dtype",
"=",
"dtype",
",",
"keep_missed",
"=",
"keep_missed",
",",
"name",
"=",
"name",
",",
"axis_name",
"=",
"axis_name",
",",
"title",
"=",
"title",
")"
] | Facade function to create 1D histograms.
This proceeds in three steps:
1) Based on magical parameter bins, construct bins for the histogram
2) Calculate frequencies for the bins
3) Construct the histogram object itself
*Guiding principle:* parameters understood by numpy.histogram should be
understood also by physt.histogram as well and should result in a Histogram1D
object with (h.numpy_bins, h.frequencies) same as the numpy.histogram
output. Additional functionality is a bonus.
This function is also aliased as "h1".
Parameters
----------
data : array_like, optional
Container of all the values (tuple, list, np.ndarray, pd.Series)
bins: int or sequence of scalars or callable or str, optional
If iterable => the bins themselves
If int => number of bins for default binning
If callable => use binning method (+ args, kwargs)
If string => use named binning method (+ args, kwargs)
weights: array_like, optional
(as numpy.histogram)
keep_missed: Optional[bool]
store statistics about how many values were lower than limits
and how many higher than limits (default: True)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_name: str
name of the variable on x axis
adaptive: bool
whether we want the bins to be modifiable
(useful for continuous filling of a priori unknown data)
dtype: type
customize underlying data type: default int64 (without weight) or float (with weights)
Other numpy.histogram parameters are excluded, see the methods of the Histogram1D class itself.
Returns
-------
physt.histogram1d.Histogram1D
See Also
--------
numpy.histogram | [
"Facade",
"function",
"to",
"create",
"1D",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L16-L127 | train |
janpipek/physt | physt/__init__.py | histogram2d | def histogram2d(data1, data2, bins=10, *args, **kwargs):
"""Facade function to create 2D histograms.
For implementation and parameters, see histogramdd.
This function is also aliased as "h2".
Returns
-------
physt.histogram_nd.Histogram2D
See Also
--------
numpy.histogram2d
histogramdd
"""
import numpy as np
# guess axis names
if "axis_names" not in kwargs:
if hasattr(data1, "name") and hasattr(data2, "name"):
kwargs["axis_names"] = [data1.name, data2.name]
if data1 is not None and data2 is not None:
data1 = np.asarray(data1)
data2 = np.asarray(data2)
data = np.concatenate([data1[:, np.newaxis],
data2[:, np.newaxis]], axis=1)
else:
data = None
return histogramdd(data, bins, *args, dim=2, **kwargs) | python | def histogram2d(data1, data2, bins=10, *args, **kwargs):
"""Facade function to create 2D histograms.
For implementation and parameters, see histogramdd.
This function is also aliased as "h2".
Returns
-------
physt.histogram_nd.Histogram2D
See Also
--------
numpy.histogram2d
histogramdd
"""
import numpy as np
# guess axis names
if "axis_names" not in kwargs:
if hasattr(data1, "name") and hasattr(data2, "name"):
kwargs["axis_names"] = [data1.name, data2.name]
if data1 is not None and data2 is not None:
data1 = np.asarray(data1)
data2 = np.asarray(data2)
data = np.concatenate([data1[:, np.newaxis],
data2[:, np.newaxis]], axis=1)
else:
data = None
return histogramdd(data, bins, *args, dim=2, **kwargs) | [
"def",
"histogram2d",
"(",
"data1",
",",
"data2",
",",
"bins",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"numpy",
"as",
"np",
"# guess axis names",
"if",
"\"axis_names\"",
"not",
"in",
"kwargs",
":",
"if",
"hasattr",
"(",
"data1",
",",
"\"name\"",
")",
"and",
"hasattr",
"(",
"data2",
",",
"\"name\"",
")",
":",
"kwargs",
"[",
"\"axis_names\"",
"]",
"=",
"[",
"data1",
".",
"name",
",",
"data2",
".",
"name",
"]",
"if",
"data1",
"is",
"not",
"None",
"and",
"data2",
"is",
"not",
"None",
":",
"data1",
"=",
"np",
".",
"asarray",
"(",
"data1",
")",
"data2",
"=",
"np",
".",
"asarray",
"(",
"data2",
")",
"data",
"=",
"np",
".",
"concatenate",
"(",
"[",
"data1",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"data2",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"]",
",",
"axis",
"=",
"1",
")",
"else",
":",
"data",
"=",
"None",
"return",
"histogramdd",
"(",
"data",
",",
"bins",
",",
"*",
"args",
",",
"dim",
"=",
"2",
",",
"*",
"*",
"kwargs",
")"
] | Facade function to create 2D histograms.
For implementation and parameters, see histogramdd.
This function is also aliased as "h2".
Returns
-------
physt.histogram_nd.Histogram2D
See Also
--------
numpy.histogram2d
histogramdd | [
"Facade",
"function",
"to",
"create",
"2D",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L130-L159 | train |
janpipek/physt | physt/__init__.py | histogramdd | def histogramdd(data, bins=10, *args, **kwargs):
"""Facade function to create n-dimensional histograms.
3D variant of this function is also aliased as "h3".
Parameters
----------
data : array_like
Container of all the values
bins: Any
weights: array_like, optional
(as numpy.histogram)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_names: Iterable[str]
names of the variable on x axis
adaptive:
whether the bins should be updated when new non-fitting value are filled
dtype: Optional[type]
Underlying type for the histogram.
If weights are specified, default is float. Otherwise int64
dim: int
Dimension - necessary if you are creating an empty adaptive histogram
Returns
-------
physt.histogram_nd.HistogramND
See Also
--------
numpy.histogramdd
"""
import numpy as np
from . import histogram_nd
from .binnings import calculate_bins_nd
adaptive = kwargs.pop("adaptive", False)
dropna = kwargs.pop("dropna", True)
name = kwargs.pop("name", None)
title = kwargs.pop("title", None)
dim = kwargs.pop("dim", None)
axis_names = kwargs.pop("axis_names", None)
# pandas - guess axis names
if not "axis_names" in kwargs:
if hasattr(data, "columns"):
try:
kwargs["axis_names"] = tuple(data.columns)
except:
pass # Perhaps columns has different meaning here.
# Prepare and check data
# Convert to array
if data is not None:
data = np.asarray(data)
if data.ndim != 2:
raise RuntimeError("Array must have shape (n, d)")
if dim is not None and dim != data.shape[1]:
raise RuntimeError("Dimension mismatch: {0}!={1}".format(dim, data.shape[1]))
_, dim = data.shape
if dropna:
data = data[~np.isnan(data).any(axis=1)]
check_nan = not dropna
else:
if dim is None:
raise RuntimeError("You have to specify either data or its dimension.")
data = np.zeros((0, dim))
check_nan = False
# Prepare bins
bin_schemas = calculate_bins_nd(data, bins, *args, check_nan=check_nan, adaptive=adaptive,
**kwargs)
#bins = [binning.bins for binning in bin_schemas]
# Prepare remaining data
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=dim,
binnings=bin_schemas,
weights=weights)
kwargs["name"] = name
if title:
kwargs["title"] = title
if axis_names:
kwargs["axis_names"] = axis_names
if dim == 2:
return histogram_nd.Histogram2D(binnings=bin_schemas, frequencies=frequencies,
errors2=errors2, **kwargs)
else:
return histogram_nd.HistogramND(dimension=dim, binnings=bin_schemas,
frequencies=frequencies, errors2=errors2, **kwargs) | python | def histogramdd(data, bins=10, *args, **kwargs):
"""Facade function to create n-dimensional histograms.
3D variant of this function is also aliased as "h3".
Parameters
----------
data : array_like
Container of all the values
bins: Any
weights: array_like, optional
(as numpy.histogram)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_names: Iterable[str]
names of the variable on x axis
adaptive:
whether the bins should be updated when new non-fitting value are filled
dtype: Optional[type]
Underlying type for the histogram.
If weights are specified, default is float. Otherwise int64
dim: int
Dimension - necessary if you are creating an empty adaptive histogram
Returns
-------
physt.histogram_nd.HistogramND
See Also
--------
numpy.histogramdd
"""
import numpy as np
from . import histogram_nd
from .binnings import calculate_bins_nd
adaptive = kwargs.pop("adaptive", False)
dropna = kwargs.pop("dropna", True)
name = kwargs.pop("name", None)
title = kwargs.pop("title", None)
dim = kwargs.pop("dim", None)
axis_names = kwargs.pop("axis_names", None)
# pandas - guess axis names
if not "axis_names" in kwargs:
if hasattr(data, "columns"):
try:
kwargs["axis_names"] = tuple(data.columns)
except:
pass # Perhaps columns has different meaning here.
# Prepare and check data
# Convert to array
if data is not None:
data = np.asarray(data)
if data.ndim != 2:
raise RuntimeError("Array must have shape (n, d)")
if dim is not None and dim != data.shape[1]:
raise RuntimeError("Dimension mismatch: {0}!={1}".format(dim, data.shape[1]))
_, dim = data.shape
if dropna:
data = data[~np.isnan(data).any(axis=1)]
check_nan = not dropna
else:
if dim is None:
raise RuntimeError("You have to specify either data or its dimension.")
data = np.zeros((0, dim))
check_nan = False
# Prepare bins
bin_schemas = calculate_bins_nd(data, bins, *args, check_nan=check_nan, adaptive=adaptive,
**kwargs)
#bins = [binning.bins for binning in bin_schemas]
# Prepare remaining data
weights = kwargs.pop("weights", None)
frequencies, errors2, missed = histogram_nd.calculate_frequencies(data, ndim=dim,
binnings=bin_schemas,
weights=weights)
kwargs["name"] = name
if title:
kwargs["title"] = title
if axis_names:
kwargs["axis_names"] = axis_names
if dim == 2:
return histogram_nd.Histogram2D(binnings=bin_schemas, frequencies=frequencies,
errors2=errors2, **kwargs)
else:
return histogram_nd.HistogramND(dimension=dim, binnings=bin_schemas,
frequencies=frequencies, errors2=errors2, **kwargs) | [
"def",
"histogramdd",
"(",
"data",
",",
"bins",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"numpy",
"as",
"np",
"from",
".",
"import",
"histogram_nd",
"from",
".",
"binnings",
"import",
"calculate_bins_nd",
"adaptive",
"=",
"kwargs",
".",
"pop",
"(",
"\"adaptive\"",
",",
"False",
")",
"dropna",
"=",
"kwargs",
".",
"pop",
"(",
"\"dropna\"",
",",
"True",
")",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"\"name\"",
",",
"None",
")",
"title",
"=",
"kwargs",
".",
"pop",
"(",
"\"title\"",
",",
"None",
")",
"dim",
"=",
"kwargs",
".",
"pop",
"(",
"\"dim\"",
",",
"None",
")",
"axis_names",
"=",
"kwargs",
".",
"pop",
"(",
"\"axis_names\"",
",",
"None",
")",
"# pandas - guess axis names",
"if",
"not",
"\"axis_names\"",
"in",
"kwargs",
":",
"if",
"hasattr",
"(",
"data",
",",
"\"columns\"",
")",
":",
"try",
":",
"kwargs",
"[",
"\"axis_names\"",
"]",
"=",
"tuple",
"(",
"data",
".",
"columns",
")",
"except",
":",
"pass",
"# Perhaps columns has different meaning here.",
"# Prepare and check data",
"# Convert to array",
"if",
"data",
"is",
"not",
"None",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"if",
"data",
".",
"ndim",
"!=",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"Array must have shape (n, d)\"",
")",
"if",
"dim",
"is",
"not",
"None",
"and",
"dim",
"!=",
"data",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"Dimension mismatch: {0}!={1}\"",
".",
"format",
"(",
"dim",
",",
"data",
".",
"shape",
"[",
"1",
"]",
")",
")",
"_",
",",
"dim",
"=",
"data",
".",
"shape",
"if",
"dropna",
":",
"data",
"=",
"data",
"[",
"~",
"np",
".",
"isnan",
"(",
"data",
")",
".",
"any",
"(",
"axis",
"=",
"1",
")",
"]",
"check_nan",
"=",
"not",
"dropna",
"else",
":",
"if",
"dim",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"You have to specify either data or its dimension.\"",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"dim",
")",
")",
"check_nan",
"=",
"False",
"# Prepare bins",
"bin_schemas",
"=",
"calculate_bins_nd",
"(",
"data",
",",
"bins",
",",
"*",
"args",
",",
"check_nan",
"=",
"check_nan",
",",
"adaptive",
"=",
"adaptive",
",",
"*",
"*",
"kwargs",
")",
"#bins = [binning.bins for binning in bin_schemas]",
"# Prepare remaining data",
"weights",
"=",
"kwargs",
".",
"pop",
"(",
"\"weights\"",
",",
"None",
")",
"frequencies",
",",
"errors2",
",",
"missed",
"=",
"histogram_nd",
".",
"calculate_frequencies",
"(",
"data",
",",
"ndim",
"=",
"dim",
",",
"binnings",
"=",
"bin_schemas",
",",
"weights",
"=",
"weights",
")",
"kwargs",
"[",
"\"name\"",
"]",
"=",
"name",
"if",
"title",
":",
"kwargs",
"[",
"\"title\"",
"]",
"=",
"title",
"if",
"axis_names",
":",
"kwargs",
"[",
"\"axis_names\"",
"]",
"=",
"axis_names",
"if",
"dim",
"==",
"2",
":",
"return",
"histogram_nd",
".",
"Histogram2D",
"(",
"binnings",
"=",
"bin_schemas",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"histogram_nd",
".",
"HistogramND",
"(",
"dimension",
"=",
"dim",
",",
"binnings",
"=",
"bin_schemas",
",",
"frequencies",
"=",
"frequencies",
",",
"errors2",
"=",
"errors2",
",",
"*",
"*",
"kwargs",
")"
] | Facade function to create n-dimensional histograms.
3D variant of this function is also aliased as "h3".
Parameters
----------
data : array_like
Container of all the values
bins: Any
weights: array_like, optional
(as numpy.histogram)
dropna: bool
whether to clear data from nan's before histogramming
name: str
name of the histogram
axis_names: Iterable[str]
names of the variable on x axis
adaptive:
whether the bins should be updated when new non-fitting value are filled
dtype: Optional[type]
Underlying type for the histogram.
If weights are specified, default is float. Otherwise int64
dim: int
Dimension - necessary if you are creating an empty adaptive histogram
Returns
-------
physt.histogram_nd.HistogramND
See Also
--------
numpy.histogramdd | [
"Facade",
"function",
"to",
"create",
"n",
"-",
"dimensional",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L162-L254 | train |
janpipek/physt | physt/__init__.py | h3 | def h3(data, *args, **kwargs):
"""Facade function to create 3D histograms.
Parameters
----------
data : array_like or list[array_like] or tuple[array_like]
Can be a single array (with three columns) or three different arrays
(for each component)
Returns
-------
physt.histogram_nd.HistogramND
"""
import numpy as np
if data is not None and isinstance(data, (list, tuple)) and not np.isscalar(data[0]):
if "axis_names" not in kwargs:
kwargs["axis_names"] = [(column.name if hasattr(column, "name") else None) for column in data]
data = np.concatenate([item[:, np.newaxis] for item in data], axis=1)
else:
kwargs["dim"] = 3
return histogramdd(data, *args, **kwargs) | python | def h3(data, *args, **kwargs):
"""Facade function to create 3D histograms.
Parameters
----------
data : array_like or list[array_like] or tuple[array_like]
Can be a single array (with three columns) or three different arrays
(for each component)
Returns
-------
physt.histogram_nd.HistogramND
"""
import numpy as np
if data is not None and isinstance(data, (list, tuple)) and not np.isscalar(data[0]):
if "axis_names" not in kwargs:
kwargs["axis_names"] = [(column.name if hasattr(column, "name") else None) for column in data]
data = np.concatenate([item[:, np.newaxis] for item in data], axis=1)
else:
kwargs["dim"] = 3
return histogramdd(data, *args, **kwargs) | [
"def",
"h3",
"(",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"data",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"not",
"np",
".",
"isscalar",
"(",
"data",
"[",
"0",
"]",
")",
":",
"if",
"\"axis_names\"",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"axis_names\"",
"]",
"=",
"[",
"(",
"column",
".",
"name",
"if",
"hasattr",
"(",
"column",
",",
"\"name\"",
")",
"else",
"None",
")",
"for",
"column",
"in",
"data",
"]",
"data",
"=",
"np",
".",
"concatenate",
"(",
"[",
"item",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"for",
"item",
"in",
"data",
"]",
",",
"axis",
"=",
"1",
")",
"else",
":",
"kwargs",
"[",
"\"dim\"",
"]",
"=",
"3",
"return",
"histogramdd",
"(",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Facade function to create 3D histograms.
Parameters
----------
data : array_like or list[array_like] or tuple[array_like]
Can be a single array (with three columns) or three different arrays
(for each component)
Returns
-------
physt.histogram_nd.HistogramND | [
"Facade",
"function",
"to",
"create",
"3D",
"histograms",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L263-L284 | train |
janpipek/physt | physt/__init__.py | collection | def collection(data, bins=10, *args, **kwargs):
"""Create histogram collection with shared binnning."""
from physt.histogram_collection import HistogramCollection
if hasattr(data, "columns"):
data = {column: data[column] for column in data.columns}
return HistogramCollection.multi_h1(data, bins, **kwargs) | python | def collection(data, bins=10, *args, **kwargs):
"""Create histogram collection with shared binnning."""
from physt.histogram_collection import HistogramCollection
if hasattr(data, "columns"):
data = {column: data[column] for column in data.columns}
return HistogramCollection.multi_h1(data, bins, **kwargs) | [
"def",
"collection",
"(",
"data",
",",
"bins",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"physt",
".",
"histogram_collection",
"import",
"HistogramCollection",
"if",
"hasattr",
"(",
"data",
",",
"\"columns\"",
")",
":",
"data",
"=",
"{",
"column",
":",
"data",
"[",
"column",
"]",
"for",
"column",
"in",
"data",
".",
"columns",
"}",
"return",
"HistogramCollection",
".",
"multi_h1",
"(",
"data",
",",
"bins",
",",
"*",
"*",
"kwargs",
")"
] | Create histogram collection with shared binnning. | [
"Create",
"histogram",
"collection",
"with",
"shared",
"binnning",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/__init__.py#L287-L292 | train |
janpipek/physt | physt/io/root.py | write_root | def write_root(histogram: HistogramBase, hfile: uproot.write.TFile.TFileUpdate, name: str):
"""Write histogram to an open ROOT file.
Parameters
----------
histogram : Any histogram
hfile : Updateable uproot file object
name : The name of the histogram inside the file
"""
hfile[name] = histogram | python | def write_root(histogram: HistogramBase, hfile: uproot.write.TFile.TFileUpdate, name: str):
"""Write histogram to an open ROOT file.
Parameters
----------
histogram : Any histogram
hfile : Updateable uproot file object
name : The name of the histogram inside the file
"""
hfile[name] = histogram | [
"def",
"write_root",
"(",
"histogram",
":",
"HistogramBase",
",",
"hfile",
":",
"uproot",
".",
"write",
".",
"TFile",
".",
"TFileUpdate",
",",
"name",
":",
"str",
")",
":",
"hfile",
"[",
"name",
"]",
"=",
"histogram"
] | Write histogram to an open ROOT file.
Parameters
----------
histogram : Any histogram
hfile : Updateable uproot file object
name : The name of the histogram inside the file | [
"Write",
"histogram",
"to",
"an",
"open",
"ROOT",
"file",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/root.py#L16-L25 | train |
janpipek/physt | physt/io/protobuf/__init__.py | write | def write(histogram):
"""Convert a histogram to a protobuf message.
Note: Currently, all binnings are converted to
static form. When you load the histogram again,
you will lose any related behaviour.
Note: A histogram collection is also planned.
Parameters
----------
histogram : HistogramBase | list | dict
Any histogram
Returns
-------
message : google.protobuf.message.Message
A protocol buffer message
"""
histogram_dict = histogram.to_dict()
message = Histogram()
for field in SIMPLE_CONVERSION_FIELDS:
setattr(message, field, histogram_dict[field])
# Main numerical data - TODO: Optimize!
message.frequencies.extend(histogram.frequencies.flatten())
message.errors2.extend(histogram.errors2.flatten())
# Binnings
for binning in histogram._binnings:
binning_message = message.binnings.add()
for edges in binning.bins:
limits = binning_message.bins.add()
limits.lower = edges[0]
limits.upper = edges[1]
# All meta data
meta_message = message.meta
# user_defined = {}
# for key, value in histogram.meta_data.items():
# if key not in PREDEFINED:
# user_defined[str(key)] = str(value)
for key in SIMPLE_META_KEYS:
if key in histogram.meta_data:
setattr(meta_message, key, str(histogram.meta_data[key]))
if "axis_names" in histogram.meta_data:
meta_message.axis_names.extend(histogram.meta_data["axis_names"])
message.physt_version = CURRENT_VERSION
message.physt_compatible = COMPATIBLE_VERSION
return message | python | def write(histogram):
"""Convert a histogram to a protobuf message.
Note: Currently, all binnings are converted to
static form. When you load the histogram again,
you will lose any related behaviour.
Note: A histogram collection is also planned.
Parameters
----------
histogram : HistogramBase | list | dict
Any histogram
Returns
-------
message : google.protobuf.message.Message
A protocol buffer message
"""
histogram_dict = histogram.to_dict()
message = Histogram()
for field in SIMPLE_CONVERSION_FIELDS:
setattr(message, field, histogram_dict[field])
# Main numerical data - TODO: Optimize!
message.frequencies.extend(histogram.frequencies.flatten())
message.errors2.extend(histogram.errors2.flatten())
# Binnings
for binning in histogram._binnings:
binning_message = message.binnings.add()
for edges in binning.bins:
limits = binning_message.bins.add()
limits.lower = edges[0]
limits.upper = edges[1]
# All meta data
meta_message = message.meta
# user_defined = {}
# for key, value in histogram.meta_data.items():
# if key not in PREDEFINED:
# user_defined[str(key)] = str(value)
for key in SIMPLE_META_KEYS:
if key in histogram.meta_data:
setattr(meta_message, key, str(histogram.meta_data[key]))
if "axis_names" in histogram.meta_data:
meta_message.axis_names.extend(histogram.meta_data["axis_names"])
message.physt_version = CURRENT_VERSION
message.physt_compatible = COMPATIBLE_VERSION
return message | [
"def",
"write",
"(",
"histogram",
")",
":",
"histogram_dict",
"=",
"histogram",
".",
"to_dict",
"(",
")",
"message",
"=",
"Histogram",
"(",
")",
"for",
"field",
"in",
"SIMPLE_CONVERSION_FIELDS",
":",
"setattr",
"(",
"message",
",",
"field",
",",
"histogram_dict",
"[",
"field",
"]",
")",
"# Main numerical data - TODO: Optimize!",
"message",
".",
"frequencies",
".",
"extend",
"(",
"histogram",
".",
"frequencies",
".",
"flatten",
"(",
")",
")",
"message",
".",
"errors2",
".",
"extend",
"(",
"histogram",
".",
"errors2",
".",
"flatten",
"(",
")",
")",
"# Binnings",
"for",
"binning",
"in",
"histogram",
".",
"_binnings",
":",
"binning_message",
"=",
"message",
".",
"binnings",
".",
"add",
"(",
")",
"for",
"edges",
"in",
"binning",
".",
"bins",
":",
"limits",
"=",
"binning_message",
".",
"bins",
".",
"add",
"(",
")",
"limits",
".",
"lower",
"=",
"edges",
"[",
"0",
"]",
"limits",
".",
"upper",
"=",
"edges",
"[",
"1",
"]",
"# All meta data",
"meta_message",
"=",
"message",
".",
"meta",
"# user_defined = {}",
"# for key, value in histogram.meta_data.items():",
"# if key not in PREDEFINED:",
"# user_defined[str(key)] = str(value)",
"for",
"key",
"in",
"SIMPLE_META_KEYS",
":",
"if",
"key",
"in",
"histogram",
".",
"meta_data",
":",
"setattr",
"(",
"meta_message",
",",
"key",
",",
"str",
"(",
"histogram",
".",
"meta_data",
"[",
"key",
"]",
")",
")",
"if",
"\"axis_names\"",
"in",
"histogram",
".",
"meta_data",
":",
"meta_message",
".",
"axis_names",
".",
"extend",
"(",
"histogram",
".",
"meta_data",
"[",
"\"axis_names\"",
"]",
")",
"message",
".",
"physt_version",
"=",
"CURRENT_VERSION",
"message",
".",
"physt_compatible",
"=",
"COMPATIBLE_VERSION",
"return",
"message"
] | Convert a histogram to a protobuf message.
Note: Currently, all binnings are converted to
static form. When you load the histogram again,
you will lose any related behaviour.
Note: A histogram collection is also planned.
Parameters
----------
histogram : HistogramBase | list | dict
Any histogram
Returns
-------
message : google.protobuf.message.Message
A protocol buffer message | [
"Convert",
"a",
"histogram",
"to",
"a",
"protobuf",
"message",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/protobuf/__init__.py#L24-L76 | train |
janpipek/physt | physt/io/protobuf/__init__.py | read | def read(message):
"""Convert a parsed protobuf message into a histogram."""
require_compatible_version(message.physt_compatible)
# Currently the only implementation
a_dict = _dict_from_v0342(message)
return create_from_dict(a_dict, "Message") | python | def read(message):
"""Convert a parsed protobuf message into a histogram."""
require_compatible_version(message.physt_compatible)
# Currently the only implementation
a_dict = _dict_from_v0342(message)
return create_from_dict(a_dict, "Message") | [
"def",
"read",
"(",
"message",
")",
":",
"require_compatible_version",
"(",
"message",
".",
"physt_compatible",
")",
"# Currently the only implementation",
"a_dict",
"=",
"_dict_from_v0342",
"(",
"message",
")",
"return",
"create_from_dict",
"(",
"a_dict",
",",
"\"Message\"",
")"
] | Convert a parsed protobuf message into a histogram. | [
"Convert",
"a",
"parsed",
"protobuf",
"message",
"into",
"a",
"histogram",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/io/protobuf/__init__.py#L79-L85 | train |
janpipek/physt | physt/bin_utils.py | make_bin_array | def make_bin_array(bins) -> np.ndarray:
"""Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
[2, 3]])
"""
bins = np.asarray(bins)
if bins.ndim == 1:
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))
elif bins.ndim == 2:
if bins.shape[1] != 2:
raise RuntimeError("Binning schema with ndim==2 must have 2 columns")
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return bins # Already correct, just pass
else:
raise RuntimeError("Binning schema must have ndim==1 or ndim==2") | python | def make_bin_array(bins) -> np.ndarray:
"""Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
[2, 3]])
"""
bins = np.asarray(bins)
if bins.ndim == 1:
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))
elif bins.ndim == 2:
if bins.shape[1] != 2:
raise RuntimeError("Binning schema with ndim==2 must have 2 columns")
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return bins # Already correct, just pass
else:
raise RuntimeError("Binning schema must have ndim==1 or ndim==2") | [
"def",
"make_bin_array",
"(",
"bins",
")",
"->",
"np",
".",
"ndarray",
":",
"bins",
"=",
"np",
".",
"asarray",
"(",
"bins",
")",
"if",
"bins",
".",
"ndim",
"==",
"1",
":",
"# if bins.shape[0] == 0:",
"# raise RuntimeError(\"Needs at least one bin\")",
"return",
"np",
".",
"hstack",
"(",
"(",
"bins",
"[",
":",
"-",
"1",
",",
"np",
".",
"newaxis",
"]",
",",
"bins",
"[",
"1",
":",
",",
"np",
".",
"newaxis",
"]",
")",
")",
"elif",
"bins",
".",
"ndim",
"==",
"2",
":",
"if",
"bins",
".",
"shape",
"[",
"1",
"]",
"!=",
"2",
":",
"raise",
"RuntimeError",
"(",
"\"Binning schema with ndim==2 must have 2 columns\"",
")",
"# if bins.shape[0] == 0:",
"# raise RuntimeError(\"Needs at least one bin\")",
"return",
"bins",
"# Already correct, just pass",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Binning schema must have ndim==1 or ndim==2\"",
")"
] | Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: array_like
Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
[2, 3]]) | [
"Turn",
"bin",
"data",
"into",
"array",
"understood",
"by",
"HistogramXX",
"classes",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L7-L36 | train |
janpipek/physt | physt/bin_utils.py | to_numpy_bins | def to_numpy_bins(bins) -> np.ndarray:
"""Convert physt bin format to numpy edges.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: all edges
"""
bins = np.asarray(bins)
if bins.ndim == 1: # Already in the proper format
return bins
if not is_consecutive(bins):
raise RuntimeError("Cannot create numpy bins from inconsecutive edges")
return np.concatenate([bins[:1, 0], bins[:, 1]]) | python | def to_numpy_bins(bins) -> np.ndarray:
"""Convert physt bin format to numpy edges.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: all edges
"""
bins = np.asarray(bins)
if bins.ndim == 1: # Already in the proper format
return bins
if not is_consecutive(bins):
raise RuntimeError("Cannot create numpy bins from inconsecutive edges")
return np.concatenate([bins[:1, 0], bins[:, 1]]) | [
"def",
"to_numpy_bins",
"(",
"bins",
")",
"->",
"np",
".",
"ndarray",
":",
"bins",
"=",
"np",
".",
"asarray",
"(",
"bins",
")",
"if",
"bins",
".",
"ndim",
"==",
"1",
":",
"# Already in the proper format",
"return",
"bins",
"if",
"not",
"is_consecutive",
"(",
"bins",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot create numpy bins from inconsecutive edges\"",
")",
"return",
"np",
".",
"concatenate",
"(",
"[",
"bins",
"[",
":",
"1",
",",
"0",
"]",
",",
"bins",
"[",
":",
",",
"1",
"]",
"]",
")"
] | Convert physt bin format to numpy edges.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: all edges | [
"Convert",
"physt",
"bin",
"format",
"to",
"numpy",
"edges",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L39-L56 | train |
janpipek/physt | physt/bin_utils.py | to_numpy_bins_with_mask | def to_numpy_bins_with_mask(bins) -> Tuple[np.ndarray, np.ndarray]:
"""Numpy binning edges including gaps.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: np.ndarray
all edges
mask: np.ndarray
List of indices that correspond to bins that have to be included
Examples
--------
>>> to_numpy_bins_with_mask([0, 1, 2])
(array([0., 1., 2.]), array([0, 1]))
>>> to_numpy_bins_with_mask([[0, 1], [2, 3]])
(array([0, 1, 2, 3]), array([0, 2])
"""
bins = np.asarray(bins)
if bins.ndim == 1:
edges = bins
if bins.shape[0] > 1:
mask = np.arange(bins.shape[0] - 1)
else:
mask = []
elif bins.ndim == 2:
edges = []
mask = []
j = 0
if bins.shape[0] > 0:
edges.append(bins[0, 0])
for i in range(bins.shape[0] - 1):
mask.append(j)
edges.append(bins[i, 1])
if bins[i, 1] != bins[i+1, 0]:
edges.append(bins[i+1, 0])
j += 1
j += 1
mask.append(j)
edges.append(bins[-1, 1])
else:
raise RuntimeError("to_numpy_bins_with_mask: array with dim=1 or 2 expected")
if not np.all(np.diff(edges) > 0):
raise RuntimeError("to_numpy_bins_with_mask: edges array not monotone.")
return edges, mask | python | def to_numpy_bins_with_mask(bins) -> Tuple[np.ndarray, np.ndarray]:
"""Numpy binning edges including gaps.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: np.ndarray
all edges
mask: np.ndarray
List of indices that correspond to bins that have to be included
Examples
--------
>>> to_numpy_bins_with_mask([0, 1, 2])
(array([0., 1., 2.]), array([0, 1]))
>>> to_numpy_bins_with_mask([[0, 1], [2, 3]])
(array([0, 1, 2, 3]), array([0, 2])
"""
bins = np.asarray(bins)
if bins.ndim == 1:
edges = bins
if bins.shape[0] > 1:
mask = np.arange(bins.shape[0] - 1)
else:
mask = []
elif bins.ndim == 2:
edges = []
mask = []
j = 0
if bins.shape[0] > 0:
edges.append(bins[0, 0])
for i in range(bins.shape[0] - 1):
mask.append(j)
edges.append(bins[i, 1])
if bins[i, 1] != bins[i+1, 0]:
edges.append(bins[i+1, 0])
j += 1
j += 1
mask.append(j)
edges.append(bins[-1, 1])
else:
raise RuntimeError("to_numpy_bins_with_mask: array with dim=1 or 2 expected")
if not np.all(np.diff(edges) > 0):
raise RuntimeError("to_numpy_bins_with_mask: edges array not monotone.")
return edges, mask | [
"def",
"to_numpy_bins_with_mask",
"(",
"bins",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"bins",
"=",
"np",
".",
"asarray",
"(",
"bins",
")",
"if",
"bins",
".",
"ndim",
"==",
"1",
":",
"edges",
"=",
"bins",
"if",
"bins",
".",
"shape",
"[",
"0",
"]",
">",
"1",
":",
"mask",
"=",
"np",
".",
"arange",
"(",
"bins",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
")",
"else",
":",
"mask",
"=",
"[",
"]",
"elif",
"bins",
".",
"ndim",
"==",
"2",
":",
"edges",
"=",
"[",
"]",
"mask",
"=",
"[",
"]",
"j",
"=",
"0",
"if",
"bins",
".",
"shape",
"[",
"0",
"]",
">",
"0",
":",
"edges",
".",
"append",
"(",
"bins",
"[",
"0",
",",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"bins",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
")",
":",
"mask",
".",
"append",
"(",
"j",
")",
"edges",
".",
"append",
"(",
"bins",
"[",
"i",
",",
"1",
"]",
")",
"if",
"bins",
"[",
"i",
",",
"1",
"]",
"!=",
"bins",
"[",
"i",
"+",
"1",
",",
"0",
"]",
":",
"edges",
".",
"append",
"(",
"bins",
"[",
"i",
"+",
"1",
",",
"0",
"]",
")",
"j",
"+=",
"1",
"j",
"+=",
"1",
"mask",
".",
"append",
"(",
"j",
")",
"edges",
".",
"append",
"(",
"bins",
"[",
"-",
"1",
",",
"1",
"]",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"to_numpy_bins_with_mask: array with dim=1 or 2 expected\"",
")",
"if",
"not",
"np",
".",
"all",
"(",
"np",
".",
"diff",
"(",
"edges",
")",
">",
"0",
")",
":",
"raise",
"RuntimeError",
"(",
"\"to_numpy_bins_with_mask: edges array not monotone.\"",
")",
"return",
"edges",
",",
"mask"
] | Numpy binning edges including gaps.
Parameters
----------
bins: array_like
1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: np.ndarray
all edges
mask: np.ndarray
List of indices that correspond to bins that have to be included
Examples
--------
>>> to_numpy_bins_with_mask([0, 1, 2])
(array([0., 1., 2.]), array([0, 1]))
>>> to_numpy_bins_with_mask([[0, 1], [2, 3]])
(array([0, 1, 2, 3]), array([0, 2]) | [
"Numpy",
"binning",
"edges",
"including",
"gaps",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L59-L108 | train |
janpipek/physt | physt/bin_utils.py | is_rising | def is_rising(bins) -> bool:
"""Check whether the bins are in raising order.
Does not check if the bins are consecutive.
Parameters
----------
bins: array_like
"""
# TODO: Optimize for numpy bins
bins = make_bin_array(bins)
if np.any(bins[:, 0] >= bins[:, 1]):
return False
if np.any(bins[1:, 0] < bins[:-1, 1]):
return False
return True | python | def is_rising(bins) -> bool:
"""Check whether the bins are in raising order.
Does not check if the bins are consecutive.
Parameters
----------
bins: array_like
"""
# TODO: Optimize for numpy bins
bins = make_bin_array(bins)
if np.any(bins[:, 0] >= bins[:, 1]):
return False
if np.any(bins[1:, 0] < bins[:-1, 1]):
return False
return True | [
"def",
"is_rising",
"(",
"bins",
")",
"->",
"bool",
":",
"# TODO: Optimize for numpy bins",
"bins",
"=",
"make_bin_array",
"(",
"bins",
")",
"if",
"np",
".",
"any",
"(",
"bins",
"[",
":",
",",
"0",
"]",
">=",
"bins",
"[",
":",
",",
"1",
"]",
")",
":",
"return",
"False",
"if",
"np",
".",
"any",
"(",
"bins",
"[",
"1",
":",
",",
"0",
"]",
"<",
"bins",
"[",
":",
"-",
"1",
",",
"1",
"]",
")",
":",
"return",
"False",
"return",
"True"
] | Check whether the bins are in raising order.
Does not check if the bins are consecutive.
Parameters
----------
bins: array_like | [
"Check",
"whether",
"the",
"bins",
"are",
"in",
"raising",
"order",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/bin_utils.py#L111-L126 | train |
janpipek/physt | physt/plotting/common.py | get_data | def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
"""Get histogram data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins
"""
if density:
if cumulative:
data = (histogram / histogram.total).cumulative_frequencies
else:
data = histogram.densities
else:
if cumulative:
data = histogram.cumulative_frequencies
else:
data = histogram.frequencies
if flatten:
data = data.flatten()
return data | python | def get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
"""Get histogram data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins
"""
if density:
if cumulative:
data = (histogram / histogram.total).cumulative_frequencies
else:
data = histogram.densities
else:
if cumulative:
data = histogram.cumulative_frequencies
else:
data = histogram.frequencies
if flatten:
data = data.flatten()
return data | [
"def",
"get_data",
"(",
"histogram",
":",
"HistogramBase",
",",
"density",
":",
"bool",
"=",
"False",
",",
"cumulative",
":",
"bool",
"=",
"False",
",",
"flatten",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"density",
":",
"if",
"cumulative",
":",
"data",
"=",
"(",
"histogram",
"/",
"histogram",
".",
"total",
")",
".",
"cumulative_frequencies",
"else",
":",
"data",
"=",
"histogram",
".",
"densities",
"else",
":",
"if",
"cumulative",
":",
"data",
"=",
"histogram",
".",
"cumulative_frequencies",
"else",
":",
"data",
"=",
"histogram",
".",
"frequencies",
"if",
"flatten",
":",
"data",
"=",
"data",
".",
"flatten",
"(",
")",
"return",
"data"
] | Get histogram data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins | [
"Get",
"histogram",
"data",
"based",
"on",
"plotting",
"parameters",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L15-L37 | train |
janpipek/physt | physt/plotting/common.py | get_err_data | def get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
"""Get histogram error data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins
"""
if cumulative:
raise RuntimeError("Error bars not supported for cumulative plots.")
if density:
data = histogram.errors / histogram.bin_sizes
else:
data = histogram.errors
if flatten:
data = data.flatten()
return data | python | def get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) -> np.ndarray:
"""Get histogram error data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins
"""
if cumulative:
raise RuntimeError("Error bars not supported for cumulative plots.")
if density:
data = histogram.errors / histogram.bin_sizes
else:
data = histogram.errors
if flatten:
data = data.flatten()
return data | [
"def",
"get_err_data",
"(",
"histogram",
":",
"HistogramBase",
",",
"density",
":",
"bool",
"=",
"False",
",",
"cumulative",
":",
"bool",
"=",
"False",
",",
"flatten",
":",
"bool",
"=",
"False",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"cumulative",
":",
"raise",
"RuntimeError",
"(",
"\"Error bars not supported for cumulative plots.\"",
")",
"if",
"density",
":",
"data",
"=",
"histogram",
".",
"errors",
"/",
"histogram",
".",
"bin_sizes",
"else",
":",
"data",
"=",
"histogram",
".",
"errors",
"if",
"flatten",
":",
"data",
"=",
"data",
".",
"flatten",
"(",
")",
"return",
"data"
] | Get histogram error data based on plotting parameters.
Parameters
----------
density : Whether to divide bin contents by bin size
cumulative : Whether to return cumulative sums instead of individual
flatten : Whether to flatten multidimensional bins | [
"Get",
"histogram",
"error",
"data",
"based",
"on",
"plotting",
"parameters",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L40-L57 | train |
janpipek/physt | physt/plotting/common.py | get_value_format | def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]:
"""Create a formatting function from a generic value_format argument.
"""
if value_format is None:
value_format = ""
if isinstance(value_format, str):
format_str = "{0:" + value_format + "}"
def value_format(x): return format_str.format(x)
return value_format | python | def get_value_format(value_format: Union[Callable, str] = str) -> Callable[[float], str]:
"""Create a formatting function from a generic value_format argument.
"""
if value_format is None:
value_format = ""
if isinstance(value_format, str):
format_str = "{0:" + value_format + "}"
def value_format(x): return format_str.format(x)
return value_format | [
"def",
"get_value_format",
"(",
"value_format",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
"=",
"str",
")",
"->",
"Callable",
"[",
"[",
"float",
"]",
",",
"str",
"]",
":",
"if",
"value_format",
"is",
"None",
":",
"value_format",
"=",
"\"\"",
"if",
"isinstance",
"(",
"value_format",
",",
"str",
")",
":",
"format_str",
"=",
"\"{0:\"",
"+",
"value_format",
"+",
"\"}\"",
"def",
"value_format",
"(",
"x",
")",
":",
"return",
"format_str",
".",
"format",
"(",
"x",
")",
"return",
"value_format"
] | Create a formatting function from a generic value_format argument. | [
"Create",
"a",
"formatting",
"function",
"from",
"a",
"generic",
"value_format",
"argument",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L60-L70 | train |
janpipek/physt | physt/plotting/common.py | pop_kwargs_with_prefix | def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict:
"""Pop all items from a dictionary that have keys beginning with a prefix.
Parameters
----------
prefix : str
kwargs : dict
Returns
-------
kwargs : dict
Items popped from the original directory, with prefix removed.
"""
keys = [key for key in kwargs if key.startswith(prefix)]
return {key[len(prefix):]: kwargs.pop(key) for key in keys} | python | def pop_kwargs_with_prefix(prefix: str, kwargs: dict) -> dict:
"""Pop all items from a dictionary that have keys beginning with a prefix.
Parameters
----------
prefix : str
kwargs : dict
Returns
-------
kwargs : dict
Items popped from the original directory, with prefix removed.
"""
keys = [key for key in kwargs if key.startswith(prefix)]
return {key[len(prefix):]: kwargs.pop(key) for key in keys} | [
"def",
"pop_kwargs_with_prefix",
"(",
"prefix",
":",
"str",
",",
"kwargs",
":",
"dict",
")",
"->",
"dict",
":",
"keys",
"=",
"[",
"key",
"for",
"key",
"in",
"kwargs",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
"]",
"return",
"{",
"key",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
":",
"kwargs",
".",
"pop",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
"}"
] | Pop all items from a dictionary that have keys beginning with a prefix.
Parameters
----------
prefix : str
kwargs : dict
Returns
-------
kwargs : dict
Items popped from the original directory, with prefix removed. | [
"Pop",
"all",
"items",
"from",
"a",
"dictionary",
"that",
"have",
"keys",
"beginning",
"with",
"a",
"prefix",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/common.py#L73-L87 | train |
janpipek/physt | physt/histogram_nd.py | HistogramND.bins | def bins(self) -> List[np.ndarray]:
"""List of bin matrices."""
return [binning.bins for binning in self._binnings] | python | def bins(self) -> List[np.ndarray]:
"""List of bin matrices."""
return [binning.bins for binning in self._binnings] | [
"def",
"bins",
"(",
"self",
")",
"->",
"List",
"[",
"np",
".",
"ndarray",
"]",
":",
"return",
"[",
"binning",
".",
"bins",
"for",
"binning",
"in",
"self",
".",
"_binnings",
"]"
] | List of bin matrices. | [
"List",
"of",
"bin",
"matrices",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L54-L56 | train |
janpipek/physt | physt/histogram_nd.py | HistogramND.select | def select(self, axis: AxisIdentifier, index, force_copy: bool = False) -> HistogramBase:
"""Select in an axis.
Parameters
----------
axis: int or str
Axis, in which we select.
index: int or slice
Index of bin (as in numpy).
force_copy: bool
If True, identity slice force a copy to be made.
"""
if index == slice(None) and not force_copy:
return self
axis_id = self._get_axis(axis)
array_index = [slice(None, None, None) for i in range(self.ndim)]
array_index[axis_id] = index
frequencies = self._frequencies[tuple(array_index)].copy()
errors2 = self._errors2[tuple(array_index)].copy()
if isinstance(index, int):
return self._reduce_dimension([ax for ax in range(self.ndim) if ax != axis_id], frequencies, errors2)
elif isinstance(index, slice):
if index.step is not None and index.step < 0:
raise IndexError("Cannot change the order of bins")
copy = self.copy()
copy._frequencies = frequencies
copy._errors2 = errors2
copy._binnings[axis_id] = self._binnings[axis_id][index]
return copy
else:
raise ValueError("Invalid index.") | python | def select(self, axis: AxisIdentifier, index, force_copy: bool = False) -> HistogramBase:
"""Select in an axis.
Parameters
----------
axis: int or str
Axis, in which we select.
index: int or slice
Index of bin (as in numpy).
force_copy: bool
If True, identity slice force a copy to be made.
"""
if index == slice(None) and not force_copy:
return self
axis_id = self._get_axis(axis)
array_index = [slice(None, None, None) for i in range(self.ndim)]
array_index[axis_id] = index
frequencies = self._frequencies[tuple(array_index)].copy()
errors2 = self._errors2[tuple(array_index)].copy()
if isinstance(index, int):
return self._reduce_dimension([ax for ax in range(self.ndim) if ax != axis_id], frequencies, errors2)
elif isinstance(index, slice):
if index.step is not None and index.step < 0:
raise IndexError("Cannot change the order of bins")
copy = self.copy()
copy._frequencies = frequencies
copy._errors2 = errors2
copy._binnings[axis_id] = self._binnings[axis_id][index]
return copy
else:
raise ValueError("Invalid index.") | [
"def",
"select",
"(",
"self",
",",
"axis",
":",
"AxisIdentifier",
",",
"index",
",",
"force_copy",
":",
"bool",
"=",
"False",
")",
"->",
"HistogramBase",
":",
"if",
"index",
"==",
"slice",
"(",
"None",
")",
"and",
"not",
"force_copy",
":",
"return",
"self",
"axis_id",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"array_index",
"=",
"[",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"ndim",
")",
"]",
"array_index",
"[",
"axis_id",
"]",
"=",
"index",
"frequencies",
"=",
"self",
".",
"_frequencies",
"[",
"tuple",
"(",
"array_index",
")",
"]",
".",
"copy",
"(",
")",
"errors2",
"=",
"self",
".",
"_errors2",
"[",
"tuple",
"(",
"array_index",
")",
"]",
".",
"copy",
"(",
")",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"return",
"self",
".",
"_reduce_dimension",
"(",
"[",
"ax",
"for",
"ax",
"in",
"range",
"(",
"self",
".",
"ndim",
")",
"if",
"ax",
"!=",
"axis_id",
"]",
",",
"frequencies",
",",
"errors2",
")",
"elif",
"isinstance",
"(",
"index",
",",
"slice",
")",
":",
"if",
"index",
".",
"step",
"is",
"not",
"None",
"and",
"index",
".",
"step",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"\"Cannot change the order of bins\"",
")",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"_frequencies",
"=",
"frequencies",
"copy",
".",
"_errors2",
"=",
"errors2",
"copy",
".",
"_binnings",
"[",
"axis_id",
"]",
"=",
"self",
".",
"_binnings",
"[",
"axis_id",
"]",
"[",
"index",
"]",
"return",
"copy",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid index.\"",
")"
] | Select in an axis.
Parameters
----------
axis: int or str
Axis, in which we select.
index: int or slice
Index of bin (as in numpy).
force_copy: bool
If True, identity slice force a copy to be made. | [
"Select",
"in",
"an",
"axis",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L71-L104 | train |
janpipek/physt | physt/histogram_nd.py | HistogramND.accumulate | def accumulate(self, axis: AxisIdentifier) -> HistogramBase:
"""Calculate cumulative frequencies along a certain axis.
Returns
-------
new_hist: Histogram of the same type & size
"""
# TODO: Merge with Histogram1D.cumulative_frequencies
# TODO: Deal with errors and totals etc.
# TODO: inplace
new_one = self.copy()
axis_id = self._get_axis(axis)
new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0])
return new_one | python | def accumulate(self, axis: AxisIdentifier) -> HistogramBase:
"""Calculate cumulative frequencies along a certain axis.
Returns
-------
new_hist: Histogram of the same type & size
"""
# TODO: Merge with Histogram1D.cumulative_frequencies
# TODO: Deal with errors and totals etc.
# TODO: inplace
new_one = self.copy()
axis_id = self._get_axis(axis)
new_one._frequencies = np.cumsum(new_one.frequencies, axis_id[0])
return new_one | [
"def",
"accumulate",
"(",
"self",
",",
"axis",
":",
"AxisIdentifier",
")",
"->",
"HistogramBase",
":",
"# TODO: Merge with Histogram1D.cumulative_frequencies",
"# TODO: Deal with errors and totals etc.",
"# TODO: inplace",
"new_one",
"=",
"self",
".",
"copy",
"(",
")",
"axis_id",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"new_one",
".",
"_frequencies",
"=",
"np",
".",
"cumsum",
"(",
"new_one",
".",
"frequencies",
",",
"axis_id",
"[",
"0",
"]",
")",
"return",
"new_one"
] | Calculate cumulative frequencies along a certain axis.
Returns
-------
new_hist: Histogram of the same type & size | [
"Calculate",
"cumulative",
"frequencies",
"along",
"a",
"certain",
"axis",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L338-L351 | train |
janpipek/physt | physt/histogram_nd.py | Histogram2D.T | def T(self) -> "Histogram2D":
"""Histogram with swapped axes.
Returns
-------
Histogram2D - a copy with swapped axes
"""
a_copy = self.copy()
a_copy._binnings = list(reversed(a_copy._binnings))
a_copy.axis_names = list(reversed(a_copy.axis_names))
a_copy._frequencies = a_copy._frequencies.T
a_copy._errors2 = a_copy._errors2.T
return a_copy | python | def T(self) -> "Histogram2D":
"""Histogram with swapped axes.
Returns
-------
Histogram2D - a copy with swapped axes
"""
a_copy = self.copy()
a_copy._binnings = list(reversed(a_copy._binnings))
a_copy.axis_names = list(reversed(a_copy.axis_names))
a_copy._frequencies = a_copy._frequencies.T
a_copy._errors2 = a_copy._errors2.T
return a_copy | [
"def",
"T",
"(",
"self",
")",
"->",
"\"Histogram2D\"",
":",
"a_copy",
"=",
"self",
".",
"copy",
"(",
")",
"a_copy",
".",
"_binnings",
"=",
"list",
"(",
"reversed",
"(",
"a_copy",
".",
"_binnings",
")",
")",
"a_copy",
".",
"axis_names",
"=",
"list",
"(",
"reversed",
"(",
"a_copy",
".",
"axis_names",
")",
")",
"a_copy",
".",
"_frequencies",
"=",
"a_copy",
".",
"_frequencies",
".",
"T",
"a_copy",
".",
"_errors2",
"=",
"a_copy",
".",
"_errors2",
".",
"T",
"return",
"a_copy"
] | Histogram with swapped axes.
Returns
-------
Histogram2D - a copy with swapped axes | [
"Histogram",
"with",
"swapped",
"axes",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L414-L426 | train |
janpipek/physt | physt/histogram_nd.py | Histogram2D.partial_normalize | def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False):
"""Normalize in rows or columns.
Parameters
----------
axis: int or str
Along which axis to sum (numpy-sense)
inplace: bool
Update the object itself
Returns
-------
hist : Histogram2D
"""
# TODO: Is this applicable for HistogramND?
axis = self._get_axis(axis)
if not inplace:
copy = self.copy()
copy.partial_normalize(axis, inplace=True)
return copy
else:
self._coerce_dtype(float)
if axis == 0:
divisor = self._frequencies.sum(axis=0)
else:
divisor = self._frequencies.sum(axis=1)[:, np.newaxis]
divisor[divisor == 0] = 1 # Prevent division errors
self._frequencies /= divisor
self._errors2 /= (divisor * divisor) # Has its limitations
return self | python | def partial_normalize(self, axis: AxisIdentifier = 0, inplace: bool = False):
"""Normalize in rows or columns.
Parameters
----------
axis: int or str
Along which axis to sum (numpy-sense)
inplace: bool
Update the object itself
Returns
-------
hist : Histogram2D
"""
# TODO: Is this applicable for HistogramND?
axis = self._get_axis(axis)
if not inplace:
copy = self.copy()
copy.partial_normalize(axis, inplace=True)
return copy
else:
self._coerce_dtype(float)
if axis == 0:
divisor = self._frequencies.sum(axis=0)
else:
divisor = self._frequencies.sum(axis=1)[:, np.newaxis]
divisor[divisor == 0] = 1 # Prevent division errors
self._frequencies /= divisor
self._errors2 /= (divisor * divisor) # Has its limitations
return self | [
"def",
"partial_normalize",
"(",
"self",
",",
"axis",
":",
"AxisIdentifier",
"=",
"0",
",",
"inplace",
":",
"bool",
"=",
"False",
")",
":",
"# TODO: Is this applicable for HistogramND?",
"axis",
"=",
"self",
".",
"_get_axis",
"(",
"axis",
")",
"if",
"not",
"inplace",
":",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"partial_normalize",
"(",
"axis",
",",
"inplace",
"=",
"True",
")",
"return",
"copy",
"else",
":",
"self",
".",
"_coerce_dtype",
"(",
"float",
")",
"if",
"axis",
"==",
"0",
":",
"divisor",
"=",
"self",
".",
"_frequencies",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"else",
":",
"divisor",
"=",
"self",
".",
"_frequencies",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"divisor",
"[",
"divisor",
"==",
"0",
"]",
"=",
"1",
"# Prevent division errors",
"self",
".",
"_frequencies",
"/=",
"divisor",
"self",
".",
"_errors2",
"/=",
"(",
"divisor",
"*",
"divisor",
")",
"# Has its limitations",
"return",
"self"
] | Normalize in rows or columns.
Parameters
----------
axis: int or str
Along which axis to sum (numpy-sense)
inplace: bool
Update the object itself
Returns
-------
hist : Histogram2D | [
"Normalize",
"in",
"rows",
"or",
"columns",
"."
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/histogram_nd.py#L428-L457 | train |
janpipek/physt | physt/binnings.py | numpy_binning | def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
"""Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See Also
--------
numpy.histogram
"""
if isinstance(bins, int):
if range:
bins = np.linspace(range[0], range[1], bins + 1)
else:
start = data.min()
stop = data.max()
bins = np.linspace(start, stop, bins + 1)
elif np.iterable(bins):
bins = np.asarray(bins)
else:
# Some numpy edge case
_, bins = np.histogram(data, bins, **kwargs)
return NumpyBinning(bins) | python | def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
"""Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See Also
--------
numpy.histogram
"""
if isinstance(bins, int):
if range:
bins = np.linspace(range[0], range[1], bins + 1)
else:
start = data.min()
stop = data.max()
bins = np.linspace(start, stop, bins + 1)
elif np.iterable(bins):
bins = np.asarray(bins)
else:
# Some numpy edge case
_, bins = np.histogram(data, bins, **kwargs)
return NumpyBinning(bins) | [
"def",
"numpy_binning",
"(",
"data",
",",
"bins",
"=",
"10",
",",
"range",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"NumpyBinning",
":",
"if",
"isinstance",
"(",
"bins",
",",
"int",
")",
":",
"if",
"range",
":",
"bins",
"=",
"np",
".",
"linspace",
"(",
"range",
"[",
"0",
"]",
",",
"range",
"[",
"1",
"]",
",",
"bins",
"+",
"1",
")",
"else",
":",
"start",
"=",
"data",
".",
"min",
"(",
")",
"stop",
"=",
"data",
".",
"max",
"(",
")",
"bins",
"=",
"np",
".",
"linspace",
"(",
"start",
",",
"stop",
",",
"bins",
"+",
"1",
")",
"elif",
"np",
".",
"iterable",
"(",
"bins",
")",
":",
"bins",
"=",
"np",
".",
"asarray",
"(",
"bins",
")",
"else",
":",
"# Some numpy edge case",
"_",
",",
"bins",
"=",
"np",
".",
"histogram",
"(",
"data",
",",
"bins",
",",
"*",
"*",
"kwargs",
")",
"return",
"NumpyBinning",
"(",
"bins",
")"
] | Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See Also
--------
numpy.histogram | [
"Construct",
"binning",
"schema",
"compatible",
"with",
"numpy",
".",
"histogram"
] | 6dd441b073514e7728235f50b2352d56aacf38d4 | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/binnings.py#L596-L625 | train |
Subsets and Splits