repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_thermal_displacement_matrices | def run_thermal_displacement_matrices(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacement matrices
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
mesh_nums = self._mesh.mesh_numbers
ir_grid_points = self._mesh.ir_grid_points
if not self._mesh.with_eigenvectors:
msg = ("run_mesh has to be done with with_eigenvectors=True.")
raise RuntimeError(msg)
if np.prod(mesh_nums) != len(ir_grid_points):
msg = ("run_mesh has to be done with is_mesh_symmetry=False.")
raise RuntimeError(msg)
tdm = ThermalDisplacementMatrices(
self._mesh,
freq_min=freq_min,
freq_max=freq_max,
lattice=self._primitive.get_cell().T)
if temperatures is None:
tdm.set_temperature_range(t_min, t_max, t_step)
else:
tdm.set_temperatures(temperatures)
tdm.run()
self._thermal_displacement_matrices = tdm | python | def run_thermal_displacement_matrices(self,
t_min=0,
t_max=1000,
t_step=10,
temperatures=None,
freq_min=None,
freq_max=None):
"""Prepare thermal displacement matrices
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
if self._mesh is None:
msg = ("run_mesh has to be done.")
raise RuntimeError(msg)
mesh_nums = self._mesh.mesh_numbers
ir_grid_points = self._mesh.ir_grid_points
if not self._mesh.with_eigenvectors:
msg = ("run_mesh has to be done with with_eigenvectors=True.")
raise RuntimeError(msg)
if np.prod(mesh_nums) != len(ir_grid_points):
msg = ("run_mesh has to be done with is_mesh_symmetry=False.")
raise RuntimeError(msg)
tdm = ThermalDisplacementMatrices(
self._mesh,
freq_min=freq_min,
freq_max=freq_max,
lattice=self._primitive.get_cell().T)
if temperatures is None:
tdm.set_temperature_range(t_min, t_max, t_step)
else:
tdm.set_temperatures(temperatures)
tdm.run()
self._thermal_displacement_matrices = tdm | [
"def",
"run_thermal_displacement_matrices",
"(",
"self",
",",
"t_min",
"=",
"0",
",",
"t_max",
"=",
"1000",
",",
"t_step",
"=",
"10",
",",
"temperatures",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"if",
"self",
... | Prepare thermal displacement matrices
Parameters
----------
t_min, t_max, t_step : float, optional
Minimum and maximum temperatures and the interval in this
temperature range. Default valuues are 0, 1000, and 10.
freq_min, freq_max : float, optional
Phonon frequencies larger than freq_min and smaller than
freq_max are included. Default is None, i.e., all phonons.
temperatures : array_like, optional
Temperature points where thermal properties are calculated.
When this is set, t_min, t_max, and t_step are ignored.
Default is None. | [
"Prepare",
"thermal",
"displacement",
"matrices"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2016-L2066 | train | 222,400 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_modulations | def set_modulations(self,
dimension,
phonon_modes,
delta_q=None,
derivative_order=None,
nac_q_direction=None):
"""Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._modulation = Modulation(self._dynamical_matrix,
dimension,
phonon_modes,
delta_q=delta_q,
derivative_order=derivative_order,
nac_q_direction=nac_q_direction,
factor=self._factor)
self._modulation.run() | python | def set_modulations(self,
dimension,
phonon_modes,
delta_q=None,
derivative_order=None,
nac_q_direction=None):
"""Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._modulation = Modulation(self._dynamical_matrix,
dimension,
phonon_modes,
delta_q=delta_q,
derivative_order=derivative_order,
nac_q_direction=nac_q_direction,
factor=self._factor)
self._modulation.run() | [
"def",
"set_modulations",
"(",
"self",
",",
"dimension",
",",
"phonon_modes",
",",
"delta_q",
"=",
"None",
",",
"derivative_order",
"=",
"None",
",",
"nac_q_direction",
"=",
"None",
")",
":",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
... | Generate atomic displacements of phonon modes.
The design of this feature is not very satisfactory, and thus API.
Therefore it should be reconsidered someday in the fugure.
Parameters
----------
dimension : array_like
Supercell dimension with respect to the primitive cell.
dtype='intc', shape=(3, ), (3, 3), (9, )
phonon_modes : list of phonon mode settings
Each element of the outer list gives one phonon mode information:
[q-point, band index (int), amplitude (float), phase (float)]
In each list of the phonon mode information, the first element is
a list that represents q-point in reduced coordinates. The second,
third, and fourth elements show the band index starting with 0,
amplitude, and phase factor, respectively. | [
"Generate",
"atomic",
"displacements",
"of",
"phonon",
"modes",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2204-L2242 | train | 222,401 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.set_irreps | def set_irreps(self,
q,
is_little_cogroup=False,
nac_q_direction=None,
degeneracy_tolerance=1e-4):
"""Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._irreps = IrReps(
self._dynamical_matrix,
q,
is_little_cogroup=is_little_cogroup,
nac_q_direction=nac_q_direction,
factor=self._factor,
symprec=self._symprec,
degeneracy_tolerance=degeneracy_tolerance,
log_level=self._log_level)
return self._irreps.run() | python | def set_irreps(self,
q,
is_little_cogroup=False,
nac_q_direction=None,
degeneracy_tolerance=1e-4):
"""Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer.
"""
if self._dynamical_matrix is None:
msg = ("Dynamical matrix has not yet built.")
raise RuntimeError(msg)
self._irreps = IrReps(
self._dynamical_matrix,
q,
is_little_cogroup=is_little_cogroup,
nac_q_direction=nac_q_direction,
factor=self._factor,
symprec=self._symprec,
degeneracy_tolerance=degeneracy_tolerance,
log_level=self._log_level)
return self._irreps.run() | [
"def",
"set_irreps",
"(",
"self",
",",
"q",
",",
"is_little_cogroup",
"=",
"False",
",",
"nac_q_direction",
"=",
"None",
",",
"degeneracy_tolerance",
"=",
"1e-4",
")",
":",
"if",
"self",
".",
"_dynamical_matrix",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Dyna... | Identify ir-reps of phonon modes.
The design of this API is not very satisfactory and is expceted
to be redesined in the next major versions once the use case
of the API for ir-reps feature becomes clearer. | [
"Identify",
"ir",
"-",
"reps",
"of",
"phonon",
"modes",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2267-L2294 | train | 222,402 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.init_dynamic_structure_factor | def init_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before initializing dynamic"
"structure factor.")
raise RuntimeError(msg)
if not self._mesh.with_eigenvectors:
msg = "run_mesh has to be called with with_eigenvectors=True."
raise RuntimeError(msg)
if np.prod(self._mesh.mesh_numbers) != len(self._mesh.ir_grid_points):
msg = "run_mesh has to be done with is_mesh_symmetry=False."
raise RuntimeError(msg)
self._dynamic_structure_factor = DynamicStructureFactor(
self._mesh,
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max) | python | def init_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation.
"""
if self._mesh is None:
msg = ("run_mesh has to be done before initializing dynamic"
"structure factor.")
raise RuntimeError(msg)
if not self._mesh.with_eigenvectors:
msg = "run_mesh has to be called with with_eigenvectors=True."
raise RuntimeError(msg)
if np.prod(self._mesh.mesh_numbers) != len(self._mesh.ir_grid_points):
msg = "run_mesh has to be done with is_mesh_symmetry=False."
raise RuntimeError(msg)
self._dynamic_structure_factor = DynamicStructureFactor(
self._mesh,
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max) | [
"def",
"init_dynamic_structure_factor",
"(",
"self",
",",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"None",
",",
"scattering_lengths",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"if",
"self",
".",
"_mes... | Initialize dynamic structure factor calculation.
*******************************************************************
This is still an experimental feature. API can be changed without
notification.
*******************************************************************
Need to call DynamicStructureFactor.run() to start calculation.
Parameters
----------
Qpoints: array_like
Q-points in any Brillouin zone.
dtype='double'
shape=(qpoints, 3)
T: float
Temperature in K.
atomic_form_factor_func: Function object
Function that returns atomic form factor (``func`` below):
f_params = {'Na': [3.148690, 2.594987, 4.073989, 6.046925,
0.767888, 0.070139, 0.995612, 14.1226457,
0.968249, 0.217037, 0.045300],
'Cl': [1.061802, 0.144727, 7.139886, 1.171795,
6.524271, 19.467656, 2.355626, 60.320301,
35.829404, 0.000436, -34.916604],b|
def get_func_AFF(f_params):
def func(symbol, Q):
return atomic_form_factor_WK1995(Q, f_params[symbol])
return func
scattering_lengths: dictionary
Coherent scattering lengths averaged over isotopes and spins.
Supposed for INS. For example, {'Na': 3.63, 'Cl': 9.5770}.
freq_min, freq_min: float
Minimum and maximum phonon frequencies to determine whether
phonons are included in the calculation. | [
"Initialize",
"dynamic",
"structure",
"factor",
"calculation",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2378-L2445 | train | 222,403 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.run_dynamic_structure_factor | def run_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor().
"""
self.init_dynamic_structure_factor(
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max)
self._dynamic_structure_factor.run() | python | def run_dynamic_structure_factor(self,
Qpoints,
T,
atomic_form_factor_func=None,
scattering_lengths=None,
freq_min=None,
freq_max=None):
"""Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor().
"""
self.init_dynamic_structure_factor(
Qpoints,
T,
atomic_form_factor_func=atomic_form_factor_func,
scattering_lengths=scattering_lengths,
freq_min=freq_min,
freq_max=freq_max)
self._dynamic_structure_factor.run() | [
"def",
"run_dynamic_structure_factor",
"(",
"self",
",",
"Qpoints",
",",
"T",
",",
"atomic_form_factor_func",
"=",
"None",
",",
"scattering_lengths",
"=",
"None",
",",
"freq_min",
"=",
"None",
",",
"freq_max",
"=",
"None",
")",
":",
"self",
".",
"init_dynamic_... | Run dynamic structure factor calculation
See the detail of parameters at
Phonopy.init_dynamic_structure_factor(). | [
"Run",
"dynamic",
"structure",
"factor",
"calculation"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2447-L2468 | train | 222,404 |
atztogo/phonopy | phonopy/api_phonopy.py | Phonopy.save | def save(self,
filename="phonopy_params.yaml",
settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True}
"""
phpy_yaml = PhonopyYaml(calculator=self._calculator,
settings=settings)
phpy_yaml.set_phonon_info(self)
with open(filename, 'w') as w:
w.write(str(phpy_yaml)) | python | def save(self,
filename="phonopy_params.yaml",
settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True}
"""
phpy_yaml = PhonopyYaml(calculator=self._calculator,
settings=settings)
phpy_yaml.set_phonon_info(self)
with open(filename, 'w') as w:
w.write(str(phpy_yaml)) | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"\"phonopy_params.yaml\"",
",",
"settings",
"=",
"None",
")",
":",
"phpy_yaml",
"=",
"PhonopyYaml",
"(",
"calculator",
"=",
"self",
".",
"_calculator",
",",
"settings",
"=",
"settings",
")",
"phpy_yaml",
".",... | Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameters are written out. Only
the settings expected to be updated from the following
default settings are needed to be set in the dictionary.
The possible parameters and their default settings are:
{'force_sets': True,
'displacements': True,
'force_constants': False,
'born_effective_charge': True,
'dielectric_constant': True} | [
"Save",
"parameters",
"in",
"Phonopy",
"instants",
"into",
"file",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L2520-L2545 | train | 222,405 |
atztogo/phonopy | phonopy/phonon/mesh.py | length2mesh | def length2mesh(length, lattice, rotations=None):
"""Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,)
"""
rec_lattice = np.linalg.inv(lattice)
rec_lat_lengths = np.sqrt(np.diagonal(np.dot(rec_lattice.T, rec_lattice)))
mesh_numbers = np.rint(rec_lat_lengths * length).astype(int)
if rotations is not None:
reclat_equiv = get_lattice_vector_equivalence(
[r.T for r in np.array(rotations)])
m = mesh_numbers
mesh_equiv = [m[1] == m[2], m[2] == m[0], m[0] == m[1]]
for i, pair in enumerate(([1, 2], [2, 0], [0, 1])):
if reclat_equiv[i] and not mesh_equiv:
m[pair] = max(m[pair])
return np.maximum(mesh_numbers, [1, 1, 1]) | python | def length2mesh(length, lattice, rotations=None):
"""Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,)
"""
rec_lattice = np.linalg.inv(lattice)
rec_lat_lengths = np.sqrt(np.diagonal(np.dot(rec_lattice.T, rec_lattice)))
mesh_numbers = np.rint(rec_lat_lengths * length).astype(int)
if rotations is not None:
reclat_equiv = get_lattice_vector_equivalence(
[r.T for r in np.array(rotations)])
m = mesh_numbers
mesh_equiv = [m[1] == m[2], m[2] == m[0], m[0] == m[1]]
for i, pair in enumerate(([1, 2], [2, 0], [0, 1])):
if reclat_equiv[i] and not mesh_equiv:
m[pair] = max(m[pair])
return np.maximum(mesh_numbers, [1, 1, 1]) | [
"def",
"length2mesh",
"(",
"length",
",",
"lattice",
",",
"rotations",
"=",
"None",
")",
":",
"rec_lattice",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"lattice",
")",
"rec_lat_lengths",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"diagonal",
"(",
"np",
... | Convert length to mesh for q-point sampling
This conversion for each reciprocal axis follows VASP convention by
N = max(1, int(l * |a|^* + 0.5))
'int' means rounding down, not rounding to nearest integer.
Parameters
----------
length : float
Length having the unit of direct space length.
lattice : array_like
Basis vectors of primitive cell in row vectors.
dtype='double', shape=(3, 3)
rotations: array_like, optional
Rotation matrices in real space. When given, mesh numbers that are
symmetrically reasonable are returned. Default is None.
dtype='intc', shape=(rotations, 3, 3)
Returns
-------
array_like
dtype=int, shape=(3,) | [
"Convert",
"length",
"to",
"mesh",
"for",
"q",
"-",
"point",
"sampling"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/mesh.py#L41-L80 | train | 222,406 |
atztogo/phonopy | phonopy/phonon/thermal_displacement.py | ThermalMotion._get_population | def _get_population(self, freq, t): # freq in THz
"""Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t
"""
condition = t > 1.0
if type(condition) == bool or type(condition) == np.bool_:
if condition:
return 1.0 / (np.exp(freq * THzToEv / (Kb * t)) - 1)
else:
return 0.0
else:
vals = np.zeros(len(t), dtype='double')
vals[condition] = 1.0 / (
np.exp(freq * THzToEv / (Kb * t[condition])) - 1)
return vals | python | def _get_population(self, freq, t): # freq in THz
"""Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t
"""
condition = t > 1.0
if type(condition) == bool or type(condition) == np.bool_:
if condition:
return 1.0 / (np.exp(freq * THzToEv / (Kb * t)) - 1)
else:
return 0.0
else:
vals = np.zeros(len(t), dtype='double')
vals[condition] = 1.0 / (
np.exp(freq * THzToEv / (Kb * t[condition])) - 1)
return vals | [
"def",
"_get_population",
"(",
"self",
",",
"freq",
",",
"t",
")",
":",
"# freq in THz",
"condition",
"=",
"t",
">",
"1.0",
"if",
"type",
"(",
"condition",
")",
"==",
"bool",
"or",
"type",
"(",
"condition",
")",
"==",
"np",
".",
"bool_",
":",
"if",
... | Return phonon population number
Three types of combinations of array inputs are possible.
- single freq and single t
- single freq and len(t) > 1
- len(freq) > 1 and single t | [
"Return",
"phonon",
"population",
"number"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/thermal_displacement.py#L101-L120 | train | 222,407 |
atztogo/phonopy | phonopy/phonon/thermal_displacement.py | ThermalDisplacements._project_eigenvectors | def _project_eigenvectors(self):
"""Eigenvectors are projected along Cartesian direction"""
self._p_eigenvectors = []
for vecs_q in self._eigenvectors:
p_vecs_q = []
for vecs in vecs_q.T:
p_vecs_q.append(np.dot(vecs.reshape(-1, 3),
self._projection_direction))
self._p_eigenvectors.append(np.transpose(p_vecs_q))
self._p_eigenvectors = np.array(self._p_eigenvectors) | python | def _project_eigenvectors(self):
"""Eigenvectors are projected along Cartesian direction"""
self._p_eigenvectors = []
for vecs_q in self._eigenvectors:
p_vecs_q = []
for vecs in vecs_q.T:
p_vecs_q.append(np.dot(vecs.reshape(-1, 3),
self._projection_direction))
self._p_eigenvectors.append(np.transpose(p_vecs_q))
self._p_eigenvectors = np.array(self._p_eigenvectors) | [
"def",
"_project_eigenvectors",
"(",
"self",
")",
":",
"self",
".",
"_p_eigenvectors",
"=",
"[",
"]",
"for",
"vecs_q",
"in",
"self",
".",
"_eigenvectors",
":",
"p_vecs_q",
"=",
"[",
"]",
"for",
"vecs",
"in",
"vecs_q",
".",
"T",
":",
"p_vecs_q",
".",
"a... | Eigenvectors are projected along Cartesian direction | [
"Eigenvectors",
"are",
"projected",
"along",
"Cartesian",
"direction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/thermal_displacement.py#L226-L236 | train | 222,408 |
atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry | def get_symmetry(cell, symprec=1e-5, angle_tolerance=-1.0):
"""This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes.
"""
_set_no_error()
lattice, positions, numbers, magmoms = _expand_cell(cell)
if lattice is None:
return None
multi = 48 * len(positions)
rotation = np.zeros((multi, 3, 3), dtype='intc')
translation = np.zeros((multi, 3), dtype='double')
# Get symmetry operations
if magmoms is None:
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
else:
return {'rotations': dataset['rotations'],
'translations': dataset['translations'],
'equivalent_atoms': dataset['equivalent_atoms']}
else:
equivalent_atoms = np.zeros(len(magmoms), dtype='intc')
num_sym = spg.symmetry_with_collinear_spin(rotation,
translation,
equivalent_atoms,
lattice,
positions,
numbers,
magmoms,
symprec,
angle_tolerance)
_set_error_message()
if num_sym == 0:
return None
else:
return {'rotations': np.array(rotation[:num_sym],
dtype='intc', order='C'),
'translations': np.array(translation[:num_sym],
dtype='double', order='C'),
'equivalent_atoms': equivalent_atoms} | python | def get_symmetry(cell, symprec=1e-5, angle_tolerance=-1.0):
"""This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes.
"""
_set_no_error()
lattice, positions, numbers, magmoms = _expand_cell(cell)
if lattice is None:
return None
multi = 48 * len(positions)
rotation = np.zeros((multi, 3, 3), dtype='intc')
translation = np.zeros((multi, 3), dtype='double')
# Get symmetry operations
if magmoms is None:
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
else:
return {'rotations': dataset['rotations'],
'translations': dataset['translations'],
'equivalent_atoms': dataset['equivalent_atoms']}
else:
equivalent_atoms = np.zeros(len(magmoms), dtype='intc')
num_sym = spg.symmetry_with_collinear_spin(rotation,
translation,
equivalent_atoms,
lattice,
positions,
numbers,
magmoms,
symprec,
angle_tolerance)
_set_error_message()
if num_sym == 0:
return None
else:
return {'rotations': np.array(rotation[:num_sym],
dtype='intc', order='C'),
'translations': np.array(translation[:num_sym],
dtype='double', order='C'),
'equivalent_atoms': equivalent_atoms} | [
"def",
"get_symmetry",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"magmoms",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"latt... | This gives crystal symmetry operations from a crystal structure.
Args:
cell: Crystal structrue given either in Atoms object or tuple.
In the case given by a tuple, it has to follow the form below,
(Lattice parameters in a 3x3 array (see the detail below),
Fractional atomic positions in an Nx3 array,
Integer numbers to distinguish species in a length N array,
(optional) Collinear magnetic moments in a length N array),
where N is the number of atoms.
Lattice parameters are given in the form:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Symmetry search tolerance in the unit of length.
angle_tolerance:
float: Symmetry search tolerance in the unit of angle deg.
If the value is negative, an internally optimized routine
is used to judge symmetry.
Return:
A dictionary: Rotation parts and translation parts. Dictionary keys:
'rotations': Gives the numpy 'intc' array of the rotation matrices.
'translations': Gives the numpy 'double' array of fractional
translations with respect to a, b, c axes. | [
"This",
"gives",
"crystal",
"symmetry",
"operations",
"from",
"a",
"crystal",
"structure",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L51-L120 | train | 222,409 |
atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry_dataset | def get_symmetry_dataset(cell,
symprec=1e-5,
angle_tolerance=-1.0,
hall_number=0):
"""Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
spg_ds = spg.dataset(lattice, positions, numbers, hall_number,
symprec, angle_tolerance)
if spg_ds is None:
_set_error_message()
return None
keys = ('number',
'hall_number',
'international',
'hall',
'choice',
'transformation_matrix',
'origin_shift',
'rotations',
'translations',
'wyckoffs',
'site_symmetry_symbols',
'equivalent_atoms',
'mapping_to_primitive',
'std_lattice',
'std_types',
'std_positions',
'std_rotation_matrix',
'std_mapping_to_primitive',
# 'pointgroup_number',
'pointgroup')
dataset = {}
for key, data in zip(keys, spg_ds):
dataset[key] = data
dataset['international'] = dataset['international'].strip()
dataset['hall'] = dataset['hall'].strip()
dataset['choice'] = dataset['choice'].strip()
dataset['transformation_matrix'] = np.array(
dataset['transformation_matrix'], dtype='double', order='C')
dataset['origin_shift'] = np.array(dataset['origin_shift'], dtype='double')
dataset['rotations'] = np.array(dataset['rotations'],
dtype='intc', order='C')
dataset['translations'] = np.array(dataset['translations'],
dtype='double', order='C')
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']]
dataset['site_symmetry_symbols'] = [
s.strip() for s in dataset['site_symmetry_symbols']]
dataset['equivalent_atoms'] = np.array(dataset['equivalent_atoms'],
dtype='intc')
dataset['mapping_to_primitive'] = np.array(dataset['mapping_to_primitive'],
dtype='intc')
dataset['std_lattice'] = np.array(np.transpose(dataset['std_lattice']),
dtype='double', order='C')
dataset['std_types'] = np.array(dataset['std_types'], dtype='intc')
dataset['std_positions'] = np.array(dataset['std_positions'],
dtype='double', order='C')
dataset['std_rotation_matrix'] = np.array(dataset['std_rotation_matrix'],
dtype='double', order='C')
dataset['std_mapping_to_primitive'] = np.array(
dataset['std_mapping_to_primitive'], dtype='intc')
dataset['pointgroup'] = dataset['pointgroup'].strip()
_set_error_message()
return dataset | python | def get_symmetry_dataset(cell,
symprec=1e-5,
angle_tolerance=-1.0,
hall_number=0):
"""Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
spg_ds = spg.dataset(lattice, positions, numbers, hall_number,
symprec, angle_tolerance)
if spg_ds is None:
_set_error_message()
return None
keys = ('number',
'hall_number',
'international',
'hall',
'choice',
'transformation_matrix',
'origin_shift',
'rotations',
'translations',
'wyckoffs',
'site_symmetry_symbols',
'equivalent_atoms',
'mapping_to_primitive',
'std_lattice',
'std_types',
'std_positions',
'std_rotation_matrix',
'std_mapping_to_primitive',
# 'pointgroup_number',
'pointgroup')
dataset = {}
for key, data in zip(keys, spg_ds):
dataset[key] = data
dataset['international'] = dataset['international'].strip()
dataset['hall'] = dataset['hall'].strip()
dataset['choice'] = dataset['choice'].strip()
dataset['transformation_matrix'] = np.array(
dataset['transformation_matrix'], dtype='double', order='C')
dataset['origin_shift'] = np.array(dataset['origin_shift'], dtype='double')
dataset['rotations'] = np.array(dataset['rotations'],
dtype='intc', order='C')
dataset['translations'] = np.array(dataset['translations'],
dtype='double', order='C')
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']]
dataset['site_symmetry_symbols'] = [
s.strip() for s in dataset['site_symmetry_symbols']]
dataset['equivalent_atoms'] = np.array(dataset['equivalent_atoms'],
dtype='intc')
dataset['mapping_to_primitive'] = np.array(dataset['mapping_to_primitive'],
dtype='intc')
dataset['std_lattice'] = np.array(np.transpose(dataset['std_lattice']),
dtype='double', order='C')
dataset['std_types'] = np.array(dataset['std_types'], dtype='intc')
dataset['std_positions'] = np.array(dataset['std_positions'],
dtype='double', order='C')
dataset['std_rotation_matrix'] = np.array(dataset['std_rotation_matrix'],
dtype='double', order='C')
dataset['std_mapping_to_primitive'] = np.array(
dataset['std_mapping_to_primitive'], dtype='intc')
dataset['pointgroup'] = dataset['pointgroup'].strip()
_set_error_message()
return dataset | [
"def",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",... | Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionary is returned. Dictionary keys:
number (int): International space group number
international (str): International symbol
hall (str): Hall symbol
choice (str): Centring, origin, basis vector setting
transformation_matrix (3x3 float):
Transformation matrix from input lattice to standardized
lattice:
L^original = L^standardized * Tmat
origin shift (3 float):
Origin shift from standardized to input origin
rotations (3x3 int), translations (float vector):
Rotation matrices and translation vectors. Space group
operations are obtained by
[(r,t) for r, t in zip(rotations, translations)]
wyckoffs (n char): Wyckoff letters
equivalent_atoms (n int): Symmetrically equivalent atoms
mapping_to_primitive (n int):
Original cell atom index mapping to primivie cell atom index
Idealized standardized unit cell:
std_lattice (3x3 float, row vectors),
std_positions (Nx3 float), std_types (N int)
std_rotation_matrix:
Rigid rotation matrix to rotate from standardized basis
vectors to idealized standardized basis vectors
L^idealized = R * L^standardized
std_mapping_to_primitive (m int):
std_positions index mapping to those of primivie cell atoms
pointgroup (str): Pointgroup symbol
If it fails, None is returned. | [
"Search",
"symmetry",
"dataset",
"from",
"an",
"input",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L123-L235 | train | 222,410 |
atztogo/phonopy | phonopy/structure/spglib.py | get_spacegroup | def get_spacegroup(cell, symprec=1e-5, angle_tolerance=-1.0, symbol_type=0):
"""Return space group in international table symbol and number as a string.
If it fails, None is returned.
"""
_set_no_error()
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
spg_type = get_spacegroup_type(dataset['hall_number'])
if symbol_type == 1:
return "%s (%d)" % (spg_type['schoenflies'], dataset['number'])
else:
return "%s (%d)" % (spg_type['international_short'], dataset['number']) | python | def get_spacegroup(cell, symprec=1e-5, angle_tolerance=-1.0, symbol_type=0):
"""Return space group in international table symbol and number as a string.
If it fails, None is returned.
"""
_set_no_error()
dataset = get_symmetry_dataset(cell,
symprec=symprec,
angle_tolerance=angle_tolerance)
if dataset is None:
return None
spg_type = get_spacegroup_type(dataset['hall_number'])
if symbol_type == 1:
return "%s (%d)" % (spg_type['schoenflies'], dataset['number'])
else:
return "%s (%d)" % (spg_type['international_short'], dataset['number']) | [
"def",
"get_spacegroup",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"symbol_type",
"=",
"0",
")",
":",
"_set_no_error",
"(",
")",
"dataset",
"=",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"sympre... | Return space group in international table symbol and number as a string.
If it fails, None is returned. | [
"Return",
"space",
"group",
"in",
"international",
"table",
"symbol",
"and",
"number",
"as",
"a",
"string",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L238-L255 | train | 222,411 |
atztogo/phonopy | phonopy/structure/spglib.py | get_hall_number_from_symmetry | def get_hall_number_from_symmetry(rotations, translations, symprec=1e-5):
"""Hall number is obtained from a set of symmetry operations.
If it fails, None is returned.
"""
r = np.array(rotations, dtype='intc', order='C')
t = np.array(translations, dtype='double', order='C')
hall_number = spg.hall_number_from_symmetry(r, t, symprec)
return hall_number | python | def get_hall_number_from_symmetry(rotations, translations, symprec=1e-5):
"""Hall number is obtained from a set of symmetry operations.
If it fails, None is returned.
"""
r = np.array(rotations, dtype='intc', order='C')
t = np.array(translations, dtype='double', order='C')
hall_number = spg.hall_number_from_symmetry(r, t, symprec)
return hall_number | [
"def",
"get_hall_number_from_symmetry",
"(",
"rotations",
",",
"translations",
",",
"symprec",
"=",
"1e-5",
")",
":",
"r",
"=",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order",
"=",
"'C'",
")",
"t",
"=",
"np",
".",
"arra... | Hall number is obtained from a set of symmetry operations.
If it fails, None is returned. | [
"Hall",
"number",
"is",
"obtained",
"from",
"a",
"set",
"of",
"symmetry",
"operations",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L258-L267 | train | 222,412 |
atztogo/phonopy | phonopy/structure/spglib.py | get_spacegroup_type | def get_spacegroup_type(hall_number):
"""Translate Hall number to space group type information.
If it fails, None is returned.
"""
_set_no_error()
keys = ('number',
'international_short',
'international_full',
'international',
'schoenflies',
'hall_symbol',
'choice',
'pointgroup_schoenflies',
'pointgroup_international',
'arithmetic_crystal_class_number',
'arithmetic_crystal_class_symbol')
spg_type_list = spg.spacegroup_type(hall_number)
_set_error_message()
if spg_type_list is not None:
spg_type = dict(zip(keys, spg_type_list))
for key in spg_type:
if key != 'number' and key != 'arithmetic_crystal_class_number':
spg_type[key] = spg_type[key].strip()
return spg_type
else:
return None | python | def get_spacegroup_type(hall_number):
"""Translate Hall number to space group type information.
If it fails, None is returned.
"""
_set_no_error()
keys = ('number',
'international_short',
'international_full',
'international',
'schoenflies',
'hall_symbol',
'choice',
'pointgroup_schoenflies',
'pointgroup_international',
'arithmetic_crystal_class_number',
'arithmetic_crystal_class_symbol')
spg_type_list = spg.spacegroup_type(hall_number)
_set_error_message()
if spg_type_list is not None:
spg_type = dict(zip(keys, spg_type_list))
for key in spg_type:
if key != 'number' and key != 'arithmetic_crystal_class_number':
spg_type[key] = spg_type[key].strip()
return spg_type
else:
return None | [
"def",
"get_spacegroup_type",
"(",
"hall_number",
")",
":",
"_set_no_error",
"(",
")",
"keys",
"=",
"(",
"'number'",
",",
"'international_short'",
",",
"'international_full'",
",",
"'international'",
",",
"'schoenflies'",
",",
"'hall_symbol'",
",",
"'choice'",
",",
... | Translate Hall number to space group type information.
If it fails, None is returned. | [
"Translate",
"Hall",
"number",
"to",
"space",
"group",
"type",
"information",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L270-L298 | train | 222,413 |
atztogo/phonopy | phonopy/structure/spglib.py | get_pointgroup | def get_pointgroup(rotations):
"""Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m "
"""
_set_no_error()
# (symbol, pointgroup_number, transformation_matrix)
pointgroup = spg.pointgroup(np.array(rotations, dtype='intc', order='C'))
_set_error_message()
return pointgroup | python | def get_pointgroup(rotations):
"""Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m "
"""
_set_no_error()
# (symbol, pointgroup_number, transformation_matrix)
pointgroup = spg.pointgroup(np.array(rotations, dtype='intc', order='C'))
_set_error_message()
return pointgroup | [
"def",
"get_pointgroup",
"(",
"rotations",
")",
":",
"_set_no_error",
"(",
")",
"# (symbol, pointgroup_number, transformation_matrix)",
"pointgroup",
"=",
"spg",
".",
"pointgroup",
"(",
"np",
".",
"array",
"(",
"rotations",
",",
"dtype",
"=",
"'intc'",
",",
"order... | Return point group in international table symbol and number.
The symbols are mapped to the numbers as follows:
1 "1 "
2 "-1 "
3 "2 "
4 "m "
5 "2/m "
6 "222 "
7 "mm2 "
8 "mmm "
9 "4 "
10 "-4 "
11 "4/m "
12 "422 "
13 "4mm "
14 "-42m "
15 "4/mmm"
16 "3 "
17 "-3 "
18 "32 "
19 "3m "
20 "-3m "
21 "6 "
22 "-6 "
23 "6/m "
24 "622 "
25 "6mm "
26 "-62m "
27 "6/mmm"
28 "23 "
29 "m-3 "
30 "432 "
31 "-43m "
32 "m-3m " | [
"Return",
"point",
"group",
"in",
"international",
"table",
"symbol",
"and",
"number",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L301-L343 | train | 222,414 |
atztogo/phonopy | phonopy/structure/spglib.py | standardize_cell | def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, _positions, _numbers, _ = _expand_cell(cell)
if lattice is None:
return None
# Atomic positions have to be specified by scaled positions for spglib.
num_atom = len(_positions)
positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')
positions[:num_atom] = _positions
numbers = np.zeros(num_atom * 4, dtype='intc')
numbers[:num_atom] = _numbers
num_atom_std = spg.standardize_cell(lattice,
positions,
numbers,
num_atom,
to_primitive * 1,
no_idealize * 1,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_std > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_std], dtype='double', order='C'),
np.array(numbers[:num_atom_std], dtype='intc'))
else:
return None | python | def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, _positions, _numbers, _ = _expand_cell(cell)
if lattice is None:
return None
# Atomic positions have to be specified by scaled positions for spglib.
num_atom = len(_positions)
positions = np.zeros((num_atom * 4, 3), dtype='double', order='C')
positions[:num_atom] = _positions
numbers = np.zeros(num_atom * 4, dtype='intc')
numbers[:num_atom] = _numbers
num_atom_std = spg.standardize_cell(lattice,
positions,
numbers,
num_atom,
to_primitive * 1,
no_idealize * 1,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_std > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_std], dtype='double', order='C'),
np.array(numbers[:num_atom_std], dtype='intc'))
else:
return None | [
"def",
"standardize_cell",
"(",
"cell",
",",
"to_primitive",
"=",
"False",
",",
"no_idealize",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"_positions",
",",
"_num... | Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
basis vectors and positions of atoms according to crystal
symmetry.
Return:
The standardized unit cell or primitive cell is returned by a tuple of
(lattice, positions, numbers).
If it fails, None is returned. | [
"Return",
"standardized",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L346-L394 | train | 222,415 |
atztogo/phonopy | phonopy/structure/spglib.py | find_primitive | def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):
"""Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
num_atom_prim = spg.primitive(lattice,
positions,
numbers,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_prim > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_prim], dtype='double', order='C'),
np.array(numbers[:num_atom_prim], dtype='intc'))
else:
return None | python | def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):
"""Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned.
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
num_atom_prim = spg.primitive(lattice,
positions,
numbers,
symprec,
angle_tolerance)
_set_error_message()
if num_atom_prim > 0:
return (np.array(lattice.T, dtype='double', order='C'),
np.array(positions[:num_atom_prim], dtype='double', order='C'),
np.array(numbers[:num_atom_prim], dtype='intc'))
else:
return None | [
"def",
"find_primitive",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",
"(",
"cell",
")",
"if",
"lattice"... | Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned. | [
"Primitive",
"cell",
"is",
"searched",
"in",
"the",
"input",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L432-L456 | train | 222,416 |
atztogo/phonopy | phonopy/structure/spglib.py | get_symmetry_from_database | def get_symmetry_from_database(hall_number):
"""Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned.
"""
_set_no_error()
rotations = np.zeros((192, 3, 3), dtype='intc')
translations = np.zeros((192, 3), dtype='double')
num_sym = spg.symmetry_from_database(rotations, translations, hall_number)
_set_error_message()
if num_sym is None:
return None
else:
return {'rotations':
np.array(rotations[:num_sym], dtype='intc', order='C'),
'translations':
np.array(translations[:num_sym], dtype='double', order='C')} | python | def get_symmetry_from_database(hall_number):
"""Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned.
"""
_set_no_error()
rotations = np.zeros((192, 3, 3), dtype='intc')
translations = np.zeros((192, 3), dtype='double')
num_sym = spg.symmetry_from_database(rotations, translations, hall_number)
_set_error_message()
if num_sym is None:
return None
else:
return {'rotations':
np.array(rotations[:num_sym], dtype='intc', order='C'),
'translations':
np.array(translations[:num_sym], dtype='double', order='C')} | [
"def",
"get_symmetry_from_database",
"(",
"hall_number",
")",
":",
"_set_no_error",
"(",
")",
"rotations",
"=",
"np",
".",
"zeros",
"(",
"(",
"192",
",",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'intc'",
")",
"translations",
"=",
"np",
".",
"zeros",
"("... | Return symmetry operations corresponding to a Hall symbol.
The Hall symbol is given by the serial number in between 1 and 530.
The symmetry operations are given by a dictionary whose keys are
'rotations' and 'translations'.
If it fails, None is returned. | [
"Return",
"symmetry",
"operations",
"corresponding",
"to",
"a",
"Hall",
"symbol",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L459-L480 | train | 222,417 |
atztogo/phonopy | phonopy/structure/spglib.py | get_grid_point_from_address | def get_grid_point_from_address(grid_address, mesh):
"""Return grid point index by tranlating grid address"""
_set_no_error()
return spg.grid_point_from_address(np.array(grid_address, dtype='intc'),
np.array(mesh, dtype='intc')) | python | def get_grid_point_from_address(grid_address, mesh):
"""Return grid point index by tranlating grid address"""
_set_no_error()
return spg.grid_point_from_address(np.array(grid_address, dtype='intc'),
np.array(mesh, dtype='intc')) | [
"def",
"get_grid_point_from_address",
"(",
"grid_address",
",",
"mesh",
")",
":",
"_set_no_error",
"(",
")",
"return",
"spg",
".",
"grid_point_from_address",
"(",
"np",
".",
"array",
"(",
"grid_address",
",",
"dtype",
"=",
"'intc'",
")",
",",
"np",
".",
"arr... | Return grid point index by tranlating grid address | [
"Return",
"grid",
"point",
"index",
"by",
"tranlating",
"grid",
"address"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L486-L491 | train | 222,418 |
atztogo/phonopy | phonopy/structure/spglib.py | get_ir_reciprocal_mesh | def get_ir_reciprocal_mesh(mesh,
cell,
is_shift=None,
is_time_reversal=True,
symprec=1e-5,
is_dense=False):
"""Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3)
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if spg.ir_reciprocal_mesh(
grid_address,
grid_mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
lattice,
positions,
numbers,
symprec) > 0:
return grid_mapping_table, grid_address
else:
return None | python | def get_ir_reciprocal_mesh(mesh,
cell,
is_shift=None,
is_time_reversal=True,
symprec=1e-5,
is_dense=False):
"""Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3)
"""
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
grid_mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if spg.ir_reciprocal_mesh(
grid_address,
grid_mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
lattice,
positions,
numbers,
symprec) > 0:
return grid_mapping_table, grid_address
else:
return None | [
"def",
"get_ir_reciprocal_mesh",
"(",
"mesh",
",",
"cell",
",",
"is_shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"symprec",
"=",
"1e-5",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
","... | Return k-points mesh and k-point map to the irreducible k-points.
The symmetry is serched from the input cell.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
cell : spglib cell tuple
Crystal structure.
is_shift : array_like, optional
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
Default is None which equals to [0, 0, 0].
dtype='intc', shape=(3,)
is_time_reversal : bool, optional
Whether time reversal symmetry is included or not. Default is True.
symprec : float, optional
Symmetry tolerance in distance. Default is 1e-5.
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc' or 'uintp', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points.
dtype='intc', shspe=(prod(mesh), 3) | [
"Return",
"k",
"-",
"points",
"mesh",
"and",
"k",
"-",
"point",
"map",
"to",
"the",
"irreducible",
"k",
"-",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L494-L559 | train | 222,419 |
atztogo/phonopy | phonopy/structure/spglib.py | get_stabilized_reciprocal_mesh | def get_stabilized_reciprocal_mesh(mesh,
rotations,
is_shift=None,
is_time_reversal=True,
qpoints=None,
is_dense=False):
"""Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3)
"""
_set_no_error()
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if qpoints is None:
qpoints = np.array([[0, 0, 0]], dtype='double', order='C')
else:
qpoints = np.array(qpoints, dtype='double', order='C')
if qpoints.shape == (3,):
qpoints = np.array([qpoints], dtype='double', order='C')
if spg.stabilized_reciprocal_mesh(
grid_address,
mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
qpoints) > 0:
return mapping_table, grid_address
else:
return None | python | def get_stabilized_reciprocal_mesh(mesh,
rotations,
is_shift=None,
is_time_reversal=True,
qpoints=None,
is_dense=False):
"""Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3)
"""
_set_no_error()
if is_dense:
dtype = 'uintp'
else:
dtype = 'intc'
mapping_table = np.zeros(np.prod(mesh), dtype=dtype)
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
if is_shift is None:
is_shift = [0, 0, 0]
if qpoints is None:
qpoints = np.array([[0, 0, 0]], dtype='double', order='C')
else:
qpoints = np.array(qpoints, dtype='double', order='C')
if qpoints.shape == (3,):
qpoints = np.array([qpoints], dtype='double', order='C')
if spg.stabilized_reciprocal_mesh(
grid_address,
mapping_table,
np.array(mesh, dtype='intc'),
np.array(is_shift, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
qpoints) > 0:
return mapping_table, grid_address
else:
return None | [
"def",
"get_stabilized_reciprocal_mesh",
"(",
"mesh",
",",
"rotations",
",",
"is_shift",
"=",
"None",
",",
"is_time_reversal",
"=",
"True",
",",
"qpoints",
"=",
"None",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"if",
"is_dense",
":"... | Return k-point map to the irreducible k-points and k-point grid points.
The symmetry is searched from the input rotation matrices in real space.
Parameters
----------
mesh : array_like
Uniform sampling mesh numbers.
dtype='intc', shape=(3,)
rotations : array_like
Rotation matrices with respect to real space basis vectors.
dtype='intc', shape=(rotations, 3)
is_shift : array_like
[0, 0, 0] gives Gamma center mesh and value 1 gives half mesh shift.
dtype='intc', shape=(3,)
is_time_reversal : bool
Time reversal symmetry is included or not.
qpoints : array_like
q-points used as stabilizer(s) given in reciprocal space with respect
to reciprocal basis vectors.
dtype='double', shape=(qpoints ,3) or (3,)
is_dense : bool, optional
grid_mapping_table is returned with dtype='uintp' if True. Otherwise
its dtype='intc'. Default is False.
Returns
-------
grid_mapping_table : ndarray
Grid point mapping table to ir-gird-points.
dtype='intc', shape=(prod(mesh),)
grid_address : ndarray
Address of all grid points. Each address is given by three unsigned
integers.
dtype='intc', shape=(prod(mesh), 3) | [
"Return",
"k",
"-",
"point",
"map",
"to",
"the",
"irreducible",
"k",
"-",
"points",
"and",
"k",
"-",
"point",
"grid",
"points",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L562-L631 | train | 222,420 |
atztogo/phonopy | phonopy/structure/spglib.py | relocate_BZ_grid_address | def relocate_BZ_grid_address(grid_address,
mesh,
reciprocal_lattice, # column vectors
is_shift=None,
is_dense=False):
"""Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map).
"""
_set_no_error()
if is_shift is None:
_is_shift = np.zeros(3, dtype='intc')
else:
_is_shift = np.array(is_shift, dtype='intc')
bz_grid_address = np.zeros((np.prod(np.add(mesh, 1)), 3), dtype='intc')
bz_map = np.zeros(np.prod(np.multiply(mesh, 2)), dtype='uintp')
num_bz_ir = spg.BZ_grid_address(
bz_grid_address,
bz_map,
grid_address,
np.array(mesh, dtype='intc'),
np.array(reciprocal_lattice, dtype='double', order='C'),
_is_shift)
if is_dense:
return bz_grid_address[:num_bz_ir], bz_map
else:
return bz_grid_address[:num_bz_ir], np.array(bz_map, dtype='intc') | python | def relocate_BZ_grid_address(grid_address,
mesh,
reciprocal_lattice, # column vectors
is_shift=None,
is_dense=False):
"""Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map).
"""
_set_no_error()
if is_shift is None:
_is_shift = np.zeros(3, dtype='intc')
else:
_is_shift = np.array(is_shift, dtype='intc')
bz_grid_address = np.zeros((np.prod(np.add(mesh, 1)), 3), dtype='intc')
bz_map = np.zeros(np.prod(np.multiply(mesh, 2)), dtype='uintp')
num_bz_ir = spg.BZ_grid_address(
bz_grid_address,
bz_map,
grid_address,
np.array(mesh, dtype='intc'),
np.array(reciprocal_lattice, dtype='double', order='C'),
_is_shift)
if is_dense:
return bz_grid_address[:num_bz_ir], bz_map
else:
return bz_grid_address[:num_bz_ir], np.array(bz_map, dtype='intc') | [
"def",
"relocate_BZ_grid_address",
"(",
"grid_address",
",",
"mesh",
",",
"reciprocal_lattice",
",",
"# column vectors",
"is_shift",
"=",
"None",
",",
"is_dense",
"=",
"False",
")",
":",
"_set_no_error",
"(",
")",
"if",
"is_shift",
"is",
"None",
":",
"_is_shift"... | Grid addresses are relocated to be inside first Brillouin zone.
Number of ir-grid-points inside Brillouin zone is returned.
It is assumed that the following arrays have the shapes of
bz_grid_address : (num_grid_points_in_FBZ, 3)
bz_map (prod(mesh * 2), )
Note that the shape of grid_address is (prod(mesh), 3) and the
addresses in grid_address are arranged to be in parallelepiped
made of reciprocal basis vectors. The addresses in bz_grid_address
are inside the first Brillouin zone or on its surface. Each
address in grid_address is mapped to one of those in
bz_grid_address by a reciprocal lattice vector (including zero
vector) with keeping element order. For those inside first
Brillouin zone, the mapping is one-to-one. For those on the first
Brillouin zone surface, more than one addresses in bz_grid_address
that are equivalent by the reciprocal lattice translations are
mapped to one address in grid_address. In this case, those grid
points except for one of them are appended to the tail of this array,
for which bz_grid_address has the following data storing:
|------------------array size of bz_grid_address-------------------------|
|--those equivalent to grid_address--|--those on surface except for one--|
|-----array size of grid_address-----|
Number of grid points stored in bz_grid_address is returned.
bz_map is used to recover grid point index expanded to include BZ
surface from grid address. The grid point indices are mapped to
(mesh[0] * 2) x (mesh[1] * 2) x (mesh[2] * 2) space (bz_map). | [
"Grid",
"addresses",
"are",
"relocated",
"to",
"be",
"inside",
"first",
"Brillouin",
"zone",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L751-L806 | train | 222,421 |
atztogo/phonopy | phonopy/structure/spglib.py | delaunay_reduce | def delaunay_reduce(lattice, eps=1e-5):
"""Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
delaunay_lattice = np.array(np.transpose(lattice),
dtype='double', order='C')
result = spg.delaunay_reduce(delaunay_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(delaunay_lattice),
dtype='double', order='C') | python | def delaunay_reduce(lattice, eps=1e-5):
"""Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
delaunay_lattice = np.array(np.transpose(lattice),
dtype='double', order='C')
result = spg.delaunay_reduce(delaunay_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(delaunay_lattice),
dtype='double', order='C') | [
"def",
"delaunay_reduce",
"(",
"lattice",
",",
"eps",
"=",
"1e-5",
")",
":",
"_set_no_error",
"(",
")",
"delaunay_lattice",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C... | Run Delaunay reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
symprec:
float: Tolerance to check if volume is close to zero or not and
if two basis vectors are orthogonal by the value of dot
product being close to zero or not.
Returns:
if the Delaunay reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned. | [
"Run",
"Delaunay",
"reduction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L809-L841 | train | 222,422 |
atztogo/phonopy | phonopy/structure/spglib.py | niggli_reduce | def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')
result = spg.niggli_reduce(niggli_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(niggli_lattice),
dtype='double', order='C') | python | def niggli_reduce(lattice, eps=1e-5):
"""Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned.
"""
_set_no_error()
niggli_lattice = np.array(np.transpose(lattice), dtype='double', order='C')
result = spg.niggli_reduce(niggli_lattice, float(eps))
_set_error_message()
if result == 0:
return None
else:
return np.array(np.transpose(niggli_lattice),
dtype='double', order='C') | [
"def",
"niggli_reduce",
"(",
"lattice",
",",
"eps",
"=",
"1e-5",
")",
":",
"_set_no_error",
"(",
")",
"niggli_lattice",
"=",
"np",
".",
"array",
"(",
"np",
".",
"transpose",
"(",
"lattice",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
... | Run Niggli reduction
Args:
lattice: Lattice parameters in the form of
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
eps:
float: Tolerance to check if difference of norms of two basis
vectors is close to zero or not and if two basis vectors are
orthogonal by the value of dot product being close to zero or
not. The detail is shown at
https://atztogo.github.io/niggli/.
Returns:
if the Niggli reduction succeeded:
Reduced lattice parameters are given as a numpy 'double' array:
[[a_x, a_y, a_z],
[b_x, b_y, b_z],
[c_x, c_y, c_z]]
otherwise None is returned. | [
"Run",
"Niggli",
"reduction"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L844-L877 | train | 222,423 |
atztogo/phonopy | phonopy/file_IO.py | get_FORCE_SETS_lines | def get_FORCE_SETS_lines(dataset, forces=None):
"""Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset.
"""
if 'first_atoms' in dataset:
return _get_FORCE_SETS_lines_type1(dataset, forces=forces)
elif 'forces' in dataset:
return _get_FORCE_SETS_lines_type2(dataset) | python | def get_FORCE_SETS_lines(dataset, forces=None):
"""Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset.
"""
if 'first_atoms' in dataset:
return _get_FORCE_SETS_lines_type1(dataset, forces=forces)
elif 'forces' in dataset:
return _get_FORCE_SETS_lines_type2(dataset) | [
"def",
"get_FORCE_SETS_lines",
"(",
"dataset",
",",
"forces",
"=",
"None",
")",
":",
"if",
"'first_atoms'",
"in",
"dataset",
":",
"return",
"_get_FORCE_SETS_lines_type1",
"(",
"dataset",
",",
"forces",
"=",
"forces",
")",
"elif",
"'forces'",
"in",
"dataset",
"... | Generate FORCE_SETS string
See the format of dataset in the docstring of
Phonopy.set_displacement_dataset. Optionally for the type-1 (traditional)
format, forces can be given. In this case, sets of forces are
unnecessary to be stored in the dataset. | [
"Generate",
"FORCE_SETS",
"string"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L52-L65 | train | 222,424 |
atztogo/phonopy | phonopy/file_IO.py | write_FORCE_CONSTANTS | def write_FORCE_CONSTANTS(force_constants,
filename='FORCE_CONSTANTS',
p2s_map=None):
"""Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc
"""
lines = get_FORCE_CONSTANTS_lines(force_constants, p2s_map=p2s_map)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | python | def write_FORCE_CONSTANTS(force_constants,
filename='FORCE_CONSTANTS',
p2s_map=None):
"""Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc
"""
lines = get_FORCE_CONSTANTS_lines(force_constants, p2s_map=p2s_map)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | [
"def",
"write_FORCE_CONSTANTS",
"(",
"force_constants",
",",
"filename",
"=",
"'FORCE_CONSTANTS'",
",",
"p2s_map",
"=",
"None",
")",
":",
"lines",
"=",
"get_FORCE_CONSTANTS_lines",
"(",
"force_constants",
",",
"p2s_map",
"=",
"p2s_map",
")",
"with",
"open",
"(",
... | Write force constants in text file format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
dtype=intc | [
"Write",
"force",
"constants",
"in",
"text",
"file",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L243-L264 | train | 222,425 |
atztogo/phonopy | phonopy/file_IO.py | write_force_constants_to_hdf5 | def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
try:
import h5py
except ImportError:
raise ModuleNotFoundError("You need to install python-h5py.")
with h5py.File(filename, 'w') as w:
w.create_dataset('force_constants', data=force_constants,
compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map)
if physical_unit is not None:
dset = w.create_dataset('physical_unit', (1,),
dtype='S%d' % len(physical_unit))
dset[0] = np.string_(physical_unit) | python | def write_force_constants_to_hdf5(force_constants,
filename='force_constants.hdf5',
p2s_map=None,
physical_unit=None,
compression=None):
"""Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
try:
import h5py
except ImportError:
raise ModuleNotFoundError("You need to install python-h5py.")
with h5py.File(filename, 'w') as w:
w.create_dataset('force_constants', data=force_constants,
compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map)
if physical_unit is not None:
dset = w.create_dataset('physical_unit', (1,),
dtype='S%d' % len(physical_unit))
dset[0] = np.string_(physical_unit) | [
"def",
"write_force_constants_to_hdf5",
"(",
"force_constants",
",",
"filename",
"=",
"'force_constants.hdf5'",
",",
"p2s_map",
"=",
"None",
",",
"physical_unit",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"try",
":",
"import",
"h5py",
"except",
"Im... | Write force constants in hdf5 format.
Parameters
----------
force_constants: ndarray
Force constants
shape=(n_satom,n_satom,3,3) or (n_patom,n_satom,3,3)
dtype=double
filename: str
Filename to be saved
p2s_map: ndarray
Primitive atom indices in supercell index system
shape=(n_patom,)
dtype=intc
physical_unit : str, optional
Physical unit used for force contants. Default is None.
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None. | [
"Write",
"force",
"constants",
"in",
"hdf5",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/file_IO.py#L285-L326 | train | 222,426 |
atztogo/phonopy | phonopy/phonon/band_structure.py | get_band_qpoints | def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
"""Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3)
"""
npts = _get_npts(band_paths, npoints, rec_lattice)
qpoints_of_paths = []
c = 0
for band_path in band_paths:
nd = len(band_path)
for i in range(nd - 1):
delta = np.subtract(band_path[i + 1], band_path[i]) / (npts[c] - 1)
qpoints = [delta * j for j in range(npts[c])]
qpoints_of_paths.append(np.array(qpoints) + band_path[i])
c += 1
return qpoints_of_paths | python | def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
"""Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3)
"""
npts = _get_npts(band_paths, npoints, rec_lattice)
qpoints_of_paths = []
c = 0
for band_path in band_paths:
nd = len(band_path)
for i in range(nd - 1):
delta = np.subtract(band_path[i + 1], band_path[i]) / (npts[c] - 1)
qpoints = [delta * j for j in range(npts[c])]
qpoints_of_paths.append(np.array(qpoints) + band_path[i])
c += 1
return qpoints_of_paths | [
"def",
"get_band_qpoints",
"(",
"band_paths",
",",
"npoints",
"=",
"51",
",",
"rec_lattice",
"=",
"None",
")",
":",
"npts",
"=",
"_get_npts",
"(",
"band_paths",
",",
"npoints",
",",
"rec_lattice",
")",
"qpoints_of_paths",
"=",
"[",
"]",
"c",
"=",
"0",
"f... | Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
[[0.5, 0.25, 0.75], [0, 0, 0]]]
npoints: int, optional
Number of q-points in each path including end points. Default is 51.
rec_lattice: array_like, optional
When given, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Reciprocal basis vectors given in column vectors.
dtype='double'
shape=(3, 3) | [
"Generate",
"qpoints",
"for",
"band",
"structure",
"path"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/band_structure.py#L70-L112 | train | 222,427 |
atztogo/phonopy | phonopy/phonon/band_structure.py | get_band_qpoints_by_seekpath | def get_band_qpoints_by_seekpath(primitive, npoints, is_const_interval=False):
"""q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths.
"""
try:
import seekpath
except ImportError:
raise ImportError("You need to install seekpath.")
band_path = seekpath.get_path(primitive.totuple())
point_coords = band_path['point_coords']
qpoints_of_paths = []
if is_const_interval:
reclat = np.linalg.inv(primitive.get_cell())
else:
reclat = None
band_paths = [[point_coords[path[0]], point_coords[path[1]]]
for path in band_path['path']]
npts = _get_npts(band_paths, npoints, reclat)
for c, path in enumerate(band_path['path']):
q_s = np.array(point_coords[path[0]])
q_e = np.array(point_coords[path[1]])
band = [q_s + (q_e - q_s) / (npts[c] - 1) * i for i in range(npts[c])]
qpoints_of_paths.append(band)
labels, path_connections = _get_labels(band_path['path'])
return qpoints_of_paths, labels, path_connections | python | def get_band_qpoints_by_seekpath(primitive, npoints, is_const_interval=False):
"""q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths.
"""
try:
import seekpath
except ImportError:
raise ImportError("You need to install seekpath.")
band_path = seekpath.get_path(primitive.totuple())
point_coords = band_path['point_coords']
qpoints_of_paths = []
if is_const_interval:
reclat = np.linalg.inv(primitive.get_cell())
else:
reclat = None
band_paths = [[point_coords[path[0]], point_coords[path[1]]]
for path in band_path['path']]
npts = _get_npts(band_paths, npoints, reclat)
for c, path in enumerate(band_path['path']):
q_s = np.array(point_coords[path[0]])
q_e = np.array(point_coords[path[1]])
band = [q_s + (q_e - q_s) / (npts[c] - 1) * i for i in range(npts[c])]
qpoints_of_paths.append(band)
labels, path_connections = _get_labels(band_path['path'])
return qpoints_of_paths, labels, path_connections | [
"def",
"get_band_qpoints_by_seekpath",
"(",
"primitive",
",",
"npoints",
",",
"is_const_interval",
"=",
"False",
")",
":",
"try",
":",
"import",
"seekpath",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"\"You need to install seekpath.\"",
")",
"band_path... | q-points along BZ high symmetry paths are generated using seekpath.
Parameters
----------
primitive : PhonopyAtoms
Primitive cell.
npoints : int
Number of q-points sampled along a path including end points.
is_const_interval : bool, optional
When True, q-points are sampled in a similar interval. The longest
path length divided by npoints including end points is used as the
reference interval. Default is False.
Returns
-------
bands : List of ndarray
Sets of qpoints that can be passed to phonopy.set_band_structure().
shape of each ndarray : (npoints, 3)
labels : List of pairs of str
Symbols of end points of paths.
connections : List of bool
This gives one path is connected to the next path, i.e., if False,
there is a jump of q-points. Number of elements is the same at
that of paths. | [
"q",
"-",
"points",
"along",
"BZ",
"high",
"symmetry",
"paths",
"are",
"generated",
"using",
"seekpath",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/phonon/band_structure.py#L115-L165 | train | 222,428 |
atztogo/phonopy | phonopy/harmonic/dynmat_to_fc.py | get_commensurate_points | def get_commensurate_points(supercell_matrix): # wrt primitive cell
"""Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
"""
smat = np.array(supercell_matrix, dtype=int)
rec_primitive = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]),
pbc=True)
rec_supercell = get_supercell(rec_primitive, smat.T)
q_pos = rec_supercell.get_scaled_positions()
return np.array(np.where(q_pos > 1 - 1e-15, q_pos - 1, q_pos),
dtype='double', order='C') | python | def get_commensurate_points(supercell_matrix): # wrt primitive cell
"""Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
"""
smat = np.array(supercell_matrix, dtype=int)
rec_primitive = PhonopyAtoms(numbers=[1],
scaled_positions=[[0, 0, 0]],
cell=np.diag([1, 1, 1]),
pbc=True)
rec_supercell = get_supercell(rec_primitive, smat.T)
q_pos = rec_supercell.get_scaled_positions()
return np.array(np.where(q_pos > 1 - 1e-15, q_pos - 1, q_pos),
dtype='double', order='C') | [
"def",
"get_commensurate_points",
"(",
"supercell_matrix",
")",
":",
"# wrt primitive cell",
"smat",
"=",
"np",
".",
"array",
"(",
"supercell_matrix",
",",
"dtype",
"=",
"int",
")",
"rec_primitive",
"=",
"PhonopyAtoms",
"(",
"numbers",
"=",
"[",
"1",
"]",
",",... | Commensurate q-points are returned.
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc | [
"Commensurate",
"q",
"-",
"points",
"are",
"returned",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/dynmat_to_fc.py#L42-L62 | train | 222,429 |
atztogo/phonopy | phonopy/harmonic/dynmat_to_fc.py | get_commensurate_points_in_integers | def get_commensurate_points_in_integers(supercell_matrix):
"""Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3)
"""
smat = np.array(supercell_matrix, dtype=int)
snf = SNF3x3(smat.T)
snf.run()
D = snf.A.diagonal()
b, c, a = np.meshgrid(range(D[1]), range(D[2]), range(D[0]))
lattice_points = np.dot(np.c_[a.ravel() * D[1] * D[2],
b.ravel() * D[0] * D[2],
c.ravel() * D[0] * D[1]], snf.Q.T)
lattice_points = np.array(lattice_points % np.prod(D),
dtype='intc', order='C')
return lattice_points | python | def get_commensurate_points_in_integers(supercell_matrix):
"""Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3)
"""
smat = np.array(supercell_matrix, dtype=int)
snf = SNF3x3(smat.T)
snf.run()
D = snf.A.diagonal()
b, c, a = np.meshgrid(range(D[1]), range(D[2]), range(D[0]))
lattice_points = np.dot(np.c_[a.ravel() * D[1] * D[2],
b.ravel() * D[0] * D[2],
c.ravel() * D[0] * D[1]], snf.Q.T)
lattice_points = np.array(lattice_points % np.prod(D),
dtype='intc', order='C')
return lattice_points | [
"def",
"get_commensurate_points_in_integers",
"(",
"supercell_matrix",
")",
":",
"smat",
"=",
"np",
".",
"array",
"(",
"supercell_matrix",
",",
"dtype",
"=",
"int",
")",
"snf",
"=",
"SNF3x3",
"(",
"smat",
".",
"T",
")",
"snf",
".",
"run",
"(",
")",
"D",
... | Commensurate q-points in integer representation are returned.
A set of integer representation of lattice points is transformed to
the equivalent set of lattice points in fractional coordinates with
respect to supercell basis vectors by
integer_lattice_points / det(supercell_matrix)
Parameters
----------
supercell_matrix : array_like
Supercell matrix with respect to primitive cell basis vectors.
shape=(3, 3)
dtype=intc
Returns
-------
lattice_points : ndarray
Integer representation of lattice points in supercell.
shape=(N, 3) | [
"Commensurate",
"q",
"-",
"points",
"in",
"integer",
"representation",
"are",
"returned",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/dynmat_to_fc.py#L65-L97 | train | 222,430 |
atztogo/phonopy | phonopy/interface/vasp.py | write_vasp | def write_vasp(filename, cell, direct=True):
"""Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True.
"""
lines = get_vasp_structure_lines(cell, direct=direct)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | python | def write_vasp(filename, cell, direct=True):
"""Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True.
"""
lines = get_vasp_structure_lines(cell, direct=direct)
with open(filename, 'w') as w:
w.write("\n".join(lines)) | [
"def",
"write_vasp",
"(",
"filename",
",",
"cell",
",",
"direct",
"=",
"True",
")",
":",
"lines",
"=",
"get_vasp_structure_lines",
"(",
"cell",
",",
"direct",
"=",
"direct",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
... | Write crystal structure to a VASP POSCAR style file.
Parameters
----------
filename : str
Filename.
cell : PhonopyAtoms
Crystal structure.
direct : bool, optional
In 'Direct' or not in VASP POSCAR format. Default is True. | [
"Write",
"crystal",
"structure",
"to",
"a",
"VASP",
"POSCAR",
"style",
"file",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/vasp.py#L249-L265 | train | 222,431 |
atztogo/phonopy | phonopy/interface/qe.py | PwscfIn._set_lattice | def _set_lattice(self):
"""Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag.
"""
unit = self._values[0]
if unit == 'alat':
if not self._tags['celldm(1)']:
print("celldm(1) has to be specified when using alat.")
sys.exit(1)
else:
factor = self._tags['celldm(1)'] # in Bohr
elif unit == 'angstrom':
factor = 1.0 / Bohr
else:
factor = 1.0
if len(self._values[1:]) < 9:
print("CELL_PARAMETERS is wrongly set.")
sys.exit(1)
lattice = np.reshape([float(x) for x in self._values[1:10]], (3, 3))
self._tags['cell_parameters'] = lattice * factor | python | def _set_lattice(self):
"""Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag.
"""
unit = self._values[0]
if unit == 'alat':
if not self._tags['celldm(1)']:
print("celldm(1) has to be specified when using alat.")
sys.exit(1)
else:
factor = self._tags['celldm(1)'] # in Bohr
elif unit == 'angstrom':
factor = 1.0 / Bohr
else:
factor = 1.0
if len(self._values[1:]) < 9:
print("CELL_PARAMETERS is wrongly set.")
sys.exit(1)
lattice = np.reshape([float(x) for x in self._values[1:10]], (3, 3))
self._tags['cell_parameters'] = lattice * factor | [
"def",
"_set_lattice",
"(",
"self",
")",
":",
"unit",
"=",
"self",
".",
"_values",
"[",
"0",
"]",
"if",
"unit",
"==",
"'alat'",
":",
"if",
"not",
"self",
".",
"_tags",
"[",
"'celldm(1)'",
"]",
":",
"print",
"(",
"\"celldm(1) has to be specified when using ... | Calculate and set lattice parameters.
Invoked by CELL_PARAMETERS tag. | [
"Calculate",
"and",
"set",
"lattice",
"parameters",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L278-L302 | train | 222,432 |
atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R.run | def run(self, cell, is_full_fc=False, parse_fc=True):
"""Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born.
"""
with open(self._filename) as f:
fc_dct = self._parse_q2r(f)
self.dimension = fc_dct['dimension']
self.epsilon = fc_dct['dielectric']
self.borns = fc_dct['born']
if parse_fc:
(self.fc,
self.primitive,
self.supercell) = self._arrange_supercell_fc(
cell, fc_dct['fc'], is_full_fc=is_full_fc) | python | def run(self, cell, is_full_fc=False, parse_fc=True):
"""Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born.
"""
with open(self._filename) as f:
fc_dct = self._parse_q2r(f)
self.dimension = fc_dct['dimension']
self.epsilon = fc_dct['dielectric']
self.borns = fc_dct['born']
if parse_fc:
(self.fc,
self.primitive,
self.supercell) = self._arrange_supercell_fc(
cell, fc_dct['fc'], is_full_fc=is_full_fc) | [
"def",
"run",
"(",
"self",
",",
"cell",
",",
"is_full_fc",
"=",
"False",
",",
"parse_fc",
"=",
"True",
")",
":",
"with",
"open",
"(",
"self",
".",
"_filename",
")",
"as",
"f",
":",
"fc_dct",
"=",
"self",
".",
"_parse_q2r",
"(",
"f",
")",
"self",
... | Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is not usable in phonopy.
Arguments
---------
cell : PhonopyAtoms
Primitive cell used for QE/PH calculation.
is_full_fc : Bool, optional, default=False
Whether to create full or compact force constants.
parse_fc : Bool, optional, default=True
Force constants file of QE is not parsed when this is False.
False may be used when expected to parse only epsilon and born. | [
"Make",
"supercell",
"force",
"constants",
"readable",
"for",
"phonopy"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L416-L447 | train | 222,433 |
atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R._parse_q2r | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html
"""
natom, dim, epsilon, borns = self._parse_parameters(f)
fc_dct = {'fc': self._parse_fc(f, natom, dim),
'dimension': dim,
'dielectric': epsilon,
'born': borns}
return fc_dct | python | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html
"""
natom, dim, epsilon, borns = self._parse_parameters(f)
fc_dct = {'fc': self._parse_fc(f, natom, dim),
'dimension': dim,
'dielectric': epsilon,
'born': borns}
return fc_dct | [
"def",
"_parse_q2r",
"(",
"self",
",",
"f",
")",
":",
"natom",
",",
"dim",
",",
"epsilon",
",",
"borns",
"=",
"self",
".",
"_parse_parameters",
"(",
"f",
")",
"fc_dct",
"=",
"{",
"'fc'",
":",
"self",
".",
"_parse_fc",
"(",
"f",
",",
"natom",
",",
... | Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613.html
https://www.mail-archive.com/pw_forum@pwscf.org/msg24388.html | [
"Parse",
"q2r",
"output",
"file"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L457-L473 | train | 222,434 |
atztogo/phonopy | phonopy/interface/qe.py | PH_Q2R._parse_fc | def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
line = f.readline()
for i_dim in range(ndim):
line = f.readline()
# fc[i, j * ndim + i_dim, k, l] = float(line.split()[3])
fc[j, i * ndim + i_dim, l, k] = float(line.split()[3])
return fc | python | def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
line = f.readline()
for i_dim in range(ndim):
line = f.readline()
# fc[i, j * ndim + i_dim, k, l] = float(line.split()[3])
fc[j, i * ndim + i_dim, l, k] = float(line.split()[3])
return fc | [
"def",
"_parse_fc",
"(",
"self",
",",
"f",
",",
"natom",
",",
"dim",
")",
":",
"ndim",
"=",
"np",
".",
"prod",
"(",
"dim",
")",
"fc",
"=",
"np",
".",
"zeros",
"(",
"(",
"natom",
",",
"natom",
"*",
"ndim",
",",
"3",
",",
"3",
")",
",",
"dtyp... | Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2. | [
"Parse",
"force",
"constants",
"part"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L507-L522 | train | 222,435 |
atztogo/phonopy | phonopy/interface/cp2k.py | get_cp2k_structure | def get_cp2k_structure(atoms):
"""Convert the atoms structure to a CP2K input file skeleton string"""
from cp2k_tools.generator import dict2cp2k
# CP2K's default unit is angstrom, convert it, but still declare it explictly:
cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)}
cp2k_cell['periodic'] = 'XYZ' # anything else does not make much sense
cp2k_coord = {
'scaled': True,
'*': [[sym] + list(coord) for sym, coord in zip(atoms.get_chemical_symbols(), atoms.get_scaled_positions())],
}
return dict2cp2k(
{
'global': {
'run_type': 'ENERGY_FORCE',
},
'force_eval': {
'subsys': {
'cell': cp2k_cell,
'coord': cp2k_coord,
},
'print': {
'forces': {
'filename': 'forces',
},
},
},
}
) | python | def get_cp2k_structure(atoms):
"""Convert the atoms structure to a CP2K input file skeleton string"""
from cp2k_tools.generator import dict2cp2k
# CP2K's default unit is angstrom, convert it, but still declare it explictly:
cp2k_cell = {sym: ('[angstrom]',) + tuple(coords) for sym, coords in zip(('a', 'b', 'c'), atoms.get_cell()*Bohr)}
cp2k_cell['periodic'] = 'XYZ' # anything else does not make much sense
cp2k_coord = {
'scaled': True,
'*': [[sym] + list(coord) for sym, coord in zip(atoms.get_chemical_symbols(), atoms.get_scaled_positions())],
}
return dict2cp2k(
{
'global': {
'run_type': 'ENERGY_FORCE',
},
'force_eval': {
'subsys': {
'cell': cp2k_cell,
'coord': cp2k_coord,
},
'print': {
'forces': {
'filename': 'forces',
},
},
},
}
) | [
"def",
"get_cp2k_structure",
"(",
"atoms",
")",
":",
"from",
"cp2k_tools",
".",
"generator",
"import",
"dict2cp2k",
"# CP2K's default unit is angstrom, convert it, but still declare it explictly:",
"cp2k_cell",
"=",
"{",
"sym",
":",
"(",
"'[angstrom]'",
",",
")",
"+",
"... | Convert the atoms structure to a CP2K input file skeleton string | [
"Convert",
"the",
"atoms",
"structure",
"to",
"a",
"CP2K",
"input",
"file",
"skeleton",
"string"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/cp2k.py#L126-L156 | train | 222,436 |
atztogo/phonopy | phonopy/api_qha.py | PhonopyQHA.plot_qha | def plot_qha(self, thin_number=10, volume_temp_exp=None):
"""Returns matplotlib.pyplot of QHA fitting curves at temperatures"""
return self._qha.plot(thin_number=thin_number,
volume_temp_exp=volume_temp_exp) | python | def plot_qha(self, thin_number=10, volume_temp_exp=None):
"""Returns matplotlib.pyplot of QHA fitting curves at temperatures"""
return self._qha.plot(thin_number=thin_number,
volume_temp_exp=volume_temp_exp) | [
"def",
"plot_qha",
"(",
"self",
",",
"thin_number",
"=",
"10",
",",
"volume_temp_exp",
"=",
"None",
")",
":",
"return",
"self",
".",
"_qha",
".",
"plot",
"(",
"thin_number",
"=",
"thin_number",
",",
"volume_temp_exp",
"=",
"volume_temp_exp",
")"
] | Returns matplotlib.pyplot of QHA fitting curves at temperatures | [
"Returns",
"matplotlib",
".",
"pyplot",
"of",
"QHA",
"fitting",
"curves",
"at",
"temperatures"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_qha.py#L137-L140 | train | 222,437 |
atztogo/phonopy | phonopy/harmonic/force_constants.py | get_fc2 | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
"""Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3),
"""
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | python | def get_fc2(supercell,
symmetry,
dataset,
atom_list=None,
decimals=None):
"""Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3),
"""
if atom_list is None:
fc_dim0 = supercell.get_number_of_atoms()
else:
fc_dim0 = len(atom_list)
force_constants = np.zeros((fc_dim0,
supercell.get_number_of_atoms(),
3, 3), dtype='double', order='C')
# Fill force_constants[ displaced_atoms, all_atoms_in_supercell ]
atom_list_done = _get_force_constants_disps(
force_constants,
supercell,
dataset,
symmetry,
atom_list=atom_list)
rotations = symmetry.get_symmetry_operations()['rotations']
lattice = np.array(supercell.get_cell().T, dtype='double', order='C')
permutations = symmetry.get_atomic_permutations()
distribute_force_constants(force_constants,
atom_list_done,
lattice,
rotations,
permutations,
atom_list=atom_list)
if decimals:
force_constants = force_constants.round(decimals=decimals)
return force_constants | [
"def",
"get_fc2",
"(",
"supercell",
",",
"symmetry",
",",
"dataset",
",",
"atom_list",
"=",
"None",
",",
"decimals",
"=",
"None",
")",
":",
"if",
"atom_list",
"is",
"None",
":",
"fc_dim0",
"=",
"supercell",
".",
"get_number_of_atoms",
"(",
")",
"else",
"... | Force constants are computed.
Force constants, Phi, are calculated from sets for forces, F, and
atomic displacement, d:
Phi = -F / d
This is solved by matrix pseudo-inversion.
Crystal symmetry is included when creating F and d matrices.
Returns
-------
ndarray
Force constants[ i, j, a, b ]
i: Atom index of finitely displaced atom.
j: Atom index at which force on the atom is measured.
a, b: Cartesian direction indices = (0, 1, 2) for i and j, respectively
dtype=double
shape=(len(atom_list),n_satom,3,3), | [
"Force",
"constants",
"are",
"computed",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L58-L113 | train | 222,438 |
atztogo/phonopy | phonopy/harmonic/force_constants.py | set_permutation_symmetry | def set_permutation_symmetry(force_constants):
"""Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py.
"""
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | python | def set_permutation_symmetry(force_constants):
"""Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py.
"""
fc_copy = force_constants.copy()
for i in range(force_constants.shape[0]):
for j in range(force_constants.shape[1]):
force_constants[i, j] = (force_constants[i, j] +
fc_copy[j, i].T) / 2 | [
"def",
"set_permutation_symmetry",
"(",
"force_constants",
")",
":",
"fc_copy",
"=",
"force_constants",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"force_constants",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"j",
"in",
"range",
"(",
"forc... | Enforce permutation symmetry to force cosntants by
Phi_ij_ab = Phi_ji_ba
i, j: atom index
a, b: Cartesian axis index
This is not necessary for harmonic phonon calculation because this
condition is imposed when making dynamical matrix Hermite in
dynamical_matrix.py. | [
"Enforce",
"permutation",
"symmetry",
"to",
"force",
"cosntants",
"by"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L462-L480 | train | 222,439 |
atztogo/phonopy | phonopy/harmonic/force_constants.py | similarity_transformation | def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | python | def similarity_transformation(rot, mat):
""" R x M x R^-1 """
return np.dot(rot, np.dot(mat, np.linalg.inv(rot))) | [
"def",
"similarity_transformation",
"(",
"rot",
",",
"mat",
")",
":",
"return",
"np",
".",
"dot",
"(",
"rot",
",",
"np",
".",
"dot",
"(",
"mat",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"rot",
")",
")",
")"
] | R x M x R^-1 | [
"R",
"x",
"M",
"x",
"R^",
"-",
"1"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L529-L531 | train | 222,440 |
atztogo/phonopy | phonopy/harmonic/force_constants.py | _get_sym_mappings_from_permutations | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
"""This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot)
"""
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | python | def _get_sym_mappings_from_permutations(permutations, atom_list_done):
"""This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot)
"""
assert permutations.ndim == 2
num_pos = permutations.shape[1]
# filled with -1
map_atoms = np.zeros((num_pos,), dtype='intc') - 1
map_syms = np.zeros((num_pos,), dtype='intc') - 1
atom_list_done = set(atom_list_done)
for atom_todo in range(num_pos):
for (sym_index, permutation) in enumerate(permutations):
if permutation[atom_todo] in atom_list_done:
map_atoms[atom_todo] = permutation[atom_todo]
map_syms[atom_todo] = sym_index
break
else:
text = ("Input forces are not enough to calculate force constants,"
"or something wrong (e.g. crystal structure does not "
"match).")
print(textwrap.fill(text))
raise ValueError
assert set(map_atoms) & set(atom_list_done) == set(map_atoms)
assert -1 not in map_atoms
assert -1 not in map_syms
return map_atoms, map_syms | [
"def",
"_get_sym_mappings_from_permutations",
"(",
"permutations",
",",
"atom_list_done",
")",
":",
"assert",
"permutations",
".",
"ndim",
"==",
"2",
"num_pos",
"=",
"permutations",
".",
"shape",
"[",
"1",
"]",
"# filled with -1",
"map_atoms",
"=",
"np",
".",
"z... | This can be thought of as computing 'map_atom_disp' and 'map_sym'
for all atoms, except done using permutations instead of by
computing overlaps.
Input:
* permutations, shape [num_rot][num_pos]
* atom_list_done
Output:
* map_atoms, shape [num_pos].
Maps each atom in the full structure to its equivalent atom in
atom_list_done. (each entry will be an integer found in
atom_list_done)
* map_syms, shape [num_pos].
For each atom, provides the index of a rotation that maps it
into atom_list_done. (there might be more than one such
rotation, but only one will be returned) (each entry will be
an integer 0 <= i < num_rot) | [
"This",
"can",
"be",
"thought",
"of",
"as",
"computing",
"map_atom_disp",
"and",
"map_sym",
"for",
"all",
"atoms",
"except",
"done",
"using",
"permutations",
"instead",
"of",
"by",
"computing",
"overlaps",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/force_constants.py#L778-L826 | train | 222,441 |
atztogo/phonopy | phonopy/harmonic/displacement.py | get_least_displacements | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
"""Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes.
"""
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | python | def get_least_displacements(symmetry,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False,
log_level=0):
"""Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes.
"""
displacements = []
if is_diagonal:
directions = directions_diag
else:
directions = directions_axis
if log_level > 2:
print("Site point symmetry:")
for atom_num in symmetry.get_independent_atoms():
site_symmetry = symmetry.get_site_symmetry(atom_num)
if log_level > 2:
print("Atom %d" % (atom_num + 1))
for i, rot in enumerate(site_symmetry):
print("----%d----" % (i + 1))
for v in rot:
print("%2d %2d %2d" % tuple(v))
for disp in get_displacement(site_symmetry,
directions,
is_trigonal,
log_level):
displacements.append([atom_num,
disp[0], disp[1], disp[2]])
if is_plusminus == 'auto':
if is_minus_displacement(disp, site_symmetry):
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
elif is_plusminus is True:
displacements.append([atom_num,
-disp[0], -disp[1], -disp[2]])
return displacements | [
"def",
"get_least_displacements",
"(",
"symmetry",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"True",
",",
"is_trigonal",
"=",
"False",
",",
"log_level",
"=",
"0",
")",
":",
"displacements",
"=",
"[",
"]",
"if",
"is_diagonal",
":",
"directi... | Return a set of displacements
Returns
-------
array_like
List of directions with respect to axes. This gives only the
symmetrically non equivalent directions. The format is like:
[[0, 1, 0, 0],
[7, 1, 0, 1], ...]
where each list is defined by:
First value: Atom index in supercell starting with 0
Second to fourth: If the direction is displaced or not (1, 0, or -1)
with respect to the axes. | [
"Return",
"a",
"set",
"of",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/displacement.py#L74-L127 | train | 222,442 |
atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims | def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | python | def read_aims(filename):
"""Method to read FHI-aims geometry files in phonopy context."""
lines = open(filename, 'r').readlines()
cell = []
is_frac = []
positions = []
symbols = []
magmoms = []
for line in lines:
fields = line.split()
if not len(fields):
continue
if fields[0] == "lattice_vector":
vec = lmap(float, fields[1:4])
cell.append(vec)
elif fields[0][0:4] == "atom":
if fields[0] == "atom":
frac = False
elif fields[0] == "atom_frac":
frac = True
pos = lmap(float, fields[1:4])
sym = fields[4]
is_frac.append(frac)
positions.append(pos)
symbols.append(sym)
magmoms.append(None)
# implicitly assuming that initial_moments line adhere to FHI-aims geometry.in specification,
# i.e. two subsequent initial_moments lines do not occur
# if they do, the value specified in the last line is taken here - without any warning
elif fields[0] == "initial_moment":
magmoms[-1] = float(fields[1])
for (n,frac) in enumerate(is_frac):
if frac:
pos = [ sum( [ positions[n][l] * cell[l][i] for l in range(3) ] ) for i in range(3) ]
positions[n] = pos
if None in magmoms:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
else:
atoms = Atoms(cell=cell, symbols=symbols, positions=positions, magmoms=magmoms)
return atoms | [
"def",
"read_aims",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"cell",
"=",
"[",
"]",
"is_frac",
"=",
"[",
"]",
"positions",
"=",
"[",
"]",
"symbols",
"=",
"[",
"]",
"magmoms",
"... | Method to read FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"read",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L49-L92 | train | 222,443 |
atztogo/phonopy | phonopy/interface/FHIaims.py | write_aims | def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | python | def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_cell():
lines += lattice_vector_line % tuple(vec)
N = atoms.get_number_of_atoms()
atom_line = "atom " + "%16.16f "*3 + "%s \n"
positions = atoms.get_positions()
symbols = atoms.get_chemical_symbols()
initial_moment_line = "initial_moment %16.6f\n"
magmoms = atoms.get_magnetic_moments()
for n in range(N):
lines += atom_line % (tuple(positions[n]) + (symbols[n],))
if magmoms is not None:
lines += initial_moment_line % magmoms[n]
with open(filename, 'w') as f:
f.write(lines) | [
"def",
"write_aims",
"(",
"filename",
",",
"atoms",
")",
":",
"lines",
"=",
"\"\"",
"lines",
"+=",
"\"# geometry.in for FHI-aims \\n\"",
"lines",
"+=",
"\"# | generated by phonopy.FHIaims.write_aims() \\n\"",
"lattice_vector_line",
"=",
"\"lattice_vector \"",
"+",
"\"%16.16... | Method to write FHI-aims geometry files in phonopy context. | [
"Method",
"to",
"write",
"FHI",
"-",
"aims",
"geometry",
"files",
"in",
"phonopy",
"context",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L95-L121 | train | 222,444 |
atztogo/phonopy | phonopy/interface/FHIaims.py | read_aims_output | def read_aims_output(filename):
""" Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration"""
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | python | def read_aims_output(filename):
""" Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration"""
lines = open(filename, 'r').readlines()
l = 0
N = 0
while l < len(lines):
line = lines[l]
if "| Number of atoms" in line:
N = int(line.split()[5])
elif "| Unit cell:" in line:
cell = []
for i in range(3):
l += 1
vec = lmap(float, lines[l].split()[1:4])
cell.append(vec)
elif ("Atomic structure:" in line) or ("Updated atomic structure:" in line):
if "Atomic structure:" in line:
i_sym = 3
i_pos_min = 4 ; i_pos_max = 7
elif "Updated atomic structure:" in line:
i_sym = 4
i_pos_min = 1 ; i_pos_max = 4
l += 1
symbols = []
positions = []
for n in range(N):
l += 1
fields = lines[l].split()
sym = fields[i_sym]
pos = lmap(float, fields[i_pos_min:i_pos_max])
symbols.append(sym)
positions.append(pos)
elif "Total atomic forces" in line:
forces = []
for i in range(N):
l += 1
force = lmap(float, lines[l].split()[-3:])
forces.append(force)
l += 1
atoms = Atoms_with_forces(cell=cell, symbols=symbols, positions=positions)
atoms.forces = forces
return atoms | [
"def",
"read_aims_output",
"(",
"filename",
")",
":",
"lines",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
".",
"readlines",
"(",
")",
"l",
"=",
"0",
"N",
"=",
"0",
"while",
"l",
"<",
"len",
"(",
"lines",
")",
":",
"line",
"=",
"lines",
"[",
... | Read FHI-aims output and
return geometry, energy and forces from last self-consistency iteration | [
"Read",
"FHI",
"-",
"aims",
"output",
"and",
"return",
"geometry",
"energy",
"and",
"forces",
"from",
"last",
"self",
"-",
"consistency",
"iteration"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/FHIaims.py#L132-L178 | train | 222,445 |
atztogo/phonopy | phonopy/structure/symmetry.py | find_primitive | def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | python | def find_primitive(cell, symprec=1e-5):
"""
A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned.
"""
lattice, positions, numbers = spg.find_primitive(cell.totuple(), symprec)
if lattice is None:
return None
else:
return Atoms(numbers=numbers,
scaled_positions=positions,
cell=lattice,
pbc=True) | [
"def",
"find_primitive",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
")",
":",
"lattice",
",",
"positions",
",",
"numbers",
"=",
"spg",
".",
"find_primitive",
"(",
"cell",
".",
"totuple",
"(",
")",
",",
"symprec",
")",
"if",
"lattice",
"is",
"None",
":",... | A primitive cell is searched in the input cell. When a primitive
cell is found, an object of Atoms class of the primitive cell is
returned. When not, None is returned. | [
"A",
"primitive",
"cell",
"is",
"searched",
"in",
"the",
"input",
"cell",
".",
"When",
"a",
"primitive",
"cell",
"is",
"found",
"an",
"object",
"of",
"Atoms",
"class",
"of",
"the",
"primitive",
"cell",
"is",
"returned",
".",
"When",
"not",
"None",
"is",
... | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L300-L313 | train | 222,446 |
atztogo/phonopy | phonopy/structure/symmetry.py | elaborate_borns_and_epsilon | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
"""Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges
"""
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | python | def elaborate_borns_and_epsilon(ucell,
borns,
epsilon,
primitive_matrix=None,
supercell_matrix=None,
is_symmetry=True,
symmetrize_tensors=False,
symprec=1e-5):
"""Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges
"""
assert len(borns) == ucell.get_number_of_atoms(), \
"num_atom %d != len(borns) %d" % (ucell.get_number_of_atoms(),
len(borns))
if symmetrize_tensors:
borns_, epsilon_ = symmetrize_borns_and_epsilon(
borns,
epsilon,
ucell,
symprec=symprec,
is_symmetry=is_symmetry)
else:
borns_ = borns
epsilon_ = epsilon
indeps_in_supercell, indeps_in_unitcell = _extract_independent_atoms(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
is_symmetry=is_symmetry,
symprec=symprec)
return borns_[indeps_in_unitcell].copy(), epsilon_, indeps_in_supercell | [
"def",
"elaborate_borns_and_epsilon",
"(",
"ucell",
",",
"borns",
",",
"epsilon",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"is_symmetry",
"=",
"True",
",",
"symmetrize_tensors",
"=",
"False",
",",
"symprec",
"=",
"1e-5",
... | Symmetrize Born effective charges and dielectric constants and
extract Born effective charges of symmetrically independent atoms
for primitive cell.
Args:
ucell (Atoms): Unit cell structure
borns (np.array): Born effective charges of ucell
epsilon (np.array): Dielectric constant tensor
Returns:
(np.array) Born effective charges of symmetrically independent atoms
in primitive cell
(np.array) Dielectric constant
(np.array) Atomic index mapping table from supercell to primitive cell
of independent atoms
Raises:
AssertionError: Inconsistency of number of atoms or Born effective
charges.
Warning:
Broken symmetry of Born effective charges | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"constants",
"and",
"extract",
"Born",
"effective",
"charges",
"of",
"symmetrically",
"independent",
"atoms",
"for",
"primitive",
"cell",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L343-L399 | train | 222,447 |
atztogo/phonopy | phonopy/structure/symmetry.py | symmetrize_borns_and_epsilon | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
"""Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True.
"""
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | python | def symmetrize_borns_and_epsilon(borns,
epsilon,
ucell,
primitive_matrix=None,
supercell_matrix=None,
symprec=1e-5,
is_symmetry=True):
"""Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True.
"""
lattice = ucell.get_cell()
positions = ucell.get_scaled_positions()
u_sym = Symmetry(ucell, is_symmetry=is_symmetry, symprec=symprec)
rotations = u_sym.get_symmetry_operations()['rotations']
translations = u_sym.get_symmetry_operations()['translations']
ptg_ops = u_sym.get_pointgroup_operations()
epsilon_ = _symmetrize_2nd_rank_tensor(epsilon, ptg_ops, lattice)
for i, Z in enumerate(borns):
site_sym = u_sym.get_site_symmetry(i)
Z = _symmetrize_2nd_rank_tensor(Z, site_sym, lattice)
borns_ = np.zeros_like(borns)
for i in range(len(borns)):
count = 0
for r, t in zip(rotations, translations):
count += 1
diff = np.dot(positions, r.T) + t - positions[i]
diff -= np.rint(diff)
dist = np.sqrt(np.sum(np.dot(diff, lattice) ** 2, axis=1))
j = np.nonzero(dist < symprec)[0][0]
r_cart = similarity_transformation(lattice.T, r)
borns_[i] += similarity_transformation(r_cart, borns[j])
borns_[i] /= count
sum_born = borns_.sum(axis=0) / len(borns_)
borns_ -= sum_born
if (abs(borns - borns_) > 0.1).any():
lines = ["Born effective charge symmetry is largely broken. "
"Largest different among elements: "
"%s" % np.amax(abs(borns - borns_))]
import warnings
warnings.warn("\n".join(lines))
if primitive_matrix is None:
return borns_, epsilon_
else:
scell, pcell = _get_supercell_and_primitive(
ucell,
primitive_matrix=primitive_matrix,
supercell_matrix=supercell_matrix,
symprec=symprec)
idx = [scell.u2u_map[i] for i in scell.s2u_map[pcell.p2s_map]]
return borns_[idx], epsilon_ | [
"def",
"symmetrize_borns_and_epsilon",
"(",
"borns",
",",
"epsilon",
",",
"ucell",
",",
"primitive_matrix",
"=",
"None",
",",
"supercell_matrix",
"=",
"None",
",",
"symprec",
"=",
"1e-5",
",",
"is_symmetry",
"=",
"True",
")",
":",
"lattice",
"=",
"ucell",
".... | Symmetrize Born effective charges and dielectric tensor
Parameters
----------
borns: array_like
Born effective charges.
shape=(unitcell_atoms, 3, 3)
dtype='double'
epsilon: array_like
Dielectric constant
shape=(3, 3)
dtype='double'
ucell: PhonopyAtoms
Unit cell
primitive_matrix: array_like, optional
Primitive matrix. This is used to select Born effective charges in
primitive cell. If None (default), Born effective charges in unit cell
are returned.
shape=(3, 3)
dtype='double'
supercell_matrix: array_like, optional
Supercell matrix. This is used to select Born effective charges in
**primitive cell**. Supercell matrix is needed because primitive
cell is created first creating supercell from unit cell, then
the primitive cell is created from the supercell. If None (defautl),
1x1x1 supercell is created.
shape=(3, 3)
dtype='int'
symprec: float, optional
Symmetry tolerance. Default is 1e-5
is_symmetry: bool, optinal
By setting False, symmetrization can be switched off. Default is True. | [
"Symmetrize",
"Born",
"effective",
"charges",
"and",
"dielectric",
"tensor"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/symmetry.py#L402-L488 | train | 222,448 |
atztogo/phonopy | phonopy/interface/dftbp.py | read_dftbp | def read_dftbp(filename):
""" Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename
"""
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | python | def read_dftbp(filename):
""" Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename
"""
infile = open(filename, 'r')
lines = infile.readlines()
# remove any comments
for ss in lines:
if ss.strip().startswith('#'):
lines.remove(ss)
natoms = int(lines[0].split()[0])
symbols = lines[1].split()
if (lines[0].split()[1].lower() == 'f'):
is_scaled = True
scale_pos = 1
scale_latvecs = dftbpToBohr
else:
is_scaled = False
scale_pos = dftbpToBohr
scale_latvecs = dftbpToBohr
# assign positions and expanded symbols
positions = []
expaned_symbols = []
for ii in range(2, natoms+2):
lsplit = lines[ii].split()
expaned_symbols.append(symbols[int(lsplit[1]) - 1])
positions.append([float(ss)*scale_pos for ss in lsplit[2:5]])
# origin is ignored, may be used in future
origin = [float(ss) for ss in lines[natoms+2].split()]
# assign coords of unitcell
cell = []
for ii in range(natoms+3, natoms+6):
lsplit = lines[ii].split()
cell.append([float(ss)*scale_latvecs for ss in lsplit[:3]])
cell = np.array(cell)
if is_scaled:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
scaled_positions=positions)
else:
atoms = Atoms(symbols=expaned_symbols,
cell=cell,
positions=positions)
return atoms | [
"def",
"read_dftbp",
"(",
"filename",
")",
":",
"infile",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"infile",
".",
"readlines",
"(",
")",
"# remove any comments",
"for",
"ss",
"in",
"lines",
":",
"if",
"ss",
".",
"strip",
"(",
")",
... | Reads DFTB+ structure files in gen format.
Args:
filename: name of the gen-file to be read
Returns:
atoms: an object of the phonopy.Atoms class, representing the structure
found in filename | [
"Reads",
"DFTB",
"+",
"structure",
"files",
"in",
"gen",
"format",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L72-L135 | train | 222,449 |
atztogo/phonopy | phonopy/interface/dftbp.py | get_reduced_symbols | def get_reduced_symbols(symbols):
"""Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once
"""
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | python | def get_reduced_symbols(symbols):
"""Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once
"""
reduced_symbols = []
for ss in symbols:
if not (ss in reduced_symbols):
reduced_symbols.append(ss)
return reduced_symbols | [
"def",
"get_reduced_symbols",
"(",
"symbols",
")",
":",
"reduced_symbols",
"=",
"[",
"]",
"for",
"ss",
"in",
"symbols",
":",
"if",
"not",
"(",
"ss",
"in",
"reduced_symbols",
")",
":",
"reduced_symbols",
".",
"append",
"(",
"ss",
")",
"return",
"reduced_sym... | Reduces expanded list of symbols.
Args:
symbols: list containing any chemical symbols as often as
the atom appears in the structure
Returns:
reduced_symbols: any symbols appears only once | [
"Reduces",
"expanded",
"list",
"of",
"symbols",
"."
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L140-L157 | train | 222,450 |
atztogo/phonopy | phonopy/interface/dftbp.py | write_dftbp | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | python | def write_dftbp(filename, atoms):
"""Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure
"""
scale_pos = dftbpToBohr
lines = ""
# 1. line, use absolute positions
natoms = atoms.get_number_of_atoms()
lines += str(natoms)
lines += ' S \n'
# 2. line
expaned_symbols = atoms.get_chemical_symbols()
symbols = get_reduced_symbols(expaned_symbols)
lines += ' '.join(symbols) + '\n'
atom_numbers = []
for ss in expaned_symbols:
atom_numbers.append(symbols.index(ss) + 1)
positions = atoms.get_positions()/scale_pos
for ii in range(natoms):
pos = positions[ii]
pos_str = "{:3d} {:3d} {:20.15f} {:20.15f} {:20.15f}\n".format(
ii + 1, atom_numbers[ii], pos[0], pos[1], pos[2])
lines += pos_str
# origin arbitrary
lines +='0.0 0.0 0.0\n'
cell = atoms.get_cell()/scale_pos
for ii in range(3):
cell_str = "{:20.15f} {:20.15f} {:20.15f}\n".format(
cell[ii][0], cell[ii][1], cell[ii][2])
lines += cell_str
outfile = open(filename, 'w')
outfile.write(lines) | [
"def",
"write_dftbp",
"(",
"filename",
",",
"atoms",
")",
":",
"scale_pos",
"=",
"dftbpToBohr",
"lines",
"=",
"\"\"",
"# 1. line, use absolute positions",
"natoms",
"=",
"atoms",
".",
"get_number_of_atoms",
"(",
")",
"lines",
"+=",
"str",
"(",
"natoms",
")",
"... | Writes DFTB+ readable, gen-formatted structure files
Args:
filename: name of the gen-file to be written
atoms: object containing information about structure | [
"Writes",
"DFTB",
"+",
"readable",
"gen",
"-",
"formatted",
"structure",
"files"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L159-L203 | train | 222,451 |
atztogo/phonopy | phonopy/interface/dftbp.py | write_supercells_with_displacements | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
"""Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename
"""
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | python | def write_supercells_with_displacements(supercell, cells_with_disps, filename="geo.gen"):
"""Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename
"""
# original cell
write_dftbp(filename + "S", supercell)
# displaced cells
for ii in range(len(cells_with_disps)):
write_dftbp(filename + "S-{:03d}".format(ii+1), cells_with_disps[ii]) | [
"def",
"write_supercells_with_displacements",
"(",
"supercell",
",",
"cells_with_disps",
",",
"filename",
"=",
"\"geo.gen\"",
")",
":",
"# original cell",
"write_dftbp",
"(",
"filename",
"+",
"\"S\"",
",",
"supercell",
")",
"# displaced cells",
"for",
"ii",
"in",
"r... | Writes perfect supercell and supercells with displacements
Args:
supercell: perfect supercell
cells_with_disps: supercells with displaced atoms
filename: root-filename | [
"Writes",
"perfect",
"supercell",
"and",
"supercells",
"with",
"displacements"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/dftbp.py#L205-L219 | train | 222,452 |
atztogo/phonopy | phonopy/interface/__init__.py | get_interface_mode | def get_interface_mode(args):
"""Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}.
"""
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | python | def get_interface_mode(args):
"""Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}.
"""
calculator_list = ['wien2k', 'abinit', 'qe', 'elk', 'siesta', 'cp2k',
'crystal', 'vasp', 'dftbp', 'turbomole']
for calculator in calculator_list:
mode = "%s_mode" % calculator
if mode in args and args.__dict__[mode]:
return calculator
return None | [
"def",
"get_interface_mode",
"(",
"args",
")",
":",
"calculator_list",
"=",
"[",
"'wien2k'",
",",
"'abinit'",
",",
"'qe'",
",",
"'elk'",
",",
"'siesta'",
",",
"'cp2k'",
",",
"'crystal'",
",",
"'vasp'",
",",
"'dftbp'",
",",
"'turbomole'",
"]",
"for",
"calcu... | Return calculator name
The calculator name is obtained from command option arguments where
argparse is used. The argument attribute name has to be
"{calculator}_mode". Then this method returns {calculator}. | [
"Return",
"calculator",
"name"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L40-L55 | train | 222,453 |
atztogo/phonopy | phonopy/interface/__init__.py | get_default_physical_units | def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au
"""
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | python | def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au
"""
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | [
"def",
"get_default_physical_units",
"(",
"interface_mode",
"=",
"None",
")",
":",
"from",
"phonopy",
".",
"units",
"import",
"(",
"Wien2kToTHz",
",",
"AbinitToTHz",
",",
"PwscfToTHz",
",",
"ElkToTHz",
",",
"SiestaToTHz",
",",
"VaspToTHz",
",",
"CP2KToTHz",
",",... | Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au | [
"Return",
"physical",
"units",
"used",
"for",
"calculators"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L231-L318 | train | 222,454 |
atztogo/phonopy | phonopy/structure/tetrahedron_method.py | get_tetrahedra_integration_weight | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative.
"""
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | python | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative.
"""
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | [
"def",
"get_tetrahedra_integration_weight",
"(",
"omegas",
",",
"tetrahedra_omegas",
",",
"function",
"=",
"'I'",
")",
":",
"if",
"isinstance",
"(",
"omegas",
",",
"float",
")",
":",
"return",
"phonoc",
".",
"tetrahedra_integration_weight",
"(",
"omegas",
",",
"... | Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative. | [
"Returns",
"integration",
"weights"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L95-L125 | train | 222,455 |
atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_1 | def _g_1(self):
"""omega1 < omega < omega2"""
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_1(self):
"""omega1 < omega < omega2"""
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_1",
"(",
"self",
")",
":",
"# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"0",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"0",
")",
"/",
"(",
"self",
".",
"_... | omega1 < omega < omega2 | [
"omega1",
"<",
"omega",
"<",
"omega2"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L438-L442 | train | 222,456 |
atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_3 | def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_3",
"(",
"self",
")",
":",
"# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"3",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"3",
")",
"/",
"(",
"self",
"... | omega3 < omega < omega4 | [
"omega3",
"<",
"omega",
"<",
"omega4"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L450-L454 | train | 222,457 |
mattupstate/flask-security | flask_security/datastore.py | UserDatastore.deactivate_user | def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False | python | def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False | [
"def",
"deactivate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"False",
"return",
"True",
"return",
"False"
] | Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate | [
"Deactivates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L180-L188 | train | 222,458 |
mattupstate/flask-security | flask_security/datastore.py | UserDatastore.activate_user | def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | python | def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | [
"def",
"activate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"True",
"return",
"True",
"return",
"False"
] | Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate | [
"Activates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L190-L198 | train | 222,459 |
mattupstate/flask-security | flask_security/datastore.py | UserDatastore.create_role | def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role) | python | def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role) | [
"def",
"create_role",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"role",
"=",
"self",
".",
"role_model",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"put",
"(",
"role",
")"
] | Creates and returns a new role from the given parameters. | [
"Creates",
"and",
"returns",
"a",
"new",
"role",
"from",
"the",
"given",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L200-L204 | train | 222,460 |
mattupstate/flask-security | flask_security/datastore.py | UserDatastore.find_or_create_role | def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | python | def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | [
"def",
"find_or_create_role",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"name\"",
"]",
"=",
"name",
"return",
"self",
".",
"find_role",
"(",
"name",
")",
"or",
"self",
".",
"create_role",
"(",
"*",
"*",
"kwargs",
"... | Returns a role matching the given name or creates it with any
additionally provided parameters. | [
"Returns",
"a",
"role",
"matching",
"the",
"given",
"name",
"or",
"creates",
"it",
"with",
"any",
"additionally",
"provided",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L206-L211 | train | 222,461 |
mattupstate/flask-security | flask_security/decorators.py | http_auth_required | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | python | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | [
"def",
"http_auth_required",
"(",
"realm",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_http_auth",
"(",
")",
":",
"return",
"f... | Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"Basic",
"HTTP",
"authentication",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L93-L114 | train | 222,462 |
mattupstate/flask-security | flask_security/decorators.py | auth_token_required | def auth_token_required(fn):
"""Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
"""
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | python | def auth_token_required(fn):
"""Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
"""
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | [
"def",
"auth_token_required",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_token",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg... | Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER` | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"token",
"authentication",
".",
"The",
"token",
"should",
"be",
"added",
"to",
"the",
"request",
"by",
"the",
"client",
"by",
"using",
"a",
"query",
"string",
"variable",
"with",
"a",
"name",
"equal",
"t... | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L117-L133 | train | 222,463 |
mattupstate/flask-security | flask_security/confirmable.py | confirm_user | def confirm_user(user):
"""Confirms the specified user
:param user: The user to confirm
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | python | def confirm_user(user):
"""Confirms the specified user
:param user: The user to confirm
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | [
"def",
"confirm_user",
"(",
"user",
")",
":",
"if",
"user",
".",
"confirmed_at",
"is",
"not",
"None",
":",
"return",
"False",
"user",
".",
"confirmed_at",
"=",
"_security",
".",
"datetime_factory",
"(",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"u... | Confirms the specified user
:param user: The user to confirm | [
"Confirms",
"the",
"specified",
"user"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/confirmable.py#L82-L92 | train | 222,464 |
mattupstate/flask-security | flask_security/recoverable.py | send_password_reset_notice | def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | python | def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | [
"def",
"send_password_reset_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_RESET_NOTICE_EMAIL'",
")",
":",
"_security",
".",
"send_mail",
"(",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_NOTICE'",
")",
",",
"user",
".",
"email",
",",
"'... | Sends the password reset notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"reset",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L45-L52 | train | 222,465 |
mattupstate/flask-security | flask_security/recoverable.py | update_password | def update_password(user, password):
"""Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | python | def update_password(user, password):
"""Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | [
"def",
"update_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_reset_notice",
"(",
"user",
")",
"password_reset",
".",
"send",
... | Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password | [
"Update",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L84-L93 | train | 222,466 |
mattupstate/flask-security | flask_security/core.py | Security.init_app | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not.
"""
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | python | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not.
"""
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"datastore",
"=",
"None",
",",
"register_blueprint",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app",
"=",
"app",
"if",
"datastore",
"is",
"None",
":",
"datastore",
"=",
"self",
".",... | Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not. | [
"Initializes",
"the",
"Flask",
"-",
"Security",
"extension",
"for",
"the",
"specified",
"application",
"and",
"datastore",
"implementation",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/core.py#L511-L560 | train | 222,467 |
mattupstate/flask-security | flask_security/views.py | login | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | python | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | [
"def",
"login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_cl... | View function for login view | [
"View",
"function",
"for",
"login",
"view"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L67-L89 | train | 222,468 |
mattupstate/flask-security | flask_security/views.py | register | def register():
"""View function which handles a registration request."""
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | python | def register():
"""View function which handles a registration request."""
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | [
"def",
"register",
"(",
")",
":",
"if",
"_security",
".",
"confirmable",
"or",
"request",
".",
"is_json",
":",
"form_class",
"=",
"_security",
".",
"confirm_register_form",
"else",
":",
"form_class",
"=",
"_security",
".",
"register_form",
"if",
"request",
"."... | View function which handles a registration request. | [
"View",
"function",
"which",
"handles",
"a",
"registration",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L102-L139 | train | 222,469 |
mattupstate/flask-security | flask_security/views.py | send_login | def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | python | def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | [
"def",
"send_login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"passwordless_login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",... | View function that sends login instructions for passwordless login | [
"View",
"function",
"that",
"sends",
"login",
"instructions",
"for",
"passwordless",
"login"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L142-L162 | train | 222,470 |
mattupstate/flask-security | flask_security/views.py | token_login | def token_login(token):
"""View function that handles passwordless login via a token"""
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | python | def token_login(token):
"""View function that handles passwordless login via a token"""
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | [
"def",
"token_login",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"login_token_status",
"(",
"token",
")",
"if",
"invalid",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INVALID_LOGIN_TOKEN'",
")",
")",
"if",
"expired",
":",
"se... | View function that handles passwordless login via a token | [
"View",
"function",
"that",
"handles",
"passwordless",
"login",
"via",
"a",
"token"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L166-L184 | train | 222,471 |
mattupstate/flask-security | flask_security/views.py | send_confirmation | def send_confirmation():
"""View function which sends confirmation instructions."""
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | python | def send_confirmation():
"""View function which sends confirmation instructions."""
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | [
"def",
"send_confirmation",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"send_confirmation_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"... | View function which sends confirmation instructions. | [
"View",
"function",
"which",
"sends",
"confirmation",
"instructions",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L187-L210 | train | 222,472 |
mattupstate/flask-security | flask_security/views.py | confirm_email | def confirm_email(token):
"""View function which handles a email confirmation request."""
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | python | def confirm_email(token):
"""View function which handles a email confirmation request."""
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | [
"def",
"confirm_email",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"confirm_email_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INV... | View function which handles a email confirmation request. | [
"View",
"function",
"which",
"handles",
"a",
"email",
"confirmation",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L213-L244 | train | 222,473 |
mattupstate/flask-security | flask_security/views.py | forgot_password | def forgot_password():
"""View function that handles a forgotten password request."""
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | python | def forgot_password():
"""View function that handles a forgotten password request."""
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | [
"def",
"forgot_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"forgot_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form... | View function that handles a forgotten password request. | [
"View",
"function",
"that",
"handles",
"a",
"forgotten",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L248-L269 | train | 222,474 |
mattupstate/flask-security | flask_security/views.py | reset_password | def reset_password(token):
"""View function that handles a reset password request."""
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | python | def reset_password(token):
"""View function that handles a reset password request."""
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | [
"def",
"reset_password",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"reset_password_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'I... | View function that handles a reset password request. | [
"View",
"function",
"that",
"handles",
"a",
"reset",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L273-L303 | train | 222,475 |
mattupstate/flask-security | flask_security/views.py | change_password | def change_password():
"""View function which handles a change password request."""
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | python | def change_password():
"""View function which handles a change password request."""
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | [
"def",
"change_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"change_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form... | View function which handles a change password request. | [
"View",
"function",
"which",
"handles",
"a",
"change",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L307-L334 | train | 222,476 |
mattupstate/flask-security | flask_security/views.py | create_blueprint | def create_blueprint(state, import_name):
"""Creates the security extension blueprint"""
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | python | def create_blueprint(state, import_name):
"""Creates the security extension blueprint"""
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | [
"def",
"create_blueprint",
"(",
"state",
",",
"import_name",
")",
":",
"bp",
"=",
"Blueprint",
"(",
"state",
".",
"blueprint_name",
",",
"import_name",
",",
"url_prefix",
"=",
"state",
".",
"url_prefix",
",",
"subdomain",
"=",
"state",
".",
"subdomain",
",",... | Creates the security extension blueprint | [
"Creates",
"the",
"security",
"extension",
"blueprint"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L337-L387 | train | 222,477 |
mattupstate/flask-security | flask_security/utils.py | login_user | def login_user(user, remember=None):
"""Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False``
"""
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | python | def login_user(user, remember=None):
"""Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False``
"""
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | [
"def",
"login_user",
"(",
"user",
",",
"remember",
"=",
"None",
")",
":",
"if",
"remember",
"is",
"None",
":",
"remember",
"=",
"config_value",
"(",
"'DEFAULT_REMEMBER_ME'",
")",
"if",
"not",
"_login_user",
"(",
"user",
",",
"remember",
")",
":",
"# pragma... | Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False`` | [
"Perform",
"the",
"login",
"routine",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L63-L98 | train | 222,478 |
mattupstate/flask-security | flask_security/utils.py | logout_user | def logout_user():
"""Logs out the current.
This will also clean up the remember me cookie if it exists.
"""
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | python | def logout_user():
"""Logs out the current.
This will also clean up the remember me cookie if it exists.
"""
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | [
"def",
"logout_user",
"(",
")",
":",
"for",
"key",
"in",
"(",
"'identity.name'",
",",
"'identity.auth_type'",
")",
":",
"session",
".",
"pop",
"(",
"key",
",",
"None",
")",
"identity_changed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",... | Logs out the current.
This will also clean up the remember me cookie if it exists. | [
"Logs",
"out",
"the",
"current",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L101-L111 | train | 222,479 |
mattupstate/flask-security | flask_security/utils.py | verify_password | def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | python | def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | [
"def",
"verify_password",
"(",
"password",
",",
"password_hash",
")",
":",
"if",
"use_double_hash",
"(",
"password_hash",
")",
":",
"password",
"=",
"get_hmac",
"(",
"password",
")",
"return",
"_pwd_context",
".",
"verify",
"(",
"password",
",",
"password_hash",... | Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database) | [
"Returns",
"True",
"if",
"the",
"password",
"matches",
"the",
"supplied",
"hash",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L132-L142 | train | 222,480 |
mattupstate/flask-security | flask_security/utils.py | find_redirect | def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for
"""
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | python | def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for
"""
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | [
"def",
"find_redirect",
"(",
"key",
")",
":",
"rv",
"=",
"(",
"get_url",
"(",
"session",
".",
"pop",
"(",
"key",
".",
"lower",
"(",
")",
",",
"None",
")",
")",
"or",
"get_url",
"(",
"current_app",
".",
"config",
"[",
"key",
".",
"upper",
"(",
")"... | Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for | [
"Returns",
"the",
"URL",
"to",
"redirect",
"to",
"after",
"a",
"user",
"logs",
"in",
"successfully",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L306-L313 | train | 222,481 |
mattupstate/flask-security | flask_security/utils.py | send_mail | def send_mail(subject, recipient, template, **context):
"""Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | python | def send_mail(subject, recipient, template, **context):
"""Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | [
"def",
"send_mail",
"(",
"subject",
",",
"recipient",
",",
"template",
",",
"*",
"*",
"context",
")",
":",
"context",
".",
"setdefault",
"(",
"'security'",
",",
"_security",
")",
"context",
".",
"update",
"(",
"_security",
".",
"_run_ctx_processor",
"(",
"... | Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | [
"Send",
"an",
"email",
"via",
"the",
"Flask",
"-",
"Mail",
"extension",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L373-L404 | train | 222,482 |
mattupstate/flask-security | flask_security/utils.py | capture_registrations | def capture_registrations():
"""Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to
"""
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | python | def capture_registrations():
"""Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to
"""
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | [
"def",
"capture_registrations",
"(",
")",
":",
"registrations",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"registrations",
".",
"append",
"(",
"data",
")",
"user_registered",
".",
"connect",
"(",
"_on",
")",
"try",
":",
... | Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"registrations",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L481-L497 | train | 222,483 |
mattupstate/flask-security | flask_security/utils.py | capture_reset_password_requests | def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | python | def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | [
"def",
"capture_reset_password_requests",
"(",
"reset_password_sent_at",
"=",
"None",
")",
":",
"reset_requests",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"reset_requests",
".",
"append",
"(",
"data",
")",
"reset_password_instr... | Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"password",
"reset",
"requests",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L501-L517 | train | 222,484 |
mattupstate/flask-security | flask_security/passwordless.py | send_login_instructions | def send_login_instructions(user):
"""Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token
"""
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | python | def send_login_instructions(user):
"""Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token
"""
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | [
"def",
"send_login_instructions",
"(",
"user",
")",
":",
"token",
"=",
"generate_login_token",
"(",
"user",
")",
"login_link",
"=",
"url_for_security",
"(",
"'token_login'",
",",
"token",
"=",
"token",
",",
"_external",
"=",
"True",
")",
"_security",
".",
"sen... | Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token | [
"Sends",
"the",
"login",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/passwordless.py#L24-L37 | train | 222,485 |
mattupstate/flask-security | flask_security/cli.py | roles_add | def roles_add(user, role):
"""Add user to role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | python | def roles_add(user, role):
"""Add user to role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | [
"def",
"roles_add",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find user.'... | Add user to role. | [
"Add",
"user",
"to",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L93-L104 | train | 222,486 |
mattupstate/flask-security | flask_security/cli.py | roles_remove | def roles_remove(user, role):
"""Remove user from role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | python | def roles_remove(user, role):
"""Remove user from role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | [
"def",
"roles_remove",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find use... | Remove user from role. | [
"Remove",
"user",
"from",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L112-L123 | train | 222,487 |
mattupstate/flask-security | flask_security/changeable.py | send_password_changed_notice | def send_password_changed_notice(user):
"""Sends the password changed notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | python | def send_password_changed_notice(user):
"""Sends the password changed notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | [
"def",
"send_password_changed_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_CHANGE_EMAIL'",
")",
":",
"subject",
"=",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE'",
")",
"_security",
".",
"send_mail",
"(",
"subject",
",",
"... | Sends the password changed notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"changed",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L25-L32 | train | 222,488 |
mattupstate/flask-security | flask_security/changeable.py | change_user_password | def change_user_password(user, password):
"""Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | python | def change_user_password(user, password):
"""Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | [
"def",
"change_user_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_changed_notice",
"(",
"user",
")",
"password_changed",
".",
"... | Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password | [
"Change",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L35-L45 | train | 222,489 |
jd/tenacity | tenacity/after.py | after_log | def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | python | def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | [
"def",
"after_log",
"(",
"logger",
",",
"log_level",
",",
"sec_format",
"=",
"\"%0.3f\"",
")",
":",
"log_tpl",
"=",
"(",
"\"Finished call to '%s' after \"",
"+",
"str",
"(",
"sec_format",
")",
"+",
"\"(s), \"",
"\"this was the %s time calling it.\"",
")",
"def",
"... | After call strategy that logs to some logger the finished attempt. | [
"After",
"call",
"strategy",
"that",
"logs",
"to",
"some",
"logger",
"the",
"finished",
"attempt",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/after.py#L24-L35 | train | 222,490 |
jd/tenacity | tenacity/__init__.py | retry | def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | python | def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"return",
"retry",
"(",
")",
"... | Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object | [
"Wrap",
"a",
"function",
"with",
"a",
"new",
"Retrying",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L88-L109 | train | 222,491 |
jd/tenacity | tenacity/__init__.py | BaseRetrying.copy | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
"""Copy this object with some parameters changed if needed."""
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | python | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
"""Copy this object with some parameters changed if needed."""
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | [
"def",
"copy",
"(",
"self",
",",
"sleep",
"=",
"_unset",
",",
"stop",
"=",
"_unset",
",",
"wait",
"=",
"_unset",
",",
"retry",
"=",
"_unset",
",",
"before",
"=",
"_unset",
",",
"after",
"=",
"_unset",
",",
"before_sleep",
"=",
"_unset",
",",
"reraise... | Copy this object with some parameters changed if needed. | [
"Copy",
"this",
"object",
"with",
"some",
"parameters",
"changed",
"if",
"needed",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L231-L246 | train | 222,492 |
jd/tenacity | tenacity/__init__.py | BaseRetrying.statistics | def statistics(self):
"""Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread).
"""
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | python | def statistics(self):
"""Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread).
"""
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | [
"def",
"statistics",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_local",
".",
"statistics",
"except",
"AttributeError",
":",
"self",
".",
"_local",
".",
"statistics",
"=",
"{",
"}",
"return",
"self",
".",
"_local",
".",
"statistics"
] | Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread). | [
"Return",
"a",
"dictionary",
"of",
"runtime",
"statistics",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L258-L283 | train | 222,493 |
jd/tenacity | tenacity/__init__.py | BaseRetrying.wraps | def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | python | def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | [
"def",
"wraps",
"(",
"self",
",",
"f",
")",
":",
"@",
"_utils",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw"... | Wrap a function for retrying.
:param f: A function to wraps for retrying. | [
"Wrap",
"a",
"function",
"for",
"retrying",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L285-L300 | train | 222,494 |
jd/tenacity | tenacity/__init__.py | Future.construct | def construct(cls, attempt_number, value, has_exception):
"""Construct a new Future object."""
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | python | def construct(cls, attempt_number, value, has_exception):
"""Construct a new Future object."""
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | [
"def",
"construct",
"(",
"cls",
",",
"attempt_number",
",",
"value",
",",
"has_exception",
")",
":",
"fut",
"=",
"cls",
"(",
"attempt_number",
")",
"if",
"has_exception",
":",
"fut",
".",
"set_exception",
"(",
"value",
")",
"else",
":",
"fut",
".",
"set_... | Construct a new Future object. | [
"Construct",
"a",
"new",
"Future",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L388-L395 | train | 222,495 |
jd/tenacity | tenacity/_utils.py | get_callback_name | def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | python | def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | [
"def",
"get_callback_name",
"(",
"cb",
")",
":",
"segments",
"=",
"[",
"]",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__qualname__",
")",
"except",
"AttributeError",
":",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__name__",
... | Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned. | [
"Get",
"a",
"callback",
"fully",
"-",
"qualified",
"name",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/_utils.py#L98-L128 | train | 222,496 |
jd/tenacity | tenacity/compat.py | make_retry_state | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | python | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | [
"def",
"make_retry_state",
"(",
"previous_attempt_number",
",",
"delay_since_first_attempt",
",",
"last_result",
"=",
"None",
")",
":",
"required_parameter_unset",
"=",
"(",
"previous_attempt_number",
"is",
"_unset",
"or",
"delay_since_first_attempt",
"is",
"_unset",
")",... | Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics. | [
"Construct",
"RetryCallState",
"for",
"given",
"attempt",
"number",
"&",
"delay",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L57-L79 | train | 222,497 |
jd/tenacity | tenacity/compat.py | func_takes_last_result | def func_takes_last_result(waiter):
"""Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning.
"""
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | python | def func_takes_last_result(waiter):
"""Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning.
"""
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | [
"def",
"func_takes_last_result",
"(",
"waiter",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"waiter",
")",
":",
"return",
"False",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"waiter",
")",
"and",
"not",
"inspect",
".",
"ismethod",
"(",
"wait... | Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning. | [
"Check",
"if",
"function",
"has",
"a",
"last_result",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L82-L94 | train | 222,498 |
jd/tenacity | tenacity/compat.py | stop_func_accept_retry_state | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | python | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | [
"def",
"stop_func_accept_retry_state",
"(",
"stop_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"if",
"func_takes_retry_state",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"@",
"_utils",
".",
"w... | Wrap "stop" function to accept "retry_state" parameter. | [
"Wrap",
"stop",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L120-L136 | train | 222,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.