repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
philklei/tahoma-api | tahoma_api/tahoma_api.py | Action.serialize | def serialize(self):
"""Serialize action."""
commands = []
for cmd in self.commands:
commands.append(cmd.serialize())
out = {'commands': commands, 'deviceURL': self.__device_url}
return out | python | def serialize(self):
"""Serialize action."""
commands = []
for cmd in self.commands:
commands.append(cmd.serialize())
out = {'commands': commands, 'deviceURL': self.__device_url}
return out | [
"def",
"serialize",
"(",
"self",
")",
":",
"commands",
"=",
"[",
"]",
"for",
"cmd",
"in",
"self",
".",
"commands",
":",
"commands",
".",
"append",
"(",
"cmd",
".",
"serialize",
"(",
")",
")",
"out",
"=",
"{",
"'commands'",
":",
"commands",
",",
"'d... | Serialize action. | [
"Serialize",
"action",
"."
] | fc84f6ba3b673d0cd0e9e618777834a74a3c7b64 | https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L827-L836 | train |
philklei/tahoma-api | tahoma_api/tahoma_api.py | Event.factory | def factory(data):
"""Tahoma Event factory."""
if data['name'] is "DeviceStateChangedEvent":
return DeviceStateChangedEvent(data)
elif data['name'] is "ExecutionStateChangedEvent":
return ExecutionStateChangedEvent(data)
elif data['name'] is "CommandExecutionState... | python | def factory(data):
"""Tahoma Event factory."""
if data['name'] is "DeviceStateChangedEvent":
return DeviceStateChangedEvent(data)
elif data['name'] is "ExecutionStateChangedEvent":
return ExecutionStateChangedEvent(data)
elif data['name'] is "CommandExecutionState... | [
"def",
"factory",
"(",
"data",
")",
":",
"if",
"data",
"[",
"'name'",
"]",
"is",
"\"DeviceStateChangedEvent\"",
":",
"return",
"DeviceStateChangedEvent",
"(",
"data",
")",
"elif",
"data",
"[",
"'name'",
"]",
"is",
"\"ExecutionStateChangedEvent\"",
":",
"return",... | Tahoma Event factory. | [
"Tahoma",
"Event",
"factory",
"."
] | fc84f6ba3b673d0cd0e9e618777834a74a3c7b64 | https://github.com/philklei/tahoma-api/blob/fc84f6ba3b673d0cd0e9e618777834a74a3c7b64/tahoma_api/tahoma_api.py#L948-L957 | train |
openknowledge-archive/flexidate | flexidate/__init__.py | parse | def parse(date, dayfirst=True):
'''Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: convert '-' to '?' when used... | python | def parse(date, dayfirst=True):
'''Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: convert '-' to '?' when used... | [
"def",
"parse",
"(",
"date",
",",
"dayfirst",
"=",
"True",
")",
":",
"if",
"not",
"date",
":",
"return",
"None",
"if",
"isinstance",
"(",
"date",
",",
"FlexiDate",
")",
":",
"return",
"date",
"if",
"isinstance",
"(",
"date",
",",
"int",
")",
":",
"... | Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: convert '-' to '?' when used that way
e.g. had this date [1... | [
"Parse",
"a",
"date",
"into",
"a",
"FlexiDate",
"."
] | d4fb7d6c7786725bd892fbccd8c3837ac45bcb67 | https://github.com/openknowledge-archive/flexidate/blob/d4fb7d6c7786725bd892fbccd8c3837ac45bcb67/flexidate/__init__.py#L162-L194 | train |
openknowledge-archive/flexidate | flexidate/__init__.py | FlexiDate.as_datetime | def as_datetime(self):
'''Get as python datetime.datetime.
Require year to be a valid datetime year. Default month and day to 1 if
do not exist.
@return: datetime.datetime object.
'''
year = int(self.year)
month = int(self.month) if self.month else 1
day... | python | def as_datetime(self):
'''Get as python datetime.datetime.
Require year to be a valid datetime year. Default month and day to 1 if
do not exist.
@return: datetime.datetime object.
'''
year = int(self.year)
month = int(self.month) if self.month else 1
day... | [
"def",
"as_datetime",
"(",
"self",
")",
":",
"year",
"=",
"int",
"(",
"self",
".",
"year",
")",
"month",
"=",
"int",
"(",
"self",
".",
"month",
")",
"if",
"self",
".",
"month",
"else",
"1",
"day",
"=",
"int",
"(",
"self",
".",
"day",
")",
"if",... | Get as python datetime.datetime.
Require year to be a valid datetime year. Default month and day to 1 if
do not exist.
@return: datetime.datetime object. | [
"Get",
"as",
"python",
"datetime",
".",
"datetime",
"."
] | d4fb7d6c7786725bd892fbccd8c3837ac45bcb67 | https://github.com/openknowledge-archive/flexidate/blob/d4fb7d6c7786725bd892fbccd8c3837ac45bcb67/flexidate/__init__.py#L144-L159 | train |
bjmorgan/vasppy | vasppy/utils.py | md5sum | def md5sum( string ):
"""
Generate the md5 checksum for a string
Args:
string (Str): The string to be checksummed.
Returns:
(Str): The hex checksum.
"""
h = hashlib.new( 'md5' )
h.update( string.encode( 'utf-8' ) )
return h.hexdigest() | python | def md5sum( string ):
"""
Generate the md5 checksum for a string
Args:
string (Str): The string to be checksummed.
Returns:
(Str): The hex checksum.
"""
h = hashlib.new( 'md5' )
h.update( string.encode( 'utf-8' ) )
return h.hexdigest() | [
"def",
"md5sum",
"(",
"string",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"'md5'",
")",
"h",
".",
"update",
"(",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | Generate the md5 checksum for a string
Args:
string (Str): The string to be checksummed.
Returns:
(Str): The hex checksum. | [
"Generate",
"the",
"md5",
"checksum",
"for",
"a",
"string"
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/utils.py#L17-L29 | train |
bjmorgan/vasppy | vasppy/utils.py | file_md5 | def file_md5( filename ):
"""
Generate the md5 checksum for a file
Args:
filename (Str): The file to be checksummed.
Returns:
(Str): The hex checksum
Notes:
If the file is gzipped, the md5 checksum returned is
for the uncompressed ASCII file.
"""
with zopen... | python | def file_md5( filename ):
"""
Generate the md5 checksum for a file
Args:
filename (Str): The file to be checksummed.
Returns:
(Str): The hex checksum
Notes:
If the file is gzipped, the md5 checksum returned is
for the uncompressed ASCII file.
"""
with zopen... | [
"def",
"file_md5",
"(",
"filename",
")",
":",
"with",
"zopen",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"file_string",
"=",
"f",
".",
"read",
"(",
")",
"try",
":",
"file_string",
"=",
"file_string",
".",
"decode",
"(",
")",
"except",
"Attrib... | Generate the md5 checksum for a file
Args:
filename (Str): The file to be checksummed.
Returns:
(Str): The hex checksum
Notes:
If the file is gzipped, the md5 checksum returned is
for the uncompressed ASCII file. | [
"Generate",
"the",
"md5",
"checksum",
"for",
"a",
"file"
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/utils.py#L31-L51 | train |
bjmorgan/vasppy | vasppy/utils.py | validate_checksum | def validate_checksum( filename, md5sum ):
"""
Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the ch... | python | def validate_checksum( filename, md5sum ):
"""
Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the ch... | [
"def",
"validate_checksum",
"(",
"filename",
",",
"md5sum",
")",
":",
"filename",
"=",
"match_filename",
"(",
"filename",
")",
"md5_hash",
"=",
"file_md5",
"(",
"filename",
"=",
"filename",
")",
"if",
"md5_hash",
"!=",
"md5sum",
":",
"raise",
"ValueError",
"... | Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the checksum is calculated for the unzipped file.
Args:
... | [
"Compares",
"the",
"md5",
"checksum",
"of",
"a",
"file",
"with",
"an",
"expected",
"value",
".",
"If",
"the",
"calculated",
"and",
"expected",
"checksum",
"values",
"are",
"not",
"equal",
"ValueError",
"is",
"raised",
".",
"If",
"the",
"filename",
"foo",
"... | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/utils.py#L69-L87 | train |
bjmorgan/vasppy | vasppy/optics.py | to_matrix | def to_matrix( xx, yy, zz, xy, yz, xz ):
"""
Convert a list of matrix components to a symmetric 3x3 matrix.
Inputs should be in the order xx, yy, zz, xy, yz, xz.
Args:
xx (float): xx component of the matrix.
yy (float): yy component of the matrix.
zz (float): zz component of the... | python | def to_matrix( xx, yy, zz, xy, yz, xz ):
"""
Convert a list of matrix components to a symmetric 3x3 matrix.
Inputs should be in the order xx, yy, zz, xy, yz, xz.
Args:
xx (float): xx component of the matrix.
yy (float): yy component of the matrix.
zz (float): zz component of the... | [
"def",
"to_matrix",
"(",
"xx",
",",
"yy",
",",
"zz",
",",
"xy",
",",
"yz",
",",
"xz",
")",
":",
"matrix",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"xx",
",",
"xy",
",",
"xz",
"]",
",",
"[",
"xy",
",",
"yy",
",",
"yz",
"]",
",",
"[",
"xz"... | Convert a list of matrix components to a symmetric 3x3 matrix.
Inputs should be in the order xx, yy, zz, xy, yz, xz.
Args:
xx (float): xx component of the matrix.
yy (float): yy component of the matrix.
zz (float): zz component of the matrix.
xy (float): xy component of the matr... | [
"Convert",
"a",
"list",
"of",
"matrix",
"components",
"to",
"a",
"symmetric",
"3x3",
"matrix",
".",
"Inputs",
"should",
"be",
"in",
"the",
"order",
"xx",
"yy",
"zz",
"xy",
"yz",
"xz",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/optics.py#L24-L41 | train |
bjmorgan/vasppy | vasppy/optics.py | absorption_coefficient | def absorption_coefficient( dielectric ):
"""
Calculate the optical absorption coefficient from an input set of
pymatgen vasprun dielectric constant data.
Args:
dielectric (list): A list containing the dielectric response function
in the pymatgen vasprun format.
... | python | def absorption_coefficient( dielectric ):
"""
Calculate the optical absorption coefficient from an input set of
pymatgen vasprun dielectric constant data.
Args:
dielectric (list): A list containing the dielectric response function
in the pymatgen vasprun format.
... | [
"def",
"absorption_coefficient",
"(",
"dielectric",
")",
":",
"energies_in_eV",
"=",
"np",
".",
"array",
"(",
"dielectric",
"[",
"0",
"]",
")",
"real_dielectric",
"=",
"parse_dielectric_data",
"(",
"dielectric",
"[",
"1",
"]",
")",
"imag_dielectric",
"=",
"par... | Calculate the optical absorption coefficient from an input set of
pymatgen vasprun dielectric constant data.
Args:
dielectric (list): A list containing the dielectric response function
in the pymatgen vasprun format.
| element 0: list of energies
... | [
"Calculate",
"the",
"optical",
"absorption",
"coefficient",
"from",
"an",
"input",
"set",
"of",
"pymatgen",
"vasprun",
"dielectric",
"constant",
"data",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/optics.py#L72-L100 | train |
bjmorgan/vasppy | vasppy/configuration.py | Configuration.dr | def dr( self, atom1, atom2 ):
"""
Calculate the distance between two atoms.
Args:
atom1 (vasppy.Atom): Atom 1.
atom2 (vasppy.Atom): Atom 2.
Returns:
(float): The distance between Atom 1 and Atom 2.
"""
return self.cell.dr( atom1.r, at... | python | def dr( self, atom1, atom2 ):
"""
Calculate the distance between two atoms.
Args:
atom1 (vasppy.Atom): Atom 1.
atom2 (vasppy.Atom): Atom 2.
Returns:
(float): The distance between Atom 1 and Atom 2.
"""
return self.cell.dr( atom1.r, at... | [
"def",
"dr",
"(",
"self",
",",
"atom1",
",",
"atom2",
")",
":",
"return",
"self",
".",
"cell",
".",
"dr",
"(",
"atom1",
".",
"r",
",",
"atom2",
".",
"r",
")"
] | Calculate the distance between two atoms.
Args:
atom1 (vasppy.Atom): Atom 1.
atom2 (vasppy.Atom): Atom 2.
Returns:
(float): The distance between Atom 1 and Atom 2. | [
"Calculate",
"the",
"distance",
"between",
"two",
"atoms",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/configuration.py#L13-L24 | train |
bjmorgan/vasppy | vasppy/procar.py | area_of_a_triangle_in_cartesian_space | def area_of_a_triangle_in_cartesian_space( a, b, c ):
"""
Returns the area of a triangle defined by three points in Cartesian space.
Args:
a (np.array): Cartesian coordinates of point A.
b (np.array): Cartesian coordinates of point B.
c (np.array): Cartesian coordinates of point C.
... | python | def area_of_a_triangle_in_cartesian_space( a, b, c ):
"""
Returns the area of a triangle defined by three points in Cartesian space.
Args:
a (np.array): Cartesian coordinates of point A.
b (np.array): Cartesian coordinates of point B.
c (np.array): Cartesian coordinates of point C.
... | [
"def",
"area_of_a_triangle_in_cartesian_space",
"(",
"a",
",",
"b",
",",
"c",
")",
":",
"return",
"0.5",
"*",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"cross",
"(",
"b",
"-",
"a",
",",
"c",
"-",
"a",
")",
")"
] | Returns the area of a triangle defined by three points in Cartesian space.
Args:
a (np.array): Cartesian coordinates of point A.
b (np.array): Cartesian coordinates of point B.
c (np.array): Cartesian coordinates of point C.
Returns:
(float): the area of the triangle. | [
"Returns",
"the",
"area",
"of",
"a",
"triangle",
"defined",
"by",
"three",
"points",
"in",
"Cartesian",
"space",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/procar.py#L24-L36 | train |
bjmorgan/vasppy | vasppy/procar.py | points_are_in_a_straight_line | def points_are_in_a_straight_line( points, tolerance=1e-7 ):
"""
Check whether a set of points fall on a straight line.
Calculates the areas of triangles formed by triplets of the points.
Returns False is any of these areas are larger than the tolerance.
Args:
points (list(np.array)): list ... | python | def points_are_in_a_straight_line( points, tolerance=1e-7 ):
"""
Check whether a set of points fall on a straight line.
Calculates the areas of triangles formed by triplets of the points.
Returns False is any of these areas are larger than the tolerance.
Args:
points (list(np.array)): list ... | [
"def",
"points_are_in_a_straight_line",
"(",
"points",
",",
"tolerance",
"=",
"1e-7",
")",
":",
"a",
"=",
"points",
"[",
"0",
"]",
"b",
"=",
"points",
"[",
"1",
"]",
"for",
"c",
"in",
"points",
"[",
"2",
":",
"]",
":",
"if",
"area_of_a_triangle_in_cart... | Check whether a set of points fall on a straight line.
Calculates the areas of triangles formed by triplets of the points.
Returns False is any of these areas are larger than the tolerance.
Args:
points (list(np.array)): list of Cartesian coordinates for each point.
tolerance (optional:floa... | [
"Check",
"whether",
"a",
"set",
"of",
"points",
"fall",
"on",
"a",
"straight",
"line",
".",
"Calculates",
"the",
"areas",
"of",
"triangles",
"formed",
"by",
"triplets",
"of",
"the",
"points",
".",
"Returns",
"False",
"is",
"any",
"of",
"these",
"areas",
... | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/procar.py#L38-L56 | train |
bjmorgan/vasppy | vasppy/procar.py | two_point_effective_mass | def two_point_effective_mass( cartesian_k_points, eigenvalues ):
"""
Calculate the effective mass given eigenvalues at two k-points.
Reimplemented from Aron Walsh's original effective mass Fortran code.
Args:
cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) ... | python | def two_point_effective_mass( cartesian_k_points, eigenvalues ):
"""
Calculate the effective mass given eigenvalues at two k-points.
Reimplemented from Aron Walsh's original effective mass Fortran code.
Args:
cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) ... | [
"def",
"two_point_effective_mass",
"(",
"cartesian_k_points",
",",
"eigenvalues",
")",
":",
"assert",
"(",
"cartesian_k_points",
".",
"shape",
"[",
"0",
"]",
"==",
"2",
")",
"assert",
"(",
"eigenvalues",
".",
"size",
"==",
"2",
")",
"dk",
"=",
"cartesian_k_p... | Calculate the effective mass given eigenvalues at two k-points.
Reimplemented from Aron Walsh's original effective mass Fortran code.
Args:
cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) Cartesian coordinates.
eigenvalues (np.array): numpy array con... | [
"Calculate",
"the",
"effective",
"mass",
"given",
"eigenvalues",
"at",
"two",
"k",
"-",
"points",
".",
"Reimplemented",
"from",
"Aron",
"Walsh",
"s",
"original",
"effective",
"mass",
"Fortran",
"code",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/procar.py#L58-L76 | train |
bjmorgan/vasppy | vasppy/procar.py | least_squares_effective_mass | def least_squares_effective_mass( cartesian_k_points, eigenvalues ):
"""
Calculate the effective mass using a least squares quadratic fit.
Args:
cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points
eigenvalues (np.array): Energy eigenvalues at each k-point... | python | def least_squares_effective_mass( cartesian_k_points, eigenvalues ):
"""
Calculate the effective mass using a least squares quadratic fit.
Args:
cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points
eigenvalues (np.array): Energy eigenvalues at each k-point... | [
"def",
"least_squares_effective_mass",
"(",
"cartesian_k_points",
",",
"eigenvalues",
")",
":",
"if",
"not",
"points_are_in_a_straight_line",
"(",
"cartesian_k_points",
")",
":",
"raise",
"ValueError",
"(",
"'k-points are not collinear'",
")",
"dk",
"=",
"cartesian_k_poin... | Calculate the effective mass using a least squares quadratic fit.
Args:
cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points
eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit.
Returns:
(float): The fitted effective mass
... | [
"Calculate",
"the",
"effective",
"mass",
"using",
"a",
"least",
"squares",
"quadratic",
"fit",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/procar.py#L78-L98 | train |
bjmorgan/vasppy | vasppy/procar.py | Procar.read_from_file | def read_from_file( self, filename, negative_occupancies='warn' ):
"""
Reads the projected wavefunction character of each band from a VASP PROCAR file.
Args:
filename (str): Filename of the PROCAR file.
negative_occupancies (:obj:Str, optional): Sets the behaviour for ha... | python | def read_from_file( self, filename, negative_occupancies='warn' ):
"""
Reads the projected wavefunction character of each band from a VASP PROCAR file.
Args:
filename (str): Filename of the PROCAR file.
negative_occupancies (:obj:Str, optional): Sets the behaviour for ha... | [
"def",
"read_from_file",
"(",
"self",
",",
"filename",
",",
"negative_occupancies",
"=",
"'warn'",
")",
":",
"valid_negative_occupancies",
"=",
"[",
"'warn'",
",",
"'raise'",
",",
"'ignore'",
",",
"'zero'",
"]",
"if",
"negative_occupancies",
"not",
"in",
"valid_... | Reads the projected wavefunction character of each band from a VASP PROCAR file.
Args:
filename (str): Filename of the PROCAR file.
negative_occupancies (:obj:Str, optional): Sets the behaviour for handling
negative occupancies. Default is `warn`.
Returns:
... | [
"Reads",
"the",
"projected",
"wavefunction",
"character",
"of",
"each",
"band",
"from",
"a",
"VASP",
"PROCAR",
"file",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/procar.py#L159-L202 | train |
bjmorgan/vasppy | vasppy/summary.py | load_vasp_summary | def load_vasp_summary( filename ):
"""
Reads a `vasp_summary.yaml` format YAML file and returns
a dictionary of dictionaries. Each YAML document in the file
corresponds to one sub-dictionary, with the corresponding
top-level key given by the `title` value.
Example:
The file:
... | python | def load_vasp_summary( filename ):
"""
Reads a `vasp_summary.yaml` format YAML file and returns
a dictionary of dictionaries. Each YAML document in the file
corresponds to one sub-dictionary, with the corresponding
top-level key given by the `title` value.
Example:
The file:
... | [
"def",
"load_vasp_summary",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"stream",
":",
"docs",
"=",
"yaml",
".",
"load_all",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")",
"data",
"=",
"{",
"... | Reads a `vasp_summary.yaml` format YAML file and returns
a dictionary of dictionaries. Each YAML document in the file
corresponds to one sub-dictionary, with the corresponding
top-level key given by the `title` value.
Example:
The file:
---
title: foo
da... | [
"Reads",
"a",
"vasp_summary",
".",
"yaml",
"format",
"YAML",
"file",
"and",
"returns",
"a",
"dictionary",
"of",
"dictionaries",
".",
"Each",
"YAML",
"document",
"in",
"the",
"file",
"corresponds",
"to",
"one",
"sub",
"-",
"dictionary",
"with",
"the",
"corres... | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/summary.py#L18-L51 | train |
bjmorgan/vasppy | vasppy/summary.py | potcar_spec | def potcar_spec( filename ):
"""
Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.
Args:
filename (Str): The name of the POTCAR file to process.
Returns:
(Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.
{ 'Fe_pv': 'PBE... | python | def potcar_spec( filename ):
"""
Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.
Args:
filename (Str): The name of the POTCAR file to process.
Returns:
(Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.
{ 'Fe_pv': 'PBE... | [
"def",
"potcar_spec",
"(",
"filename",
")",
":",
"p_spec",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"potcars",
"=",
"re",
".",
"split",
"(",
"'(End of Dataset\\n)'",
",",
"f",
".",
"read",
"(",
")",
")",
"pot... | Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.
Args:
filename (Str): The name of the POTCAR file to process.
Returns:
(Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.
{ 'Fe_pv': 'PBE_54', 'O', 'PBE_54' } | [
"Returns",
"a",
"dictionary",
"specifying",
"the",
"pseudopotentials",
"contained",
"in",
"a",
"POTCAR",
"file",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/summary.py#L53-L75 | train |
bjmorgan/vasppy | vasppy/summary.py | find_vasp_calculations | def find_vasp_calculations():
"""
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories.
"""
dir_list = [ './' + re.sub( r'vasprun\.xml', '', p... | python | def find_vasp_calculations():
"""
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories.
"""
dir_list = [ './' + re.sub( r'vasprun\.xml', '', p... | [
"def",
"find_vasp_calculations",
"(",
")",
":",
"dir_list",
"=",
"[",
"'./'",
"+",
"re",
".",
"sub",
"(",
"r'vasprun\\.xml'",
",",
"''",
",",
"path",
")",
"for",
"path",
"in",
"glob",
".",
"iglob",
"(",
"'**/vasprun.xml'",
",",
"recursive",
"=",
"True",
... | Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories. | [
"Returns",
"a",
"list",
"of",
"all",
"subdirectories",
"that",
"contain",
"either",
"a",
"vasprun",
".",
"xml",
"file",
"or",
"a",
"compressed",
"vasprun",
".",
"xml",
".",
"gz",
"file",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/summary.py#L77-L90 | train |
bjmorgan/vasppy | vasppy/summary.py | Summary.parse_vasprun | def parse_vasprun( self ):
"""
Read in `vasprun.xml` as a pymatgen Vasprun object.
Args:
None
Returns:
None
None:
If the vasprun.xml is not well formed this method will catch the ParseError
and set self.vasprun = None.
""... | python | def parse_vasprun( self ):
"""
Read in `vasprun.xml` as a pymatgen Vasprun object.
Args:
None
Returns:
None
None:
If the vasprun.xml is not well formed this method will catch the ParseError
and set self.vasprun = None.
""... | [
"def",
"parse_vasprun",
"(",
"self",
")",
":",
"self",
".",
"vasprun_filename",
"=",
"match_filename",
"(",
"'vasprun.xml'",
")",
"if",
"not",
"self",
".",
"vasprun_filename",
":",
"raise",
"FileNotFoundError",
"(",
"'Could not find vasprun.xml or vasprun.xml.gz file'",... | Read in `vasprun.xml` as a pymatgen Vasprun object.
Args:
None
Returns:
None
None:
If the vasprun.xml is not well formed this method will catch the ParseError
and set self.vasprun = None. | [
"Read",
"in",
"vasprun",
".",
"xml",
"as",
"a",
"pymatgen",
"Vasprun",
"object",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/summary.py#L160-L182 | train |
bjmorgan/vasppy | vasppy/doscar.py | Doscar.read_projected_dos | def read_projected_dos( self ):
"""
Read the projected density of states data into """
pdos_list = []
for i in range( self.number_of_atoms ):
df = self.read_atomic_dos_as_df( i+1 )
pdos_list.append( df )
self.pdos = np.vstack( [ np.array( df ) for df in pd... | python | def read_projected_dos( self ):
"""
Read the projected density of states data into """
pdos_list = []
for i in range( self.number_of_atoms ):
df = self.read_atomic_dos_as_df( i+1 )
pdos_list.append( df )
self.pdos = np.vstack( [ np.array( df ) for df in pd... | [
"def",
"read_projected_dos",
"(",
"self",
")",
":",
"pdos_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"number_of_atoms",
")",
":",
"df",
"=",
"self",
".",
"read_atomic_dos_as_df",
"(",
"i",
"+",
"1",
")",
"pdos_list",
".",
"appen... | Read the projected density of states data into | [
"Read",
"the",
"projected",
"density",
"of",
"states",
"data",
"into"
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/doscar.py#L108-L116 | train |
bjmorgan/vasppy | vasppy/doscar.py | Doscar.pdos_select | def pdos_select( self, atoms=None, spin=None, l=None, m=None ):
"""
Returns a subset of the projected density of states array.
Args:
atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1.
Default is to selec... | python | def pdos_select( self, atoms=None, spin=None, l=None, m=None ):
"""
Returns a subset of the projected density of states array.
Args:
atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1.
Default is to selec... | [
"def",
"pdos_select",
"(",
"self",
",",
"atoms",
"=",
"None",
",",
"spin",
"=",
"None",
",",
"l",
"=",
"None",
",",
"m",
"=",
"None",
")",
":",
"valid_m_values",
"=",
"{",
"'s'",
":",
"[",
"]",
",",
"'p'",
":",
"[",
"'x'",
",",
"'y'",
",",
"'... | Returns a subset of the projected density of states array.
Args:
atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1.
Default is to select all atoms.
spin (str): Select up or down, or both spin channels to inc... | [
"Returns",
"a",
"subset",
"of",
"the",
"projected",
"density",
"of",
"states",
"array",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/doscar.py#L118-L183 | train |
bjmorgan/vasppy | vasppy/calculation.py | Calculation.scale_stoichiometry | def scale_stoichiometry( self, scaling ):
"""
Scale the Calculation stoichiometry
Returns the stoichiometry, scaled by the argument scaling.
Args:
scaling (float): The scaling factor.
Returns:
(Counter(Str:Int)): The scaled stoichiometry as a Counter of ... | python | def scale_stoichiometry( self, scaling ):
"""
Scale the Calculation stoichiometry
Returns the stoichiometry, scaled by the argument scaling.
Args:
scaling (float): The scaling factor.
Returns:
(Counter(Str:Int)): The scaled stoichiometry as a Counter of ... | [
"def",
"scale_stoichiometry",
"(",
"self",
",",
"scaling",
")",
":",
"return",
"{",
"k",
":",
"v",
"*",
"scaling",
"for",
"k",
",",
"v",
"in",
"self",
".",
"stoichiometry",
".",
"items",
"(",
")",
"}"
] | Scale the Calculation stoichiometry
Returns the stoichiometry, scaled by the argument scaling.
Args:
scaling (float): The scaling factor.
Returns:
(Counter(Str:Int)): The scaled stoichiometry as a Counter of label: stoichiometry pairs | [
"Scale",
"the",
"Calculation",
"stoichiometry",
"Returns",
"the",
"stoichiometry",
"scaled",
"by",
"the",
"argument",
"scaling",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/calculation.py#L54-L65 | train |
bjmorgan/vasppy | vasppy/cell.py | angle | def angle( x, y ):
"""
Calculate the angle between two vectors, in degrees.
Args:
x (np.array): one vector.
y (np.array): the other vector.
Returns:
(float): the angle between x and y in degrees.
"""
dot = np.dot( x, y )
x_mod = np.linalg.norm( x )
y_mod = ... | python | def angle( x, y ):
"""
Calculate the angle between two vectors, in degrees.
Args:
x (np.array): one vector.
y (np.array): the other vector.
Returns:
(float): the angle between x and y in degrees.
"""
dot = np.dot( x, y )
x_mod = np.linalg.norm( x )
y_mod = ... | [
"def",
"angle",
"(",
"x",
",",
"y",
")",
":",
"dot",
"=",
"np",
".",
"dot",
"(",
"x",
",",
"y",
")",
"x_mod",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"x",
")",
"y_mod",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"y",
")",
"cos_angle",
... | Calculate the angle between two vectors, in degrees.
Args:
x (np.array): one vector.
y (np.array): the other vector.
Returns:
(float): the angle between x and y in degrees. | [
"Calculate",
"the",
"angle",
"between",
"two",
"vectors",
"in",
"degrees",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L4-L19 | train |
bjmorgan/vasppy | vasppy/cell.py | Cell.minimum_image | def minimum_image( self, r1, r2 ):
"""
Find the minimum image vector from point r1 to point r2.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
Returns:
(np.array): the fractional coordinate... | python | def minimum_image( self, r1, r2 ):
"""
Find the minimum image vector from point r1 to point r2.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
Returns:
(np.array): the fractional coordinate... | [
"def",
"minimum_image",
"(",
"self",
",",
"r1",
",",
"r2",
")",
":",
"delta_r",
"=",
"r2",
"-",
"r1",
"delta_r",
"=",
"np",
".",
"array",
"(",
"[",
"x",
"-",
"math",
".",
"copysign",
"(",
"1.0",
",",
"x",
")",
"if",
"abs",
"(",
"x",
")",
">",... | Find the minimum image vector from point r1 to point r2.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
Returns:
(np.array): the fractional coordinate vector from r1 to the nearest image of r2. | [
"Find",
"the",
"minimum",
"image",
"vector",
"from",
"point",
"r1",
"to",
"point",
"r2",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L94-L107 | train |
bjmorgan/vasppy | vasppy/cell.py | Cell.minimum_image_dr | def minimum_image_dr( self, r1, r2, cutoff=None ):
"""
Calculate the shortest distance between two points in the cell,
accounting for periodic boundary conditions.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of ... | python | def minimum_image_dr( self, r1, r2, cutoff=None ):
"""
Calculate the shortest distance between two points in the cell,
accounting for periodic boundary conditions.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of ... | [
"def",
"minimum_image_dr",
"(",
"self",
",",
"r1",
",",
"r2",
",",
"cutoff",
"=",
"None",
")",
":",
"delta_r_vector",
"=",
"self",
".",
"minimum_image",
"(",
"r1",
",",
"r2",
")",
"return",
"(",
"self",
".",
"dr",
"(",
"np",
".",
"zeros",
"(",
"3",... | Calculate the shortest distance between two points in the cell,
accounting for periodic boundary conditions.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
cutoff (:obj: `float`, optional): if set, return ... | [
"Calculate",
"the",
"shortest",
"distance",
"between",
"two",
"points",
"in",
"the",
"cell",
"accounting",
"for",
"periodic",
"boundary",
"conditions",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L109-L123 | train |
bjmorgan/vasppy | vasppy/cell.py | Cell.lengths | def lengths( self ):
"""
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths.
"""
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | python | def lengths( self ):
"""
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths.
"""
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | [
"def",
"lengths",
"(",
"self",
")",
":",
"return",
"(",
"np",
".",
"array",
"(",
"[",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"row",
"**",
"2",
")",
")",
"for",
"row",
"in",
"self",
".",
"matrix",
"]",
")",
")"
] | The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths. | [
"The",
"cell",
"lengths",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L125-L135 | train |
bjmorgan/vasppy | vasppy/cell.py | Cell.inside_cell | def inside_cell( self, r ):
"""
Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell.
Args:
r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries).
Returns:
(np.array): Fracti... | python | def inside_cell( self, r ):
"""
Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell.
Args:
r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries).
Returns:
(np.array): Fracti... | [
"def",
"inside_cell",
"(",
"self",
",",
"r",
")",
":",
"centre",
"=",
"np",
".",
"array",
"(",
"[",
"0.5",
",",
"0.5",
",",
"0.5",
"]",
")",
"new_r",
"=",
"self",
".",
"nearest_image",
"(",
"centre",
",",
"r",
")",
"return",
"new_r"
] | Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell.
Args:
r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries).
Returns:
(np.array): Fractional coordinates of an equivalent point, inside ... | [
"Given",
"a",
"fractional",
"-",
"coordinate",
"if",
"this",
"lies",
"outside",
"the",
"cell",
"return",
"the",
"equivalent",
"point",
"inside",
"the",
"cell",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L174-L186 | train |
bjmorgan/vasppy | vasppy/cell.py | Cell.volume | def volume( self ):
"""
The cell volume.
Args:
None
Returns:
(float): The cell volume.
"""
return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) ) | python | def volume( self ):
"""
The cell volume.
Args:
None
Returns:
(float): The cell volume.
"""
return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) ) | [
"def",
"volume",
"(",
"self",
")",
":",
"return",
"np",
".",
"dot",
"(",
"self",
".",
"matrix",
"[",
"0",
"]",
",",
"np",
".",
"cross",
"(",
"self",
".",
"matrix",
"[",
"1",
"]",
",",
"self",
".",
"matrix",
"[",
"2",
"]",
")",
")"
] | The cell volume.
Args:
None
Returns:
(float): The cell volume. | [
"The",
"cell",
"volume",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/cell.py#L188-L198 | train |
bjmorgan/vasppy | vasppy/vaspmeta.py | VASPMeta.from_file | def from_file( cls, filename ):
"""
Create a VASPMeta object by reading a `vaspmeta.yaml` file
Args:
filename (Str): filename to read in.
Returns:
(vasppy.VASPMeta): the VASPMeta object
"""
with open( filename, 'r' ) as stream:
data =... | python | def from_file( cls, filename ):
"""
Create a VASPMeta object by reading a `vaspmeta.yaml` file
Args:
filename (Str): filename to read in.
Returns:
(vasppy.VASPMeta): the VASPMeta object
"""
with open( filename, 'r' ) as stream:
data =... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"stream",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")",
"notes",
"=",
"da... | Create a VASPMeta object by reading a `vaspmeta.yaml` file
Args:
filename (Str): filename to read in.
Returns:
(vasppy.VASPMeta): the VASPMeta object | [
"Create",
"a",
"VASPMeta",
"object",
"by",
"reading",
"a",
"vaspmeta",
".",
"yaml",
"file"
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/vaspmeta.py#L47-L73 | train |
bjmorgan/vasppy | vasppy/outcar.py | vasp_version_from_outcar | def vasp_version_from_outcar( filename='OUTCAR' ):
"""
Returns the first line from a VASP OUTCAR file, to get the VASP source version string.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(Str): The first line read from the OUTCAR file.
"""
wit... | python | def vasp_version_from_outcar( filename='OUTCAR' ):
"""
Returns the first line from a VASP OUTCAR file, to get the VASP source version string.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(Str): The first line read from the OUTCAR file.
"""
wit... | [
"def",
"vasp_version_from_outcar",
"(",
"filename",
"=",
"'OUTCAR'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"return",
"line"
] | Returns the first line from a VASP OUTCAR file, to get the VASP source version string.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(Str): The first line read from the OUTCAR file. | [
"Returns",
"the",
"first",
"line",
"from",
"a",
"VASP",
"OUTCAR",
"file",
"to",
"get",
"the",
"VASP",
"source",
"version",
"string",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/outcar.py#L41-L53 | train |
bjmorgan/vasppy | vasppy/outcar.py | potcar_eatom_list_from_outcar | def potcar_eatom_list_from_outcar( filename='OUTCAR' ):
"""
Returns a list of EATOM values for the pseudopotentials used.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(List(Float)): A list of EATOM values, in the order they appear in the OUTCAR.
"... | python | def potcar_eatom_list_from_outcar( filename='OUTCAR' ):
"""
Returns a list of EATOM values for the pseudopotentials used.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(List(Float)): A list of EATOM values, in the order they appear in the OUTCAR.
"... | [
"def",
"potcar_eatom_list_from_outcar",
"(",
"filename",
"=",
"'OUTCAR'",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"outcar",
"=",
"f",
".",
"read",
"(",
")",
"eatom_re",
"=",
"re",
".",
"compile",
"(",
"\"energy of atom\\s+\\d+\\s+EATO... | Returns a list of EATOM values for the pseudopotentials used.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(List(Float)): A list of EATOM values, in the order they appear in the OUTCAR. | [
"Returns",
"a",
"list",
"of",
"EATOM",
"values",
"for",
"the",
"pseudopotentials",
"used",
"."
] | cc2d1449697b17ee1c43715a02cddcb1139a6834 | https://github.com/bjmorgan/vasppy/blob/cc2d1449697b17ee1c43715a02cddcb1139a6834/vasppy/outcar.py#L55-L69 | train |
brandon-rhodes/logging_tree | logging_tree/format.py | build_description | def build_description(node=None):
"""Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out.
"""
if node is None:
from logging_tree.nodes import tree
node = tree... | python | def build_description(node=None):
"""Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out.
"""
if node is None:
from logging_tree.nodes import tree
node = tree... | [
"def",
"build_description",
"(",
"node",
"=",
"None",
")",
":",
"if",
"node",
"is",
"None",
":",
"from",
"logging_tree",
".",
"nodes",
"import",
"tree",
"node",
"=",
"tree",
"(",
")",
"return",
"'\\n'",
".",
"join",
"(",
"[",
"line",
".",
"rstrip",
"... | Return a multi-line string describing a `logging_tree.nodes.Node`.
If no `node` argument is provided, then the entire tree of currently
active `logging` loggers is printed out. | [
"Return",
"a",
"multi",
"-",
"line",
"string",
"describing",
"a",
"logging_tree",
".",
"nodes",
".",
"Node",
"."
] | 8513cf85b3bf8ff1b58e54c73718a41ef6524a4c | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/format.py#L20-L30 | train |
brandon-rhodes/logging_tree | logging_tree/format.py | _describe | def _describe(node, parent):
"""Generate lines describing the given `node` tuple.
This is the recursive back-end that powers ``describe()``. With its
extra ``parent`` parameter, this routine remembers the nearest
non-placeholder ancestor so that it can compare it against the
actual value of the ``... | python | def _describe(node, parent):
"""Generate lines describing the given `node` tuple.
This is the recursive back-end that powers ``describe()``. With its
extra ``parent`` parameter, this routine remembers the nearest
non-placeholder ancestor so that it can compare it against the
actual value of the ``... | [
"def",
"_describe",
"(",
"node",
",",
"parent",
")",
":",
"name",
",",
"logger",
",",
"children",
"=",
"node",
"is_placeholder",
"=",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"PlaceHolder",
")",
"if",
"is_placeholder",
":",
"yield",
"'<--[%s]'",
"... | Generate lines describing the given `node` tuple.
This is the recursive back-end that powers ``describe()``. With its
extra ``parent`` parameter, this routine remembers the nearest
non-placeholder ancestor so that it can compare it against the
actual value of the ``.parent`` attribute of each node. | [
"Generate",
"lines",
"describing",
"the",
"given",
"node",
"tuple",
"."
] | 8513cf85b3bf8ff1b58e54c73718a41ef6524a4c | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/format.py#L41-L104 | train |
brandon-rhodes/logging_tree | logging_tree/format.py | describe_filter | def describe_filter(f):
"""Return text describing the logging filter `f`."""
if f.__class__ is logging.Filter: # using type() breaks in Python <= 2.6
return 'name=%r' % f.name
return repr(f) | python | def describe_filter(f):
"""Return text describing the logging filter `f`."""
if f.__class__ is logging.Filter: # using type() breaks in Python <= 2.6
return 'name=%r' % f.name
return repr(f) | [
"def",
"describe_filter",
"(",
"f",
")",
":",
"if",
"f",
".",
"__class__",
"is",
"logging",
".",
"Filter",
":",
"return",
"'name=%r'",
"%",
"f",
".",
"name",
"return",
"repr",
"(",
"f",
")"
] | Return text describing the logging filter `f`. | [
"Return",
"text",
"describing",
"the",
"logging",
"filter",
"f",
"."
] | 8513cf85b3bf8ff1b58e54c73718a41ef6524a4c | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/format.py#L112-L116 | train |
brandon-rhodes/logging_tree | logging_tree/format.py | describe_handler | def describe_handler(h):
"""Yield one or more lines describing the logging handler `h`."""
t = h.__class__ # using type() breaks in Python <= 2.6
format = handler_formats.get(t)
if format is not None:
yield format % h.__dict__
else:
yield repr(h)
level = getattr(h, 'level', logg... | python | def describe_handler(h):
"""Yield one or more lines describing the logging handler `h`."""
t = h.__class__ # using type() breaks in Python <= 2.6
format = handler_formats.get(t)
if format is not None:
yield format % h.__dict__
else:
yield repr(h)
level = getattr(h, 'level', logg... | [
"def",
"describe_handler",
"(",
"h",
")",
":",
"t",
"=",
"h",
".",
"__class__",
"format",
"=",
"handler_formats",
".",
"get",
"(",
"t",
")",
"if",
"format",
"is",
"not",
"None",
":",
"yield",
"format",
"%",
"h",
".",
"__dict__",
"else",
":",
"yield",... | Yield one or more lines describing the logging handler `h`. | [
"Yield",
"one",
"or",
"more",
"lines",
"describing",
"the",
"logging",
"handler",
"h",
"."
] | 8513cf85b3bf8ff1b58e54c73718a41ef6524a4c | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/format.py#L144-L170 | train |
brandon-rhodes/logging_tree | logging_tree/nodes.py | tree | def tree():
"""Return a tree of tuples representing the logger layout.
Each tuple looks like ``('logger-name', <Logger>, [...])`` where the
third element is a list of zero or more child tuples that share the
same layout.
"""
root = ('', logging.root, [])
nodes = {}
items = list(logging... | python | def tree():
"""Return a tree of tuples representing the logger layout.
Each tuple looks like ``('logger-name', <Logger>, [...])`` where the
third element is a list of zero or more child tuples that share the
same layout.
"""
root = ('', logging.root, [])
nodes = {}
items = list(logging... | [
"def",
"tree",
"(",
")",
":",
"root",
"=",
"(",
"''",
",",
"logging",
".",
"root",
",",
"[",
"]",
")",
"nodes",
"=",
"{",
"}",
"items",
"=",
"list",
"(",
"logging",
".",
"root",
".",
"manager",
".",
"loggerDict",
".",
"items",
"(",
")",
")",
... | Return a tree of tuples representing the logger layout.
Each tuple looks like ``('logger-name', <Logger>, [...])`` where the
third element is a list of zero or more child tuples that share the
same layout. | [
"Return",
"a",
"tree",
"of",
"tuples",
"representing",
"the",
"logger",
"layout",
"."
] | 8513cf85b3bf8ff1b58e54c73718a41ef6524a4c | https://github.com/brandon-rhodes/logging_tree/blob/8513cf85b3bf8ff1b58e54c73718a41ef6524a4c/logging_tree/nodes.py#L5-L25 | train |
signalwire/signalwire-python | signalwire/rest/__init__.py | patched_str | def patched_str(self):
""" Try to pretty-print the exception, if this is going on screen. """
def red(words):
return u("\033[31m\033[49m%s\033[0m") % words
def white(words):
return u("\033[37m\033[49m%s\033[0m") % words
def blue(words):
return u("\033[34m\033[49m%s\033[0m") % words
... | python | def patched_str(self):
""" Try to pretty-print the exception, if this is going on screen. """
def red(words):
return u("\033[31m\033[49m%s\033[0m") % words
def white(words):
return u("\033[37m\033[49m%s\033[0m") % words
def blue(words):
return u("\033[34m\033[49m%s\033[0m") % words
... | [
"def",
"patched_str",
"(",
"self",
")",
":",
"def",
"red",
"(",
"words",
")",
":",
"return",
"u",
"(",
"\"\\033[31m\\033[49m%s\\033[0m\"",
")",
"%",
"words",
"def",
"white",
"(",
"words",
")",
":",
"return",
"u",
"(",
"\"\\033[37m\\033[49m%s\\033[0m\"",
")",... | Try to pretty-print the exception, if this is going on screen. | [
"Try",
"to",
"pretty",
"-",
"print",
"the",
"exception",
"if",
"this",
"is",
"going",
"on",
"screen",
"."
] | 71eebb38d23f39f5de716991ca49128a6084b75d | https://github.com/signalwire/signalwire-python/blob/71eebb38d23f39f5de716991ca49128a6084b75d/signalwire/rest/__init__.py#L27-L66 | train |
QInfer/python-qinfer | src/qinfer/score.py | ScoreMixin.h | def h(self):
r"""
Returns the step size to be used in numerical differentiation with
respect to the model parameters.
The step size is given as a vector with length ``n_modelparams`` so
that each model parameter can be weighted independently.
"""
if np.... | python | def h(self):
r"""
Returns the step size to be used in numerical differentiation with
respect to the model parameters.
The step size is given as a vector with length ``n_modelparams`` so
that each model parameter can be weighted independently.
"""
if np.... | [
"def",
"h",
"(",
"self",
")",
":",
"r",
"if",
"np",
".",
"size",
"(",
"self",
".",
"_h",
")",
">",
"1",
":",
"assert",
"np",
".",
"size",
"(",
"self",
".",
"_h",
")",
"==",
"self",
".",
"n_modelparams",
"return",
"self",
".",
"_h",
"else",
":... | r"""
Returns the step size to be used in numerical differentiation with
respect to the model parameters.
The step size is given as a vector with length ``n_modelparams`` so
that each model parameter can be weighted independently. | [
"r",
"Returns",
"the",
"step",
"size",
"to",
"be",
"used",
"in",
"numerical",
"differentiation",
"with",
"respect",
"to",
"the",
"model",
"parameters",
".",
"The",
"step",
"size",
"is",
"given",
"as",
"a",
"vector",
"with",
"length",
"n_modelparams",
"so",
... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/score.py#L62-L74 | train |
QInfer/python-qinfer | src/qinfer/parallel.py | DirectViewParallelizedModel.clear_cache | def clear_cache(self):
"""
Clears any cache associated with the serial model and the engines
seen by the direct view.
"""
self.underlying_model.clear_cache()
try:
logger.info('DirectView results has {} items. Clearing.'.format(
len(self._dv.res... | python | def clear_cache(self):
"""
Clears any cache associated with the serial model and the engines
seen by the direct view.
"""
self.underlying_model.clear_cache()
try:
logger.info('DirectView results has {} items. Clearing.'.format(
len(self._dv.res... | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"self",
".",
"underlying_model",
".",
"clear_cache",
"(",
")",
"try",
":",
"logger",
".",
"info",
"(",
"'DirectView results has {} items. Clearing.'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_dv",
".",
"resu... | Clears any cache associated with the serial model and the engines
seen by the direct view. | [
"Clears",
"any",
"cache",
"associated",
"with",
"the",
"serial",
"model",
"and",
"the",
"engines",
"seen",
"by",
"the",
"direct",
"view",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/parallel.py#L167-L181 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater._maybe_resample | def _maybe_resample(self):
"""
Checks the resample threshold and conditionally resamples.
"""
ess = self.n_ess
if ess <= 10:
warnings.warn(
"Extremely small n_ess encountered ({}). "
"Resampling is likely to fail. Consider adding partic... | python | def _maybe_resample(self):
"""
Checks the resample threshold and conditionally resamples.
"""
ess = self.n_ess
if ess <= 10:
warnings.warn(
"Extremely small n_ess encountered ({}). "
"Resampling is likely to fail. Consider adding partic... | [
"def",
"_maybe_resample",
"(",
"self",
")",
":",
"ess",
"=",
"self",
".",
"n_ess",
"if",
"ess",
"<=",
"10",
":",
"warnings",
".",
"warn",
"(",
"\"Extremely small n_ess encountered ({}). \"",
"\"Resampling is likely to fail. Consider adding particles, or \"",
"\"resampling... | Checks the resample threshold and conditionally resamples. | [
"Checks",
"the",
"resample",
"threshold",
"and",
"conditionally",
"resamples",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L263-L277 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.reset | def reset(self, n_particles=None, only_params=None, reset_weights=True):
"""
Causes all particle locations and weights to be drawn fresh from the
initial prior.
:param int n_particles: Forces the size of the new particle set. If
`None`, the size of the particle set is not ch... | python | def reset(self, n_particles=None, only_params=None, reset_weights=True):
"""
Causes all particle locations and weights to be drawn fresh from the
initial prior.
:param int n_particles: Forces the size of the new particle set. If
`None`, the size of the particle set is not ch... | [
"def",
"reset",
"(",
"self",
",",
"n_particles",
"=",
"None",
",",
"only_params",
"=",
"None",
",",
"reset_weights",
"=",
"True",
")",
":",
"if",
"n_particles",
"is",
"not",
"None",
"and",
"only_params",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"... | Causes all particle locations and weights to be drawn fresh from the
initial prior.
:param int n_particles: Forces the size of the new particle set. If
`None`, the size of the particle set is not changed.
:param slice only_params: Resets only some of the parameters. Cannot
... | [
"Causes",
"all",
"particle",
"locations",
"and",
"weights",
"to",
"be",
"drawn",
"fresh",
"from",
"the",
"initial",
"prior",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L281-L320 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.batch_update | def batch_update(self, outcomes, expparams, resample_interval=5):
r"""
Updates based on a batch of outcomes and experiments, rather than just
one.
:param numpy.ndarray outcomes: An array of outcomes of the experiments that
were performed.
:param numpy.ndarray exppara... | python | def batch_update(self, outcomes, expparams, resample_interval=5):
r"""
Updates based on a batch of outcomes and experiments, rather than just
one.
:param numpy.ndarray outcomes: An array of outcomes of the experiments that
were performed.
:param numpy.ndarray exppara... | [
"def",
"batch_update",
"(",
"self",
",",
"outcomes",
",",
"expparams",
",",
"resample_interval",
"=",
"5",
")",
":",
"r",
"n_exps",
"=",
"outcomes",
".",
"shape",
"[",
"0",
"]",
"if",
"expparams",
".",
"shape",
"[",
"0",
"]",
"!=",
"n_exps",
":",
"ra... | r"""
Updates based on a batch of outcomes and experiments, rather than just
one.
:param numpy.ndarray outcomes: An array of outcomes of the experiments that
were performed.
:param numpy.ndarray expparams: Either a scalar or record single-index
array of experiment... | [
"r",
"Updates",
"based",
"on",
"a",
"batch",
"of",
"outcomes",
"and",
"experiments",
"rather",
"than",
"just",
"one",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L459-L487 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.resample | def resample(self):
"""
Forces the updater to perform a resampling step immediately.
"""
if self.just_resampled:
warnings.warn(
"Resampling without additional data; this may not perform as "
"desired.",
ResamplerWarning
... | python | def resample(self):
"""
Forces the updater to perform a resampling step immediately.
"""
if self.just_resampled:
warnings.warn(
"Resampling without additional data; this may not perform as "
"desired.",
ResamplerWarning
... | [
"def",
"resample",
"(",
"self",
")",
":",
"if",
"self",
".",
"just_resampled",
":",
"warnings",
".",
"warn",
"(",
"\"Resampling without additional data; this may not perform as \"",
"\"desired.\"",
",",
"ResamplerWarning",
")",
"self",
".",
"_just_resampled",
"=",
"Tr... | Forces the updater to perform a resampling step immediately. | [
"Forces",
"the",
"updater",
"to",
"perform",
"a",
"resampling",
"step",
"immediately",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L491-L551 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.expected_information_gain | def expected_information_gain(self, expparams):
r"""
Calculates the expected information gain for each hypothetical experiment.
:param expparams: The experiments at which to compute expected
information gain.
:type expparams: :class:`~numpy.ndarray` of dtype given by the cur... | python | def expected_information_gain(self, expparams):
r"""
Calculates the expected information gain for each hypothetical experiment.
:param expparams: The experiments at which to compute expected
information gain.
:type expparams: :class:`~numpy.ndarray` of dtype given by the cur... | [
"def",
"expected_information_gain",
"(",
"self",
",",
"expparams",
")",
":",
"r",
"n_eps",
"=",
"expparams",
".",
"size",
"if",
"n_eps",
">",
"1",
"and",
"not",
"self",
".",
"model",
".",
"is_n_outcomes_constant",
":",
"risk",
"=",
"np",
".",
"empty",
"(... | r"""
Calculates the expected information gain for each hypothetical experiment.
:param expparams: The experiments at which to compute expected
information gain.
:type expparams: :class:`~numpy.ndarray` of dtype given by the current
model's :attr:`~qinfer.abstract_model.S... | [
"r",
"Calculates",
"the",
"expected",
"information",
"gain",
"for",
"each",
"hypothetical",
"experiment",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L614-L663 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.posterior_marginal | def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None):
"""
Returns an estimate of the marginal distribution of a given model parameter, based on
taking the derivative of the interpolated cdf.
:param int idx_param: Index of parameter to be margin... | python | def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None):
"""
Returns an estimate of the marginal distribution of a given model parameter, based on
taking the derivative of the interpolated cdf.
:param int idx_param: Index of parameter to be margin... | [
"def",
"posterior_marginal",
"(",
"self",
",",
"idx_param",
"=",
"0",
",",
"res",
"=",
"100",
",",
"smoothing",
"=",
"0",
",",
"range_min",
"=",
"None",
",",
"range_max",
"=",
"None",
")",
":",
"s",
"=",
"np",
".",
"argsort",
"(",
"self",
".",
"par... | Returns an estimate of the marginal distribution of a given model parameter, based on
taking the derivative of the interpolated cdf.
:param int idx_param: Index of parameter to be marginalized.
:param int res1: Resolution of of the axis.
:param float smoothing: Standard deviation of the... | [
"Returns",
"an",
"estimate",
"of",
"the",
"marginal",
"distribution",
"of",
"a",
"given",
"model",
"parameter",
"based",
"on",
"taking",
"the",
"derivative",
"of",
"the",
"interpolated",
"cdf",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L672-L716 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.plot_posterior_marginal | def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0,
range_min=None, range_max=None, label_xaxis=True,
other_plot_args={}, true_model=None
):
"""
Plots a marginal of the requested parameter.
:param int idx_param: Index of parameter to be marginali... | python | def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0,
range_min=None, range_max=None, label_xaxis=True,
other_plot_args={}, true_model=None
):
"""
Plots a marginal of the requested parameter.
:param int idx_param: Index of parameter to be marginali... | [
"def",
"plot_posterior_marginal",
"(",
"self",
",",
"idx_param",
"=",
"0",
",",
"res",
"=",
"100",
",",
"smoothing",
"=",
"0",
",",
"range_min",
"=",
"None",
",",
"range_max",
"=",
"None",
",",
"label_xaxis",
"=",
"True",
",",
"other_plot_args",
"=",
"{"... | Plots a marginal of the requested parameter.
:param int idx_param: Index of parameter to be marginalized.
:param int res1: Resolution of of the axis.
:param float smoothing: Standard deviation of the Gaussian kernel
used to smooth; same units as parameter.
:param float range... | [
"Plots",
"a",
"marginal",
"of",
"the",
"requested",
"parameter",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L718-L754 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.plot_covariance | def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None):
"""
Plots the covariance matrix of the posterior as a Hinton diagram.
.. note::
This function requires that mpltools is installed.
:param bool corr: If `True`, the covariance matri... | python | def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None):
"""
Plots the covariance matrix of the posterior as a Hinton diagram.
.. note::
This function requires that mpltools is installed.
:param bool corr: If `True`, the covariance matri... | [
"def",
"plot_covariance",
"(",
"self",
",",
"corr",
"=",
"False",
",",
"param_slice",
"=",
"None",
",",
"tick_labels",
"=",
"None",
",",
"tick_params",
"=",
"None",
")",
":",
"if",
"mpls",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"Hinton diagrams ... | Plots the covariance matrix of the posterior as a Hinton diagram.
.. note::
This function requires that mpltools is installed.
:param bool corr: If `True`, the covariance matrix is first normalized
by the outer product of the square root diagonal of the covariance matrix
... | [
"Plots",
"the",
"covariance",
"matrix",
"of",
"the",
"posterior",
"as",
"a",
"Hinton",
"diagram",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L756-L792 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.posterior_mesh | def posterior_mesh(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
"""
Returns a mesh, useful for plotting, of kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
... | python | def posterior_mesh(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
"""
Returns a mesh, useful for plotting, of kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
... | [
"def",
"posterior_mesh",
"(",
"self",
",",
"idx_param1",
"=",
"0",
",",
"idx_param2",
"=",
"1",
",",
"res1",
"=",
"100",
",",
"res2",
"=",
"100",
",",
"smoothing",
"=",
"0.01",
")",
":",
"locs",
"=",
"self",
".",
"particle_locations",
"[",
":",
",",
... | Returns a mesh, useful for plotting, of kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
plotting.
:param int idx_param2: Parameter to be treated as :math:`y` when
plottin... | [
"Returns",
"a",
"mesh",
"useful",
"for",
"plotting",
"of",
"kernel",
"density",
"estimation",
"of",
"a",
"2D",
"projection",
"of",
"the",
"current",
"posterior",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L795-L838 | train |
QInfer/python-qinfer | src/qinfer/smc.py | SMCUpdater.plot_posterior_contour | def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
"""
Plots a contour of the kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
p... | python | def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
"""
Plots a contour of the kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
p... | [
"def",
"plot_posterior_contour",
"(",
"self",
",",
"idx_param1",
"=",
"0",
",",
"idx_param2",
"=",
"1",
",",
"res1",
"=",
"100",
",",
"res2",
"=",
"100",
",",
"smoothing",
"=",
"0.01",
")",
":",
"return",
"plt",
".",
"contour",
"(",
"*",
"self",
".",... | Plots a contour of the kernel density estimation
of a 2D projection of the current posterior distribution.
:param int idx_param1: Parameter to be treated as :math:`x` when
plotting.
:param int idx_param2: Parameter to be treated as :math:`y` when
plotting.
:param... | [
"Plots",
"a",
"contour",
"of",
"the",
"kernel",
"density",
"estimation",
"of",
"a",
"2D",
"projection",
"of",
"the",
"current",
"posterior",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/smc.py#L840-L858 | train |
QInfer/python-qinfer | src/qinfer/tomography/plotting_tools.py | plot_rebit_prior | def plot_rebit_prior(prior, rebit_axes=REBIT_AXES,
n_samples=2000, true_state=None, true_size=250,
force_mean=None,
legend=True,
mean_color_index=2
):
"""
Plots rebit states drawn from a given prior.
:param qinfer.tomography.DensityOperatorDistribution prior: Distributio... | python | def plot_rebit_prior(prior, rebit_axes=REBIT_AXES,
n_samples=2000, true_state=None, true_size=250,
force_mean=None,
legend=True,
mean_color_index=2
):
"""
Plots rebit states drawn from a given prior.
:param qinfer.tomography.DensityOperatorDistribution prior: Distributio... | [
"def",
"plot_rebit_prior",
"(",
"prior",
",",
"rebit_axes",
"=",
"REBIT_AXES",
",",
"n_samples",
"=",
"2000",
",",
"true_state",
"=",
"None",
",",
"true_size",
"=",
"250",
",",
"force_mean",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"mean_color_index",
... | Plots rebit states drawn from a given prior.
:param qinfer.tomography.DensityOperatorDistribution prior: Distribution over
rebit states to plot.
:param list rebit_axes: List containing indices for the :math:`x`
and :math:`z` axes.
:param int n_samples: Number of samples to draw from the
... | [
"Plots",
"rebit",
"states",
"drawn",
"from",
"a",
"given",
"prior",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/plotting_tools.py#L156-L202 | train |
QInfer/python-qinfer | src/qinfer/tomography/plotting_tools.py | plot_rebit_posterior | def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250,
legend=True,
level=0.95,
region_est_method='cov'
):
"""
Plots posterior distributions over rebits, including covariance ellipsoids
:param qinfer.smc.SMCUpdat... | python | def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250,
legend=True,
level=0.95,
region_est_method='cov'
):
"""
Plots posterior distributions over rebits, including covariance ellipsoids
:param qinfer.smc.SMCUpdat... | [
"def",
"plot_rebit_posterior",
"(",
"updater",
",",
"prior",
"=",
"None",
",",
"true_state",
"=",
"None",
",",
"n_std",
"=",
"3",
",",
"rebit_axes",
"=",
"REBIT_AXES",
",",
"true_size",
"=",
"250",
",",
"legend",
"=",
"True",
",",
"level",
"=",
"0.95",
... | Plots posterior distributions over rebits, including covariance ellipsoids
:param qinfer.smc.SMCUpdater updater: Posterior distribution over rebits.
:param qinfer.tomography.DensityOperatorDistribution: Prior distribution
over rebit states.
:param np.ndarray true_state: Model parameters for "true" ... | [
"Plots",
"posterior",
"distributions",
"over",
"rebits",
"including",
"covariance",
"ellipsoids"
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/plotting_tools.py#L205-L291 | train |
QInfer/python-qinfer | src/qinfer/simple_est.py | data_to_params | def data_to_params(data,
expparams_dtype,
col_outcomes=(0, 'counts'),
cols_expparams=None
):
"""
Given data as a NumPy array, separates out each column either as
the outcomes, or as a field of an expparams array. Columns may be specified
either as indices into a two-axis scal... | python | def data_to_params(data,
expparams_dtype,
col_outcomes=(0, 'counts'),
cols_expparams=None
):
"""
Given data as a NumPy array, separates out each column either as
the outcomes, or as a field of an expparams array. Columns may be specified
either as indices into a two-axis scal... | [
"def",
"data_to_params",
"(",
"data",
",",
"expparams_dtype",
",",
"col_outcomes",
"=",
"(",
"0",
",",
"'counts'",
")",
",",
"cols_expparams",
"=",
"None",
")",
":",
"BY_IDX",
",",
"BY_NAME",
"=",
"range",
"(",
"2",
")",
"is_exp_scalar",
"=",
"np",
".",
... | Given data as a NumPy array, separates out each column either as
the outcomes, or as a field of an expparams array. Columns may be specified
either as indices into a two-axis scalar array, or as field names for a one-axis
record array.
Since scalar arrays are homogenous in type, this may result in loss... | [
"Given",
"data",
"as",
"a",
"NumPy",
"array",
"separates",
"out",
"each",
"column",
"either",
"as",
"the",
"outcomes",
"or",
"as",
"a",
"field",
"of",
"an",
"expparams",
"array",
".",
"Columns",
"may",
"be",
"specified",
"either",
"as",
"indices",
"into",
... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/simple_est.py#L70-L106 | train |
QInfer/python-qinfer | src/qinfer/tomography/models.py | TomographyModel.canonicalize | def canonicalize(self, modelparams):
"""
Truncates negative eigenvalues and from each
state represented by a tensor of model parameter
vectors, and renormalizes as appropriate.
:param np.ndarray modelparams: Array of shape
``(n_states, dim**2)`` containing model para... | python | def canonicalize(self, modelparams):
"""
Truncates negative eigenvalues and from each
state represented by a tensor of model parameter
vectors, and renormalizes as appropriate.
:param np.ndarray modelparams: Array of shape
``(n_states, dim**2)`` containing model para... | [
"def",
"canonicalize",
"(",
"self",
",",
"modelparams",
")",
":",
"modelparams",
"=",
"np",
".",
"apply_along_axis",
"(",
"self",
".",
"trunc_neg_eigs",
",",
"1",
",",
"modelparams",
")",
"if",
"not",
"self",
".",
"_allow_subnormalied",
":",
"modelparams",
"... | Truncates negative eigenvalues and from each
state represented by a tensor of model parameter
vectors, and renormalizes as appropriate.
:param np.ndarray modelparams: Array of shape
``(n_states, dim**2)`` containing model parameter
representations of each of ``n_states``... | [
"Truncates",
"negative",
"eigenvalues",
"and",
"from",
"each",
"state",
"represented",
"by",
"a",
"tensor",
"of",
"model",
"parameter",
"vectors",
"and",
"renormalizes",
"as",
"appropriate",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L149-L170 | train |
QInfer/python-qinfer | src/qinfer/tomography/models.py | TomographyModel.trunc_neg_eigs | def trunc_neg_eigs(self, particle):
"""
Given a state represented as a model parameter vector,
returns a model parameter vector representing the same
state with any negative eigenvalues set to zero.
:param np.ndarray particle: Vector of length ``(dim ** 2, )``
repres... | python | def trunc_neg_eigs(self, particle):
"""
Given a state represented as a model parameter vector,
returns a model parameter vector representing the same
state with any negative eigenvalues set to zero.
:param np.ndarray particle: Vector of length ``(dim ** 2, )``
repres... | [
"def",
"trunc_neg_eigs",
"(",
"self",
",",
"particle",
")",
":",
"arr",
"=",
"np",
".",
"tensordot",
"(",
"particle",
",",
"self",
".",
"_basis",
".",
"data",
".",
"conj",
"(",
")",
",",
"1",
")",
"w",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"... | Given a state represented as a model parameter vector,
returns a model parameter vector representing the same
state with any negative eigenvalues set to zero.
:param np.ndarray particle: Vector of length ``(dim ** 2, )``
representing a state.
:return: The same state with any... | [
"Given",
"a",
"state",
"represented",
"as",
"a",
"model",
"parameter",
"vector",
"returns",
"a",
"model",
"parameter",
"vector",
"representing",
"the",
"same",
"state",
"with",
"any",
"negative",
"eigenvalues",
"set",
"to",
"zero",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L172-L192 | train |
QInfer/python-qinfer | src/qinfer/tomography/models.py | TomographyModel.renormalize | def renormalize(self, modelparams):
"""
Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model para... | python | def renormalize(self, modelparams):
"""
Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model para... | [
"def",
"renormalize",
"(",
"self",
",",
"modelparams",
")",
":",
"norm",
"=",
"modelparams",
"[",
":",
",",
"0",
"]",
"*",
"np",
".",
"sqrt",
"(",
"self",
".",
"_dim",
")",
"assert",
"not",
"np",
".",
"sum",
"(",
"norm",
"==",
"0",
")",
"return",... | Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model parameter vectors.
:return: The same state, normaliz... | [
"Renormalizes",
"one",
"or",
"more",
"states",
"represented",
"as",
"model",
"parameter",
"vectors",
"such",
"that",
"each",
"state",
"has",
"trace",
"1",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/models.py#L194-L209 | train |
QInfer/python-qinfer | src/qinfer/domains.py | ProductDomain.values | def values(self):
"""
Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray`
"""
separate_values = [domain.valu... | python | def values(self):
"""
Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray`
"""
separate_values = [domain.valu... | [
"def",
"values",
"(",
"self",
")",
":",
"separate_values",
"=",
"[",
"domain",
".",
"values",
"for",
"domain",
"in",
"self",
".",
"_domains",
"]",
"return",
"np",
".",
"concatenate",
"(",
"[",
"join_struct_arrays",
"(",
"list",
"(",
"map",
"(",
"np",
"... | Returns an `np.array` of type `dtype` containing
some values from the domain.
For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once.
:rtype: `np.ndarray` | [
"Returns",
"an",
"np",
".",
"array",
"of",
"type",
"dtype",
"containing",
"some",
"values",
"from",
"the",
"domain",
".",
"For",
"domains",
"where",
"is_finite",
"is",
"True",
"all",
"elements",
"of",
"the",
"domain",
"will",
"be",
"yielded",
"exactly",
"o... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L238-L251 | train |
QInfer/python-qinfer | src/qinfer/domains.py | IntegerDomain.min | def min(self):
"""
Returns the minimum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._min) if not np.isinf(self._min) else self._min | python | def min(self):
"""
Returns the minimum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._min) if not np.isinf(self._min) else self._min | [
"def",
"min",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_min",
")",
"if",
"not",
"np",
".",
"isinf",
"(",
"self",
".",
"_min",
")",
"else",
"self",
".",
"_min"
] | Returns the minimum value of the domain.
:rtype: `float` or `np.inf` | [
"Returns",
"the",
"minimum",
"value",
"of",
"the",
"domain",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L448-L454 | train |
QInfer/python-qinfer | src/qinfer/domains.py | IntegerDomain.max | def max(self):
"""
Returns the maximum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._max) if not np.isinf(self._max) else self._max | python | def max(self):
"""
Returns the maximum value of the domain.
:rtype: `float` or `np.inf`
"""
return int(self._max) if not np.isinf(self._max) else self._max | [
"def",
"max",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"_max",
")",
"if",
"not",
"np",
".",
"isinf",
"(",
"self",
".",
"_max",
")",
"else",
"self",
".",
"_max"
] | Returns the maximum value of the domain.
:rtype: `float` or `np.inf` | [
"Returns",
"the",
"maximum",
"value",
"of",
"the",
"domain",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L456-L462 | train |
QInfer/python-qinfer | src/qinfer/domains.py | IntegerDomain.is_finite | def is_finite(self):
"""
Whether or not the domain contains a finite number of points.
:type: `bool`
"""
return not np.isinf(self.min) and not np.isinf(self.max) | python | def is_finite(self):
"""
Whether or not the domain contains a finite number of points.
:type: `bool`
"""
return not np.isinf(self.min) and not np.isinf(self.max) | [
"def",
"is_finite",
"(",
"self",
")",
":",
"return",
"not",
"np",
".",
"isinf",
"(",
"self",
".",
"min",
")",
"and",
"not",
"np",
".",
"isinf",
"(",
"self",
".",
"max",
")"
] | Whether or not the domain contains a finite number of points.
:type: `bool` | [
"Whether",
"or",
"not",
"the",
"domain",
"contains",
"a",
"finite",
"number",
"of",
"points",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L475-L481 | train |
QInfer/python-qinfer | src/qinfer/domains.py | MultinomialDomain.n_members | def n_members(self):
"""
Returns the number of members in the domain if it
`is_finite`, otherwise, returns `None`.
:type: ``int``
"""
return int(binom(self.n_meas + self.n_elements -1, self.n_elements - 1)) | python | def n_members(self):
"""
Returns the number of members in the domain if it
`is_finite`, otherwise, returns `None`.
:type: ``int``
"""
return int(binom(self.n_meas + self.n_elements -1, self.n_elements - 1)) | [
"def",
"n_members",
"(",
"self",
")",
":",
"return",
"int",
"(",
"binom",
"(",
"self",
".",
"n_meas",
"+",
"self",
".",
"n_elements",
"-",
"1",
",",
"self",
".",
"n_elements",
"-",
"1",
")",
")"
] | Returns the number of members in the domain if it
`is_finite`, otherwise, returns `None`.
:type: ``int`` | [
"Returns",
"the",
"number",
"of",
"members",
"in",
"the",
"domain",
"if",
"it",
"is_finite",
"otherwise",
"returns",
"None",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L619-L626 | train |
QInfer/python-qinfer | src/qinfer/domains.py | MultinomialDomain.to_regular_array | def to_regular_array(self, A):
"""
Converts from an array of type `self.dtype` to an array
of type `int` with an additional index labeling the
tuple indeces.
:param np.ndarray A: An `np.array` of type `self.dtype`.
:rtype: `np.ndarray`
"""
# this could b... | python | def to_regular_array(self, A):
"""
Converts from an array of type `self.dtype` to an array
of type `int` with an additional index labeling the
tuple indeces.
:param np.ndarray A: An `np.array` of type `self.dtype`.
:rtype: `np.ndarray`
"""
# this could b... | [
"def",
"to_regular_array",
"(",
"self",
",",
"A",
")",
":",
"return",
"A",
".",
"view",
"(",
"(",
"int",
",",
"len",
"(",
"A",
".",
"dtype",
".",
"names",
")",
")",
")",
".",
"reshape",
"(",
"A",
".",
"shape",
"+",
"(",
"-",
"1",
",",
")",
... | Converts from an array of type `self.dtype` to an array
of type `int` with an additional index labeling the
tuple indeces.
:param np.ndarray A: An `np.array` of type `self.dtype`.
:rtype: `np.ndarray` | [
"Converts",
"from",
"an",
"array",
"of",
"type",
"self",
".",
"dtype",
"to",
"an",
"array",
"of",
"type",
"int",
"with",
"an",
"additional",
"index",
"labeling",
"the",
"tuple",
"indeces",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L661-L673 | train |
QInfer/python-qinfer | src/qinfer/domains.py | MultinomialDomain.from_regular_array | def from_regular_array(self, A):
"""
Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
:rtype: `np.ndarray`
... | python | def from_regular_array(self, A):
"""
Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
:rtype: `np.ndarray`
... | [
"def",
"from_regular_array",
"(",
"self",
",",
"A",
")",
":",
"dims",
"=",
"A",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"return",
"A",
".",
"reshape",
"(",
"(",
"np",
".",
"prod",
"(",
"dims",
")",
",",
"-",
"1",
")",
")",
".",
"view",
"(",
... | Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
:rtype: `np.ndarray` | [
"Converts",
"from",
"an",
"array",
"of",
"type",
"int",
"where",
"the",
"last",
"index",
"is",
"assumed",
"to",
"have",
"length",
"self",
".",
"n_elements",
"to",
"an",
"array",
"of",
"type",
"self",
".",
"d_type",
"with",
"one",
"fewer",
"index",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/domains.py#L675-L686 | train |
QInfer/python-qinfer | src/qinfer/ipy.py | IPythonProgressBar.start | def start(self, max):
"""
Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar.
"""
try:
self.widget.max = max
display(self.widget)
except:
pass | python | def start(self, max):
"""
Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar.
"""
try:
self.widget.max = max
display(self.widget)
except:
pass | [
"def",
"start",
"(",
"self",
",",
"max",
")",
":",
"try",
":",
"self",
".",
"widget",
".",
"max",
"=",
"max",
"display",
"(",
"self",
".",
"widget",
")",
"except",
":",
"pass"
] | Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar. | [
"Displays",
"the",
"progress",
"bar",
"for",
"a",
"given",
"maximum",
"value",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/ipy.py#L94-L104 | train |
QInfer/python-qinfer | src/qinfer/tomography/legacy.py | MultiQubitStatePauliModel.likelihood | def likelihood(self, outcomes, modelparams, expparams):
"""
Calculates the likelihood function at the states specified
by modelparams and measurement specified by expparams.
This is given by the Born rule and is the probability of
outcomes given the state and measurement operato... | python | def likelihood(self, outcomes, modelparams, expparams):
"""
Calculates the likelihood function at the states specified
by modelparams and measurement specified by expparams.
This is given by the Born rule and is the probability of
outcomes given the state and measurement operato... | [
"def",
"likelihood",
"(",
"self",
",",
"outcomes",
",",
"modelparams",
",",
"expparams",
")",
":",
"super",
"(",
"MultiQubitStatePauliModel",
",",
"self",
")",
".",
"likelihood",
"(",
"outcomes",
",",
"modelparams",
",",
"expparams",
")",
"pr0",
"=",
"0.5",
... | Calculates the likelihood function at the states specified
by modelparams and measurement specified by expparams.
This is given by the Born rule and is the probability of
outcomes given the state and measurement operator. | [
"Calculates",
"the",
"likelihood",
"function",
"at",
"the",
"states",
"specified",
"by",
"modelparams",
"and",
"measurement",
"specified",
"by",
"expparams",
".",
"This",
"is",
"given",
"by",
"the",
"Born",
"rule",
"and",
"is",
"the",
"probability",
"of",
"out... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/legacy.py#L317-L341 | train |
QInfer/python-qinfer | src/qinfer/derived_models.py | BinomialModel.domain | def domain(self, expparams):
"""
Returns a list of ``Domain``s, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where ``n_outcomes_... | python | def domain(self, expparams):
"""
Returns a list of ``Domain``s, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where ``n_outcomes_... | [
"def",
"domain",
"(",
"self",
",",
"expparams",
")",
":",
"return",
"[",
"IntegerDomain",
"(",
"min",
"=",
"0",
",",
"max",
"=",
"n_o",
"-",
"1",
")",
"for",
"n_o",
"in",
"self",
".",
"n_outcomes",
"(",
"expparams",
")",
"]"
] | Returns a list of ``Domain``s, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where ``n_outcomes_constant`` is ``True``,
``None`` shou... | [
"Returns",
"a",
"list",
"of",
"Domain",
"s",
"one",
"for",
"each",
"input",
"expparam",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/derived_models.py#L287-L298 | train |
QInfer/python-qinfer | src/qinfer/derived_models.py | GaussianHyperparameterizedModel.underlying_likelihood | def underlying_likelihood(self, binary_outcomes, modelparams, expparams):
"""
Given outcomes hypothesized for the underlying model, returns the likelihood
which which those outcomes occur.
"""
original_mps = modelparams[..., self._orig_mps_slice]
return self.underlying_mo... | python | def underlying_likelihood(self, binary_outcomes, modelparams, expparams):
"""
Given outcomes hypothesized for the underlying model, returns the likelihood
which which those outcomes occur.
"""
original_mps = modelparams[..., self._orig_mps_slice]
return self.underlying_mo... | [
"def",
"underlying_likelihood",
"(",
"self",
",",
"binary_outcomes",
",",
"modelparams",
",",
"expparams",
")",
":",
"original_mps",
"=",
"modelparams",
"[",
"...",
",",
"self",
".",
"_orig_mps_slice",
"]",
"return",
"self",
".",
"underlying_model",
".",
"likeli... | Given outcomes hypothesized for the underlying model, returns the likelihood
which which those outcomes occur. | [
"Given",
"outcomes",
"hypothesized",
"for",
"the",
"underlying",
"model",
"returns",
"the",
"likelihood",
"which",
"which",
"those",
"outcomes",
"occur",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/derived_models.py#L443-L449 | train |
QInfer/python-qinfer | src/qinfer/abstract_model.py | Simulatable.are_expparam_dtypes_consistent | def are_expparam_dtypes_consistent(self, expparams):
"""
Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarr... | python | def are_expparam_dtypes_consistent(self, expparams):
"""
Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarr... | [
"def",
"are_expparam_dtypes_consistent",
"(",
"self",
",",
"expparams",
")",
":",
"if",
"self",
".",
"is_n_outcomes_constant",
":",
"return",
"True",
"if",
"expparams",
".",
"size",
">",
"0",
":",
"domains",
"=",
"self",
".",
"domain",
"(",
"expparams",
")",... | Returns ``True`` iff all of the given expparams
correspond to outcome domains with the same dtype.
For efficiency, concrete subclasses should override this method
if the result is always ``True``.
:param np.ndarray expparams: Array of expparamms
of type ``expparams_dtype... | [
"Returns",
"True",
"iff",
"all",
"of",
"the",
"given",
"expparams",
"correspond",
"to",
"outcome",
"domains",
"with",
"the",
"same",
"dtype",
".",
"For",
"efficiency",
"concrete",
"subclasses",
"should",
"override",
"this",
"method",
"if",
"the",
"result",
"is... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L218-L239 | train |
QInfer/python-qinfer | src/qinfer/abstract_model.py | Simulatable.simulate_experiment | def simulate_experiment(self, modelparams, expparams, repeat=1):
"""
Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter ... | python | def simulate_experiment(self, modelparams, expparams, repeat=1):
"""
Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter ... | [
"def",
"simulate_experiment",
"(",
"self",
",",
"modelparams",
",",
"expparams",
",",
"repeat",
"=",
"1",
")",
":",
"self",
".",
"_sim_count",
"+=",
"modelparams",
".",
"shape",
"[",
"0",
"]",
"*",
"expparams",
".",
"shape",
"[",
"0",
"]",
"*",
"repeat... | Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter vectors describing the hypotheses under
which data should be simulated.
... | [
"Produces",
"data",
"according",
"to",
"the",
"given",
"model",
"parameters",
"and",
"experimental",
"parameters",
"structured",
"as",
"a",
"NumPy",
"array",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L284-L307 | train |
QInfer/python-qinfer | src/qinfer/abstract_model.py | Model.likelihood | def likelihood(self, outcomes, modelparams, expparams):
r"""
Calculates the probability of each given outcome, conditioned on each
given model parameter vector and each given experimental control setting.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
a... | python | def likelihood(self, outcomes, modelparams, expparams):
r"""
Calculates the probability of each given outcome, conditioned on each
given model parameter vector and each given experimental control setting.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
a... | [
"def",
"likelihood",
"(",
"self",
",",
"outcomes",
",",
"modelparams",
",",
"expparams",
")",
":",
"r",
"self",
".",
"_call_count",
"+=",
"(",
"safe_shape",
"(",
"outcomes",
")",
"*",
"safe_shape",
"(",
"modelparams",
")",
"*",
"safe_shape",
"(",
"expparam... | r"""
Calculates the probability of each given outcome, conditioned on each
given model parameter vector and each given experimental control setting.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter vectors describing the hypotheses for
... | [
"r",
"Calculates",
"the",
"probability",
"of",
"each",
"given",
"outcome",
"conditioned",
"on",
"each",
"given",
"model",
"parameter",
"vector",
"and",
"each",
"given",
"experimental",
"control",
"setting",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L444-L468 | train |
QInfer/python-qinfer | src/qinfer/utils.py | get_qutip_module | def get_qutip_module(required_version='3.2'):
"""
Attempts to return the qutip module, but
silently returns ``None`` if it can't be
imported, or doesn't have version at
least ``required_version``.
:param str required_version: Valid input to
``distutils.version.LooseVersion``.
:retur... | python | def get_qutip_module(required_version='3.2'):
"""
Attempts to return the qutip module, but
silently returns ``None`` if it can't be
imported, or doesn't have version at
least ``required_version``.
:param str required_version: Valid input to
``distutils.version.LooseVersion``.
:retur... | [
"def",
"get_qutip_module",
"(",
"required_version",
"=",
"'3.2'",
")",
":",
"try",
":",
"import",
"qutip",
"as",
"qt",
"from",
"distutils",
".",
"version",
"import",
"LooseVersion",
"_qt_version",
"=",
"LooseVersion",
"(",
"qt",
".",
"version",
".",
"version",... | Attempts to return the qutip module, but
silently returns ``None`` if it can't be
imported, or doesn't have version at
least ``required_version``.
:param str required_version: Valid input to
``distutils.version.LooseVersion``.
:return: The qutip module or ``None``.
:rtype: ``module`` or... | [
"Attempts",
"to",
"return",
"the",
"qutip",
"module",
"but",
"silently",
"returns",
"None",
"if",
"it",
"can",
"t",
"be",
"imported",
"or",
"doesn",
"t",
"have",
"version",
"at",
"least",
"required_version",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L64-L85 | train |
QInfer/python-qinfer | src/qinfer/utils.py | particle_covariance_mtx | def particle_covariance_mtx(weights,locations):
"""
Returns an estimate of the covariance of a distribution
represented by a given set of SMC particle.
:param weights: An array containing the weights of each
particle.
:param location: An array containing the locations of
each partic... | python | def particle_covariance_mtx(weights,locations):
"""
Returns an estimate of the covariance of a distribution
represented by a given set of SMC particle.
:param weights: An array containing the weights of each
particle.
:param location: An array containing the locations of
each partic... | [
"def",
"particle_covariance_mtx",
"(",
"weights",
",",
"locations",
")",
":",
"warnings",
".",
"warn",
"(",
"'particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution'",
",",
"DeprecationWarning",
")",
"mu",
"=",
"particle_meanfn",
"(",
"weights",
... | Returns an estimate of the covariance of a distribution
represented by a given set of SMC particle.
:param weights: An array containing the weights of each
particle.
:param location: An array containing the locations of
each particle.
:rtype: :class:`numpy.ndarray`, shape
``(n_m... | [
"Returns",
"an",
"estimate",
"of",
"the",
"covariance",
"of",
"a",
"distribution",
"represented",
"by",
"a",
"given",
"set",
"of",
"SMC",
"particle",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L235-L287 | train |
QInfer/python-qinfer | src/qinfer/utils.py | ellipsoid_volume | def ellipsoid_volume(A=None, invA=None):
"""
Returns the volume of an ellipsoid given either its
matrix or the inverse of its matrix.
"""
if invA is None and A is None:
raise ValueError("Must pass either inverse(A) or A.")
if invA is None and A is not None:
invA = la.inv(A)
... | python | def ellipsoid_volume(A=None, invA=None):
"""
Returns the volume of an ellipsoid given either its
matrix or the inverse of its matrix.
"""
if invA is None and A is None:
raise ValueError("Must pass either inverse(A) or A.")
if invA is None and A is not None:
invA = la.inv(A)
... | [
"def",
"ellipsoid_volume",
"(",
"A",
"=",
"None",
",",
"invA",
"=",
"None",
")",
":",
"if",
"invA",
"is",
"None",
"and",
"A",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must pass either inverse(A) or A.\"",
")",
"if",
"invA",
"is",
"None",
"and",
... | Returns the volume of an ellipsoid given either its
matrix or the inverse of its matrix. | [
"Returns",
"the",
"volume",
"of",
"an",
"ellipsoid",
"given",
"either",
"its",
"matrix",
"or",
"the",
"inverse",
"of",
"its",
"matrix",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L290-L307 | train |
QInfer/python-qinfer | src/qinfer/utils.py | in_ellipsoid | def in_ellipsoid(x, A, c):
"""
Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarray x: Shape ``(n_points, dim)`... | python | def in_ellipsoid(x, A, c):
"""
Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarray x: Shape ``(n_points, dim)`... | [
"def",
"in_ellipsoid",
"(",
"x",
",",
"A",
",",
"c",
")",
":",
"if",
"x",
".",
"ndim",
"==",
"1",
":",
"y",
"=",
"c",
"-",
"x",
"return",
"np",
".",
"einsum",
"(",
"'j,jl,l'",
",",
"y",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"A",
")",
... | Determines which of the points ``x`` are in the
closed ellipsoid with shape matrix ``A`` centered at ``c``.
For a single point ``x``, this is computed as
.. math::
(c-x)^T\cdot A^{-1}\cdot (c-x) \leq 1
:param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``.
:param np.ndarra... | [
"Determines",
"which",
"of",
"the",
"points",
"x",
"are",
"in",
"the",
"closed",
"ellipsoid",
"with",
"shape",
"matrix",
"A",
"centered",
"at",
"c",
".",
"For",
"a",
"single",
"point",
"x",
"this",
"is",
"computed",
"as"
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L355-L374 | train |
QInfer/python-qinfer | src/qinfer/utils.py | assert_sigfigs_equal | def assert_sigfigs_equal(x, y, sigfigs=3):
"""
Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
... | python | def assert_sigfigs_equal(x, y, sigfigs=3):
"""
Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
... | [
"def",
"assert_sigfigs_equal",
"(",
"x",
",",
"y",
",",
"sigfigs",
"=",
"3",
")",
":",
"xpow",
"=",
"np",
".",
"floor",
"(",
"np",
".",
"log10",
"(",
"x",
")",
")",
"x",
"=",
"x",
"*",
"10",
"**",
"(",
"-",
"xpow",
")",
"y",
"=",
"y",
"*",
... | Tests if all elements in x and y
agree up to a certain number of
significant figures.
:param np.ndarray x: Array of numbers.
:param np.ndarray y: Array of numbers you want to
be equal to ``x``.
:param int sigfigs: How many significant
figures you demand that they share.
Defa... | [
"Tests",
"if",
"all",
"elements",
"in",
"x",
"and",
"y",
"agree",
"up",
"to",
"a",
"certain",
"number",
"of",
"significant",
"figures",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L385-L406 | train |
QInfer/python-qinfer | src/qinfer/utils.py | format_uncertainty | def format_uncertainty(value, uncertianty, scinotn_break=4):
"""
Given a value and its uncertianty, format as a LaTeX string
for pretty-printing.
:param int scinotn_break: How many decimal points to print
before breaking into scientific notation.
"""
if uncertianty == 0:
# Retur... | python | def format_uncertainty(value, uncertianty, scinotn_break=4):
"""
Given a value and its uncertianty, format as a LaTeX string
for pretty-printing.
:param int scinotn_break: How many decimal points to print
before breaking into scientific notation.
"""
if uncertianty == 0:
# Retur... | [
"def",
"format_uncertainty",
"(",
"value",
",",
"uncertianty",
",",
"scinotn_break",
"=",
"4",
")",
":",
"if",
"uncertianty",
"==",
"0",
":",
"return",
"\"{0:f}\"",
".",
"format",
"(",
"value",
")",
"else",
":",
"mag_unc",
"=",
"int",
"(",
"np",
".",
"... | Given a value and its uncertianty, format as a LaTeX string
for pretty-printing.
:param int scinotn_break: How many decimal points to print
before breaking into scientific notation. | [
"Given",
"a",
"value",
"and",
"its",
"uncertianty",
"format",
"as",
"a",
"LaTeX",
"string",
"for",
"pretty",
"-",
"printing",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L408-L450 | train |
QInfer/python-qinfer | src/qinfer/utils.py | from_simplex | def from_simplex(x):
r"""
Inteprets the last index of x as unit simplices and returns a
real array of the sampe shape in logit space.
Inverse to :func:`to_simplex` ; see that function for more details.
:param np.ndarray: Array of unit simplices along the last index.
:rtype: ``np.ndarray``... | python | def from_simplex(x):
r"""
Inteprets the last index of x as unit simplices and returns a
real array of the sampe shape in logit space.
Inverse to :func:`to_simplex` ; see that function for more details.
:param np.ndarray: Array of unit simplices along the last index.
:rtype: ``np.ndarray``... | [
"def",
"from_simplex",
"(",
"x",
")",
":",
"r",
"n",
"=",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"z",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"x",
".",
"shape",
")",
"z",
"[",
"...",
",",
"0",
"]",
"=",
"x",
"[",
"...",
",",
"0",
"]... | r"""
Inteprets the last index of x as unit simplices and returns a
real array of the sampe shape in logit space.
Inverse to :func:`to_simplex` ; see that function for more details.
:param np.ndarray: Array of unit simplices along the last index.
:rtype: ``np.ndarray`` | [
"r",
"Inteprets",
"the",
"last",
"index",
"of",
"x",
"as",
"unit",
"simplices",
"and",
"returns",
"a",
"real",
"array",
"of",
"the",
"sampe",
"shape",
"in",
"logit",
"space",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L511-L533 | train |
QInfer/python-qinfer | src/qinfer/utils.py | join_struct_arrays | def join_struct_arrays(arrays):
"""
Takes a list of possibly structured arrays, concatenates their
dtypes, and returns one big array with that dtype. Does the
inverse of ``separate_struct_array``.
:param list arrays: List of ``np.ndarray``s
"""
# taken from http://stackoverflow.com/question... | python | def join_struct_arrays(arrays):
"""
Takes a list of possibly structured arrays, concatenates their
dtypes, and returns one big array with that dtype. Does the
inverse of ``separate_struct_array``.
:param list arrays: List of ``np.ndarray``s
"""
# taken from http://stackoverflow.com/question... | [
"def",
"join_struct_arrays",
"(",
"arrays",
")",
":",
"sizes",
"=",
"np",
".",
"array",
"(",
"[",
"a",
".",
"itemsize",
"for",
"a",
"in",
"arrays",
"]",
")",
"offsets",
"=",
"np",
".",
"r_",
"[",
"0",
",",
"sizes",
".",
"cumsum",
"(",
")",
"]",
... | Takes a list of possibly structured arrays, concatenates their
dtypes, and returns one big array with that dtype. Does the
inverse of ``separate_struct_array``.
:param list arrays: List of ``np.ndarray``s | [
"Takes",
"a",
"list",
"of",
"possibly",
"structured",
"arrays",
"concatenates",
"their",
"dtypes",
"and",
"returns",
"one",
"big",
"array",
"with",
"that",
"dtype",
".",
"Does",
"the",
"inverse",
"of",
"separate_struct_array",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L551-L567 | train |
QInfer/python-qinfer | src/qinfer/utils.py | separate_struct_array | def separate_struct_array(array, dtypes):
"""
Takes an array with a structured dtype, and separates it out into
a list of arrays with dtypes coming from the input ``dtypes``.
Does the inverse of ``join_struct_arrays``.
:param np.ndarray array: Structured array.
:param dtypes: List of ``np.dtype... | python | def separate_struct_array(array, dtypes):
"""
Takes an array with a structured dtype, and separates it out into
a list of arrays with dtypes coming from the input ``dtypes``.
Does the inverse of ``join_struct_arrays``.
:param np.ndarray array: Structured array.
:param dtypes: List of ``np.dtype... | [
"def",
"separate_struct_array",
"(",
"array",
",",
"dtypes",
")",
":",
"try",
":",
"offsets",
"=",
"np",
".",
"cumsum",
"(",
"[",
"np",
".",
"dtype",
"(",
"dtype",
")",
".",
"itemsize",
"for",
"dtype",
"in",
"dtypes",
"]",
")",
"except",
"TypeError",
... | Takes an array with a structured dtype, and separates it out into
a list of arrays with dtypes coming from the input ``dtypes``.
Does the inverse of ``join_struct_arrays``.
:param np.ndarray array: Structured array.
:param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the number of
t... | [
"Takes",
"an",
"array",
"with",
"a",
"structured",
"dtype",
"and",
"separates",
"it",
"out",
"into",
"a",
"list",
"of",
"arrays",
"with",
"dtypes",
"coming",
"from",
"the",
"input",
"dtypes",
".",
"Does",
"the",
"inverse",
"of",
"join_struct_arrays",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L569-L591 | train |
QInfer/python-qinfer | src/qinfer/utils.py | sqrtm_psd | def sqrtm_psd(A, est_error=True, check_finite=True):
"""
Returns the matrix square root of a positive semidefinite matrix,
truncating negative eigenvalues.
"""
w, v = eigh(A, check_finite=check_finite)
mask = w <= 0
w[mask] = 0
np.sqrt(w, out=w)
A_sqrt = (v * w).dot(v.conj().T)
... | python | def sqrtm_psd(A, est_error=True, check_finite=True):
"""
Returns the matrix square root of a positive semidefinite matrix,
truncating negative eigenvalues.
"""
w, v = eigh(A, check_finite=check_finite)
mask = w <= 0
w[mask] = 0
np.sqrt(w, out=w)
A_sqrt = (v * w).dot(v.conj().T)
... | [
"def",
"sqrtm_psd",
"(",
"A",
",",
"est_error",
"=",
"True",
",",
"check_finite",
"=",
"True",
")",
":",
"w",
",",
"v",
"=",
"eigh",
"(",
"A",
",",
"check_finite",
"=",
"check_finite",
")",
"mask",
"=",
"w",
"<=",
"0",
"w",
"[",
"mask",
"]",
"=",... | Returns the matrix square root of a positive semidefinite matrix,
truncating negative eigenvalues. | [
"Returns",
"the",
"matrix",
"square",
"root",
"of",
"a",
"positive",
"semidefinite",
"matrix",
"truncating",
"negative",
"eigenvalues",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L593-L607 | train |
QInfer/python-qinfer | src/qinfer/tomography/bases.py | tensor_product_basis | def tensor_product_basis(*bases):
"""
Returns a TomographyBasis formed by the tensor
product of two or more factor bases. Each basis element
is the tensor product of basis elements from the underlying
factors.
"""
dim = np.prod([basis.data.shape[1] for basis in bases])
tp_basis = np.zero... | python | def tensor_product_basis(*bases):
"""
Returns a TomographyBasis formed by the tensor
product of two or more factor bases. Each basis element
is the tensor product of basis elements from the underlying
factors.
"""
dim = np.prod([basis.data.shape[1] for basis in bases])
tp_basis = np.zero... | [
"def",
"tensor_product_basis",
"(",
"*",
"bases",
")",
":",
"dim",
"=",
"np",
".",
"prod",
"(",
"[",
"basis",
".",
"data",
".",
"shape",
"[",
"1",
"]",
"for",
"basis",
"in",
"bases",
"]",
")",
"tp_basis",
"=",
"np",
".",
"zeros",
"(",
"(",
"dim",... | Returns a TomographyBasis formed by the tensor
product of two or more factor bases. Each basis element
is the tensor product of basis elements from the underlying
factors. | [
"Returns",
"a",
"TomographyBasis",
"formed",
"by",
"the",
"tensor",
"product",
"of",
"two",
"or",
"more",
"factor",
"bases",
".",
"Each",
"basis",
"element",
"is",
"the",
"tensor",
"product",
"of",
"basis",
"elements",
"from",
"the",
"underlying",
"factors",
... | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L113-L135 | train |
QInfer/python-qinfer | src/qinfer/tomography/bases.py | TomographyBasis.state_to_modelparams | def state_to_modelparams(self, state):
"""
Converts a QuTiP-represented state into a model parameter vector.
:param qutip.Qobj state: State to be converted.
:rtype: :class:`np.ndarray`
:return: The representation of the given state in this basis,
as a vector of real ... | python | def state_to_modelparams(self, state):
"""
Converts a QuTiP-represented state into a model parameter vector.
:param qutip.Qobj state: State to be converted.
:rtype: :class:`np.ndarray`
:return: The representation of the given state in this basis,
as a vector of real ... | [
"def",
"state_to_modelparams",
"(",
"self",
",",
"state",
")",
":",
"basis",
"=",
"self",
".",
"flat",
"(",
")",
"data",
"=",
"state",
".",
"data",
".",
"todense",
"(",
")",
".",
"view",
"(",
"np",
".",
"ndarray",
")",
".",
"flatten",
"(",
")",
"... | Converts a QuTiP-represented state into a model parameter vector.
:param qutip.Qobj state: State to be converted.
:rtype: :class:`np.ndarray`
:return: The representation of the given state in this basis,
as a vector of real parameters. | [
"Converts",
"a",
"QuTiP",
"-",
"represented",
"state",
"into",
"a",
"model",
"parameter",
"vector",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L323-L336 | train |
QInfer/python-qinfer | src/qinfer/tomography/bases.py | TomographyBasis.modelparams_to_state | def modelparams_to_state(self, modelparams):
"""
Converts one or more vectors of model parameters into
QuTiP-represented states.
:param np.ndarray modelparams: Array of shape
``(basis.dim ** 2, )`` or
``(n_states, basis.dim ** 2)`` containing
states r... | python | def modelparams_to_state(self, modelparams):
"""
Converts one or more vectors of model parameters into
QuTiP-represented states.
:param np.ndarray modelparams: Array of shape
``(basis.dim ** 2, )`` or
``(n_states, basis.dim ** 2)`` containing
states r... | [
"def",
"modelparams_to_state",
"(",
"self",
",",
"modelparams",
")",
":",
"if",
"modelparams",
".",
"ndim",
"==",
"1",
":",
"qobj",
"=",
"qt",
".",
"Qobj",
"(",
"np",
".",
"tensordot",
"(",
"modelparams",
",",
"self",
".",
"data",
",",
"1",
")",
",",... | Converts one or more vectors of model parameters into
QuTiP-represented states.
:param np.ndarray modelparams: Array of shape
``(basis.dim ** 2, )`` or
``(n_states, basis.dim ** 2)`` containing
states represented as model parameter vectors in this
basis.
... | [
"Converts",
"one",
"or",
"more",
"vectors",
"of",
"model",
"parameters",
"into",
"QuTiP",
"-",
"represented",
"states",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L338-L362 | train |
QInfer/python-qinfer | src/qinfer/tomography/bases.py | TomographyBasis.covariance_mtx_to_superop | def covariance_mtx_to_superop(self, mtx):
"""
Converts a covariance matrix to the corresponding
superoperator, represented as a QuTiP Qobj
with ``type="super"``.
"""
M = self.flat()
return qt.Qobj(
np.dot(np.dot(M.conj().T, mtx), M),
dims=[... | python | def covariance_mtx_to_superop(self, mtx):
"""
Converts a covariance matrix to the corresponding
superoperator, represented as a QuTiP Qobj
with ``type="super"``.
"""
M = self.flat()
return qt.Qobj(
np.dot(np.dot(M.conj().T, mtx), M),
dims=[... | [
"def",
"covariance_mtx_to_superop",
"(",
"self",
",",
"mtx",
")",
":",
"M",
"=",
"self",
".",
"flat",
"(",
")",
"return",
"qt",
".",
"Qobj",
"(",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"M",
".",
"conj",
"(",
")",
".",
"T",
",",
"mtx",
... | Converts a covariance matrix to the corresponding
superoperator, represented as a QuTiP Qobj
with ``type="super"``. | [
"Converts",
"a",
"covariance",
"matrix",
"to",
"the",
"corresponding",
"superoperator",
"represented",
"as",
"a",
"QuTiP",
"Qobj",
"with",
"type",
"=",
"super",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/tomography/bases.py#L364-L374 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | MixtureDistribution._dist_kw_arg | def _dist_kw_arg(self, k):
"""
Returns a dictionary of keyword arguments
for the k'th distribution.
:param int k: Index of the distribution in question.
:rtype: ``dict``
"""
if self._dist_kw_args is not None:
return {
key:self._dist_kw... | python | def _dist_kw_arg(self, k):
"""
Returns a dictionary of keyword arguments
for the k'th distribution.
:param int k: Index of the distribution in question.
:rtype: ``dict``
"""
if self._dist_kw_args is not None:
return {
key:self._dist_kw... | [
"def",
"_dist_kw_arg",
"(",
"self",
",",
"k",
")",
":",
"if",
"self",
".",
"_dist_kw_args",
"is",
"not",
"None",
":",
"return",
"{",
"key",
":",
"self",
".",
"_dist_kw_args",
"[",
"key",
"]",
"[",
"k",
",",
":",
"]",
"for",
"key",
"in",
"self",
"... | Returns a dictionary of keyword arguments
for the k'th distribution.
:param int k: Index of the distribution in question.
:rtype: ``dict`` | [
"Returns",
"a",
"dictionary",
"of",
"keyword",
"arguments",
"for",
"the",
"k",
"th",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L207-L221 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | ParticleDistribution.sample | def sample(self, n=1):
"""
Returns random samples from the current particle distribution according
to particle weights.
:param int n: The number of samples to draw.
:return: The sampled model parameter vectors.
:rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``.
... | python | def sample(self, n=1):
"""
Returns random samples from the current particle distribution according
to particle weights.
:param int n: The number of samples to draw.
:return: The sampled model parameter vectors.
:rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``.
... | [
"def",
"sample",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"cumsum_weights",
"=",
"np",
".",
"cumsum",
"(",
"self",
".",
"particle_weights",
")",
"return",
"self",
".",
"particle_locations",
"[",
"np",
".",
"minimum",
"(",
"cumsum_weights",
".",
"search... | Returns random samples from the current particle distribution according
to particle weights.
:param int n: The number of samples to draw.
:return: The sampled model parameter vectors.
:rtype: `~numpy.ndarray` of shape ``(n, updater.n_rvs)``. | [
"Returns",
"random",
"samples",
"from",
"the",
"current",
"particle",
"distribution",
"according",
"to",
"particle",
"weights",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L320-L333 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | ParticleDistribution.est_covariance_mtx | def est_covariance_mtx(self, corr=False):
"""
Returns the full-rank covariance matrix of the current particle
distribution.
:param bool corr: If `True`, the covariance matrix is normalized
by the outer product of the square root diagonal of the covariance matrix,
... | python | def est_covariance_mtx(self, corr=False):
"""
Returns the full-rank covariance matrix of the current particle
distribution.
:param bool corr: If `True`, the covariance matrix is normalized
by the outer product of the square root diagonal of the covariance matrix,
... | [
"def",
"est_covariance_mtx",
"(",
"self",
",",
"corr",
"=",
"False",
")",
":",
"cov",
"=",
"self",
".",
"particle_covariance_mtx",
"(",
"self",
".",
"particle_weights",
",",
"self",
".",
"particle_locations",
")",
"if",
"corr",
":",
"dstd",
"=",
"np",
".",... | Returns the full-rank covariance matrix of the current particle
distribution.
:param bool corr: If `True`, the covariance matrix is normalized
by the outer product of the square root diagonal of the covariance matrix,
i.e. the correlation matrix is returned instead.
:rt... | [
"Returns",
"the",
"full",
"-",
"rank",
"covariance",
"matrix",
"of",
"the",
"current",
"particle",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L432-L453 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | ParticleDistribution.est_credible_region | def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None):
"""
Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the retur... | python | def est_credible_region(self, level=0.95, return_outside=False, modelparam_slice=None):
"""
Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the retur... | [
"def",
"est_credible_region",
"(",
"self",
",",
"level",
"=",
"0.95",
",",
"return_outside",
"=",
"False",
",",
"modelparam_slice",
"=",
"None",
")",
":",
"s_",
"=",
"np",
".",
"s_",
"[",
"modelparam_slice",
"]",
"if",
"modelparam_slice",
"is",
"not",
"Non... | Returns an array containing particles inside a credible region of a
given level, such that the described region has probability mass
no less than the desired level.
Particles in the returned region are selected by including the highest-
weight particles first until the desired credibili... | [
"Returns",
"an",
"array",
"containing",
"particles",
"inside",
"a",
"credible",
"region",
"of",
"a",
"given",
"level",
"such",
"that",
"the",
"described",
"region",
"has",
"probability",
"mass",
"no",
"less",
"than",
"the",
"desired",
"level",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L558-L614 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | ParticleDistribution.region_est_hull | def region_est_hull(self, level=0.95, modelparam_slice=None):
"""
Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:para... | python | def region_est_hull(self, level=0.95, modelparam_slice=None):
"""
Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:para... | [
"def",
"region_est_hull",
"(",
"self",
",",
"level",
"=",
"0.95",
",",
"modelparam_slice",
"=",
"None",
")",
":",
"points",
"=",
"self",
".",
"est_credible_region",
"(",
"level",
"=",
"level",
",",
"modelparam_slice",
"=",
"modelparam_slice",
")",
"hull",
"=... | Estimates a credible region over models by taking the convex hull of
a credible subset of particles.
:param float level: The desired crediblity level (see
:meth:`SMCUpdater.est_credible_region`).
:param slice modelparam_slice: Slice over which model parameters
to conside... | [
"Estimates",
"a",
"credible",
"region",
"over",
"models",
"by",
"taking",
"the",
"convex",
"hull",
"of",
"a",
"credible",
"subset",
"of",
"particles",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L616-L641 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | ParticleDistribution.in_credible_region | def in_credible_region(self, points, level=0.95, modelparam_slice=None, method='hpd-hull', tol=0.0001):
"""
Decides whether each of the points lie within a credible region
of the current distribution.
If ``tol`` is ``None``, the particles are tested directly against
the convex h... | python | def in_credible_region(self, points, level=0.95, modelparam_slice=None, method='hpd-hull', tol=0.0001):
"""
Decides whether each of the points lie within a credible region
of the current distribution.
If ``tol`` is ``None``, the particles are tested directly against
the convex h... | [
"def",
"in_credible_region",
"(",
"self",
",",
"points",
",",
"level",
"=",
"0.95",
",",
"modelparam_slice",
"=",
"None",
",",
"method",
"=",
"'hpd-hull'",
",",
"tol",
"=",
"0.0001",
")",
":",
"if",
"method",
"==",
"'pce'",
":",
"s_",
"=",
"np",
".",
... | Decides whether each of the points lie within a credible region
of the current distribution.
If ``tol`` is ``None``, the particles are tested directly against
the convex hull object. If ``tol`` is a positive ``float``,
particles are tested to be in the interior of the smallest
e... | [
"Decides",
"whether",
"each",
"of",
"the",
"points",
"lie",
"within",
"a",
"credible",
"region",
"of",
"the",
"current",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L668-L751 | train |
QInfer/python-qinfer | src/qinfer/distributions.py | PostselectedDistribution.sample | def sample(self, n=1):
"""
Returns one or more samples from this probability distribution.
:param int n: Number of samples to return.
:return numpy.ndarray: An array containing samples from the
distribution of shape ``(n, d)``, where ``d`` is the number of
random... | python | def sample(self, n=1):
"""
Returns one or more samples from this probability distribution.
:param int n: Number of samples to return.
:return numpy.ndarray: An array containing samples from the
distribution of shape ``(n, d)``, where ``d`` is the number of
random... | [
"def",
"sample",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"samples",
"=",
"np",
".",
"empty",
"(",
"(",
"n",
",",
"self",
".",
"n_rvs",
")",
")",
"idxs_to_sample",
"=",
"np",
".",
"arange",
"(",
"n",
")",
"iters",
"=",
"0",
"while",
"idxs_to_... | Returns one or more samples from this probability distribution.
:param int n: Number of samples to return.
:return numpy.ndarray: An array containing samples from the
distribution of shape ``(n, d)``, where ``d`` is the number of
random variables. | [
"Returns",
"one",
"or",
"more",
"samples",
"from",
"this",
"probability",
"distribution",
"."
] | 8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3 | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/distributions.py#L1321-L1347 | train |
amelchio/pysonos | pysonos/services.py | Service.iter_actions | def iter_actions(self):
"""Yield the service's actions with their arguments.
Yields:
`Action`: the next action.
Each action is an Action namedtuple, consisting of action_name
(a string), in_args (a list of Argument namedtuples consisting of name
and argtype), and ou... | python | def iter_actions(self):
"""Yield the service's actions with their arguments.
Yields:
`Action`: the next action.
Each action is an Action namedtuple, consisting of action_name
(a string), in_args (a list of Argument namedtuples consisting of name
and argtype), and ou... | [
"def",
"iter_actions",
"(",
"self",
")",
":",
"ns",
"=",
"'{urn:schemas-upnp-org:service-1-0}'",
"scpd_body",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
"+",
"self",
".",
"scpd_url",
")",
".",
"content",
"tree",
"=",
"XML",
".",
"fromstring",... | Yield the service's actions with their arguments.
Yields:
`Action`: the next action.
Each action is an Action namedtuple, consisting of action_name
(a string), in_args (a list of Argument namedtuples consisting of name
and argtype), and out_args (ditto), eg::
A... | [
"Yield",
"the",
"service",
"s",
"actions",
"with",
"their",
"arguments",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/services.py#L645-L711 | train |
amelchio/pysonos | pysonos/events.py | parse_event_xml | def parse_event_xml(xml_event):
"""Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string rep... | python | def parse_event_xml(xml_event):
"""Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string rep... | [
"def",
"parse_event_xml",
"(",
"xml_event",
")",
":",
"result",
"=",
"{",
"}",
"tree",
"=",
"XML",
".",
"fromstring",
"(",
"xml_event",
")",
"properties",
"=",
"tree",
".",
"findall",
"(",
"'{urn:schemas-upnp-org:event-1-0}property'",
")",
"for",
"prop",
"in",... | Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string representation of the
variable... | [
"Parse",
"the",
"body",
"of",
"a",
"UPnP",
"event",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L37-L170 | train |
amelchio/pysonos | pysonos/events.py | Subscription.unsubscribe | def unsubscribe(self):
"""Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused
"""
# Trying to unsubscribe if already unsubscribed, or not yet
# subscribed, fails silently
if self._has_been_unsubscribed or not self.is_sub... | python | def unsubscribe(self):
"""Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused
"""
# Trying to unsubscribe if already unsubscribed, or not yet
# subscribed, fails silently
if self._has_been_unsubscribed or not self.is_sub... | [
"def",
"unsubscribe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_has_been_unsubscribed",
"or",
"not",
"self",
".",
"is_subscribed",
":",
"return",
"self",
".",
"_auto_renew_thread_flag",
".",
"set",
"(",
")",
"headers",
"=",
"{",
"'SID'",
":",
"self",
"."... | Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused | [
"Unsubscribe",
"from",
"the",
"service",
"s",
"events",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L586-L633 | train |
amelchio/pysonos | pysonos/core.py | SoCo.play_mode | def play_mode(self, playmode):
"""Set the speaker's mode."""
playmode = playmode.upper()
if playmode not in PLAY_MODES.keys():
raise KeyError("'%s' is not a valid play mode" % playmode)
self.avTransport.SetPlayMode([
('InstanceID', 0),
('NewPlayMode',... | python | def play_mode(self, playmode):
"""Set the speaker's mode."""
playmode = playmode.upper()
if playmode not in PLAY_MODES.keys():
raise KeyError("'%s' is not a valid play mode" % playmode)
self.avTransport.SetPlayMode([
('InstanceID', 0),
('NewPlayMode',... | [
"def",
"play_mode",
"(",
"self",
",",
"playmode",
")",
":",
"playmode",
"=",
"playmode",
".",
"upper",
"(",
")",
"if",
"playmode",
"not",
"in",
"PLAY_MODES",
".",
"keys",
"(",
")",
":",
"raise",
"KeyError",
"(",
"\"'%s' is not a valid play mode\"",
"%",
"p... | Set the speaker's mode. | [
"Set",
"the",
"speaker",
"s",
"mode",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L408-L417 | train |
amelchio/pysonos | pysonos/core.py | SoCo.repeat | def repeat(self, repeat):
"""Set the queue's repeat option"""
shuffle = self.shuffle
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)] | python | def repeat(self, repeat):
"""Set the queue's repeat option"""
shuffle = self.shuffle
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)] | [
"def",
"repeat",
"(",
"self",
",",
"repeat",
")",
":",
"shuffle",
"=",
"self",
".",
"shuffle",
"self",
".",
"play_mode",
"=",
"PLAY_MODE_BY_MEANING",
"[",
"(",
"shuffle",
",",
"repeat",
")",
"]"
] | Set the queue's repeat option | [
"Set",
"the",
"queue",
"s",
"repeat",
"option"
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L444-L447 | train |
amelchio/pysonos | pysonos/core.py | SoCo.join | def join(self, master):
"""Join this speaker to another "master" speaker."""
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-rincon:{0}'.format(master.uid)),
('CurrentURIMetaData', '')
])
self._zgs_cache.clear()
self._... | python | def join(self, master):
"""Join this speaker to another "master" speaker."""
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-rincon:{0}'.format(master.uid)),
('CurrentURIMetaData', '')
])
self._zgs_cache.clear()
self._... | [
"def",
"join",
"(",
"self",
",",
"master",
")",
":",
"self",
".",
"avTransport",
".",
"SetAVTransportURI",
"(",
"[",
"(",
"'InstanceID'",
",",
"0",
")",
",",
"(",
"'CurrentURI'",
",",
"'x-rincon:{0}'",
".",
"format",
"(",
"master",
".",
"uid",
")",
")"... | Join this speaker to another "master" speaker. | [
"Join",
"this",
"speaker",
"to",
"another",
"master",
"speaker",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1079-L1087 | train |
amelchio/pysonos | pysonos/core.py | SoCo.unjoin | def unjoin(self):
"""Remove this speaker from a group.
Seems to work ok even if you remove what was previously the group
master from it's own group. If the speaker was not in a group also
returns ok.
"""
self.avTransport.BecomeCoordinatorOfStandaloneGroup([
... | python | def unjoin(self):
"""Remove this speaker from a group.
Seems to work ok even if you remove what was previously the group
master from it's own group. If the speaker was not in a group also
returns ok.
"""
self.avTransport.BecomeCoordinatorOfStandaloneGroup([
... | [
"def",
"unjoin",
"(",
"self",
")",
":",
"self",
".",
"avTransport",
".",
"BecomeCoordinatorOfStandaloneGroup",
"(",
"[",
"(",
"'InstanceID'",
",",
"0",
")",
"]",
")",
"self",
".",
"_zgs_cache",
".",
"clear",
"(",
")",
"self",
".",
"_parse_zone_group_state",
... | Remove this speaker from a group.
Seems to work ok even if you remove what was previously the group
master from it's own group. If the speaker was not in a group also
returns ok. | [
"Remove",
"this",
"speaker",
"from",
"a",
"group",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1089-L1101 | train |
amelchio/pysonos | pysonos/core.py | SoCo.set_sleep_timer | def set_sleep_timer(self, sleep_time_seconds):
"""Sets the sleep timer.
Args:
sleep_time_seconds (int or NoneType): How long to wait before
turning off speaker in seconds, None to cancel a sleep timer.
Maximum value of 86399
Raises:
SoCoE... | python | def set_sleep_timer(self, sleep_time_seconds):
"""Sets the sleep timer.
Args:
sleep_time_seconds (int or NoneType): How long to wait before
turning off speaker in seconds, None to cancel a sleep timer.
Maximum value of 86399
Raises:
SoCoE... | [
"def",
"set_sleep_timer",
"(",
"self",
",",
"sleep_time_seconds",
")",
":",
"try",
":",
"if",
"sleep_time_seconds",
"is",
"None",
":",
"sleep_time",
"=",
"''",
"else",
":",
"sleep_time",
"=",
"format",
"(",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
... | Sets the sleep timer.
Args:
sleep_time_seconds (int or NoneType): How long to wait before
turning off speaker in seconds, None to cancel a sleep timer.
Maximum value of 86399
Raises:
SoCoException: Upon errors interacting with Sonos controller
... | [
"Sets",
"the",
"sleep",
"timer",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1714-L1749 | train |
amelchio/pysonos | pysonos/snapshot.py | Snapshot._restore_coordinator | def _restore_coordinator(self):
"""Do the coordinator-only part of the restore."""
# Start by ensuring that the speaker is paused as we don't want
# things all rolling back when we are changing them, as this could
# include things like audio
transport_info = self.device.get_curre... | python | def _restore_coordinator(self):
"""Do the coordinator-only part of the restore."""
# Start by ensuring that the speaker is paused as we don't want
# things all rolling back when we are changing them, as this could
# include things like audio
transport_info = self.device.get_curre... | [
"def",
"_restore_coordinator",
"(",
"self",
")",
":",
"transport_info",
"=",
"self",
".",
"device",
".",
"get_current_transport_info",
"(",
")",
"if",
"transport_info",
"is",
"not",
"None",
":",
"if",
"transport_info",
"[",
"'current_transport_state'",
"]",
"==",
... | Do the coordinator-only part of the restore. | [
"Do",
"the",
"coordinator",
"-",
"only",
"part",
"of",
"the",
"restore",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L186-L231 | train |
amelchio/pysonos | pysonos/snapshot.py | Snapshot._restore_volume | def _restore_volume(self, fade):
"""Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore.
"""
self.device.mute = self.mute
# Can only change volume on device with fixed volume set to False
# otherwise get uPnP error, so check fir... | python | def _restore_volume(self, fade):
"""Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore.
"""
self.device.mute = self.mute
# Can only change volume on device with fixed volume set to False
# otherwise get uPnP error, so check fir... | [
"def",
"_restore_volume",
"(",
"self",
",",
"fade",
")",
":",
"self",
".",
"device",
".",
"mute",
"=",
"self",
".",
"mute",
"if",
"self",
".",
"volume",
"==",
"100",
":",
"fixed_vol",
"=",
"self",
".",
"device",
".",
"renderingControl",
".",
"GetOutput... | Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore. | [
"Reinstate",
"volume",
"."
] | 23527c445a00e198fbb94d44b92f7f99d139e325 | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L233-L264 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.