Skip to content

Commit

Permalink
replace tests 'str(x) is not None' with actual expected value (#3472)
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Nov 14, 2023
1 parent 8aee215 commit 6e94085
Show file tree
Hide file tree
Showing 39 changed files with 168 additions and 195 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1191,8 +1191,7 @@ def get_coordination_symmetry_measures(self, only_minimum=True, all_csms=True, o
def _update_results_all_csms(self, result_dict, permutations, imin, geometry):
permutation = permutations[imin]
# Without central site, centered on the centroid (centroid does not include the central site)
# result_dict[geometry.mp_symbol]['csm_wocs_ctwocc'] = \
# result[imin]
# result_dict[geometry.mp_symbol]['csm_wocs_ctwocc'] = result[imin]
pdist = self.local_geometry.points_wocs_ctwocc(permutation=permutation)
pperf = self.perfect_geometry.points_wocs_ctwocc()
sm_info = symmetry_measure(points_distorted=pdist, points_perfect=pperf)
Expand Down
28 changes: 14 additions & 14 deletions pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,23 +205,23 @@ def diamond_functions(xx, yy, y_x0, x_y0):
Returns:
A dictionary with the lower and upper diamond functions.
"""
npxx = np.array(xx)
npyy = np.array(yy)
if np.any(npxx == npyy):
np_xx = np.array(xx)
np_yy = np.array(yy)
if np.any(np_xx == np_yy):
raise RuntimeError("Invalid points for diamond_functions")
if np.all(npxx < npyy) or np.all(npxx > npyy):
if npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
if np.all(np_xx < np_yy) or np.all(np_xx > np_yy):
if np_xx[0] < np_yy[0]:
p1 = np_xx
p2 = np_yy
else:
p1 = npyy
p2 = npxx
elif npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
p1 = np_yy
p2 = np_xx
elif np_xx[0] < np_yy[0]:
p1 = np_xx
p2 = np_yy
else:
p1 = npyy
p2 = npxx
p1 = np_yy
p2 = np_xx
slope = (p2[1] - p1[1]) / (p2[0] - p1[0])
if slope > 0.0:
x_bpoint = p1[0] + x_y0
Expand Down
10 changes: 2 additions & 8 deletions pymatgen/analysis/elasticity/stress.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ def piola_kirchoff_1(self, def_grad):
def_grad (3x3 array-like): deformation gradient tensor
"""
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
raise ValueError("The stress tensor is not symmetric, PK stress is based on a symmetric stress tensor.")
def_grad = SquareTensor(def_grad)
return def_grad.det * np.dot(self, def_grad.inv.trans)

Expand All @@ -97,8 +94,5 @@ def piola_kirchoff_2(self, def_grad):
"""
def_grad = SquareTensor(def_grad)
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
raise ValueError("The stress tensor is not symmetric, PK stress is based on a symmetric stress tensor.")
return def_grad.det * np.dot(np.dot(def_grad.inv, self), def_grad.inv.trans)
3 changes: 1 addition & 2 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4204,8 +4204,7 @@ def from_preset(cls, preset) -> CutOffDictNN:
Args:
preset (str): A preset name. The list of supported presets are:
- "vesta_2019": The distance cutoffs used by the VESTA
visualisation program.
- "vesta_2019": The distance cutoffs used by the VESTA visualisation program.
Returns:
A CutOffDictNN using the preset cut-off dictionary.
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/structure_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ def average_coordination_number(structures, freq=10):
for spec in structures[0].composition.as_dict():
coordination_numbers[spec] = 0.0
count = 0
for i, s in enumerate(structures):
if i % freq != 0:
for idx, site in enumerate(structures):
if idx % freq != 0:
continue
count += 1
vnn = VoronoiNN()
for j, atom in enumerate(s):
cn = vnn.get_cn(s, j, use_weights=True)
for j, atom in enumerate(site):
cn = vnn.get_cn(site, j, use_weights=True)
coordination_numbers[atom.species_string] += cn
elements = structures[0].composition.as_dict()
return {el: v / elements[el] / count for el, v in coordination_numbers.items()}
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/surface_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,7 @@ def monolayer_vs_BE(self, plot_eads=False):
Args:
plot_eads (bool): Option to plot the adsorption energy (binding
energy multiplied by number of adsorbates) instead.
energy multiplied by number of adsorbates) instead.
Returns:
Plot: Plot of binding energy vs monolayer for all facets.
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -1315,7 +1315,7 @@ def get_points_in_sphere(
center: Cartesian coordinates of center of sphere.
r: radius of sphere.
zip_results (bool): Whether to zip the results together to group by
point, or return the raw fcoord, dist, index arrays
point, or return the raw fcoord, dist, index arrays
Returns:
if zip_results:
Expand Down Expand Up @@ -1389,7 +1389,7 @@ def get_points_in_sphere_py(
center: Cartesian coordinates of center of sphere.
r: radius of sphere.
zip_results (bool): Whether to zip the results together to group by
point, or return the raw fcoord, dist, index arrays
point, or return the raw fcoord, dist, index arrays
Returns:
if zip_results:
Expand Down Expand Up @@ -1446,7 +1446,7 @@ def get_points_in_sphere_old(
center: Cartesian coordinates of center of sphere.
r: radius of sphere.
zip_results (bool): Whether to zip the results together to group by
point, or return the raw fcoord, dist, index arrays
point, or return the raw fcoord, dist, index arrays
Returns:
if zip_results:
Expand Down
18 changes: 7 additions & 11 deletions pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,10 @@ def get_lattvec(self):

def bandana(self, emin=-np.inf, emax=np.inf):
"""Cut out bands outside the range (emin,emax)."""
bandmin = np.min(self.ebands_all, axis=1)
bandmax = np.max(self.ebands_all, axis=1)
ntoolow = np.count_nonzero(bandmax <= emin)
accepted = np.logical_and(bandmin < emax, bandmax > emin)
band_min = np.min(self.ebands_all, axis=1)
band_max = np.max(self.ebands_all, axis=1)
n_too_low = np.count_nonzero(band_max <= emin)
accepted = np.logical_and(band_min < emax, band_max > emin)
# self.data_bkp = np.copy(self.data.ebands)
self.ebands = self.ebands_all[accepted]

Expand All @@ -273,7 +273,7 @@ def bandana(self, emin=-np.inf, emax=np.inf):
self.mommat = self.mommat[:, accepted, :]
# Removing bands may change the number of valence electrons
if self.nelect_all:
self.nelect = self.nelect_all - self.dosweight * ntoolow
self.nelect = self.nelect_all - self.dosweight * n_too_low

return accepted

Expand All @@ -282,8 +282,7 @@ def set_upper_lower_bands(self, e_lower, e_upper):
range in the spin up/down bands when calculating the DOS.
"""
warnings.warn(
"This method does not work anymore in case of spin \
polarized case due to the concatenation of bands !"
"This method does not work anymore in case of spin polarized case due to the concatenation of bands !"
)

lower_band = e_lower * np.ones((1, self.ebands.shape[1]))
Expand Down Expand Up @@ -1166,10 +1165,7 @@ def merge_up_down_doses(dos_up, dos_dn):
Return:
CompleteDos object
"""
warnings.warn(
"This function is not useful anymore. VasprunBSLoader deals \
with spin case."
)
warnings.warn("This function is not useful anymore. VasprunBSLoader deals with spin case.")
cdos = Dos(
dos_up.efermi,
dos_up.energies,
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1524,9 +1524,9 @@ def get_projected_plots_dots_patom_pmorb(
result, correct index numbers of atoms.
sum_atoms: Sum projection of the similar atoms together (e.g.: Cu
on site-1 and Cu on site-5). The format is {Element: [Site numbers]}, for instance:
{'Cu': [1,5], 'O': [3,4]} means summing projections over Cu on site-1 and Cu on
site-5 and O on site-3 and on site-4. If you do not want to use this functional,
just turn it off by setting sum_atoms = None.
{'Cu': [1,5], 'O': [3,4]} means summing projections over Cu on site-1 and Cu on
site-5 and O on site-3 and on site-4. If you do not want to use this functional,
just turn it off by setting sum_atoms = None.
sum_morbs: Sum projections of individual orbitals of similar atoms
together (e.g.: 'dxy' and 'dxz'). The format is {Element: [individual orbitals]},
for instance: {'Cu': ['dxy', 'dxz'], 'O': ['px', 'py']} means summing projections
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/abinit/abiobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,8 +689,8 @@ def __init__(
Number of division for the sampling of the smallest segment if mode is "path".
Not used for the other modes
kpts: Number of divisions. Even when only a single specification is
required, e.g. in the automatic scheme, the kpts should still
be specified as a 2D array. e.g., [[20]] or [[2,2,2]].
required, e.g. in the automatic scheme, the kpts should still
be specified as a 2D array. e.g., [[20]] or [[2,2,2]].
kpt_shifts: Shifts for Kpoints.
use_symmetries: False if spatial symmetries should not be used
to reduce the number of independent k-points.
Expand Down
5 changes: 1 addition & 4 deletions pymatgen/io/exciting/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,7 @@ def write_etree(self, celltype, cartesian=False, bandstr=False, symprec: float =
symbol = "GAMMA"
_ = ET.SubElement(path, "point", coord=coord, label=symbol)
elif bandstr and celltype != "primitive":
raise ValueError(
"Bandstructure is only implemented for the \
standard primitive unit cell!"
)
raise ValueError("Bandstructure is only implemented for the standard primitive unit cell!")

# write extra parameters from kwargs if provided
self._dicttoxml(kwargs, root)
Expand Down
5 changes: 1 addition & 4 deletions pymatgen/io/feff/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,10 +244,7 @@ def tags(self) -> Tags:
mult = (self.nkpts * abc[0] * abc[1] * abc[2]) ** (1 / 3)
self.config_dict["KMESH"] = [int(round(mult / length)) for length in abc]
else:
logger.warning(
"Large system(>=14 atoms) or EXAFS calculation, \
removing K-space settings"
)
logger.warning("Large system(>=14 atoms) or EXAFS calculation, removing K-space settings")
del self.config_dict["RECIPROCAL"]
self.config_dict.pop("CIF", None)
self.config_dict.pop("TARGET", None)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/lammps/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,7 +1245,7 @@ def __init__(
"""
Args:
list_of_molecules: A list of LammpsData objects of a chemical cluster.
Each LammpsData object (cluster) may contain one or more molecule ID.
Each LammpsData object (cluster) may contain one or more molecule ID.
list_of_names: A list of name (string) for each cluster. The characters in each name are
restricted to word characters ([a-zA-Z0-9_]). If names with any non-word characters
are passed in, the special characters will be substituted by '_'.
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/io/lammps/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ def __init__(
) -> None:
"""
Args:
inputfile: The input file containing settings.
It can be a LammpsInputFile object or a string representation.
inputfile: The input file containing settings. It can be a LammpsInputFile object
or a string representation.
data: The data file containing structure and topology information.
It can be a LammpsData or a CombinedData object.
It can be a LammpsData or a CombinedData object.
calc_type: Human-readable string used to briefly describe the type of computations performed by LAMMPS.
template_file: Path (string) to the template file used to create the input file for LAMMPS.
keep_stages: Whether to keep the stage structure of the LammpsInputFile or not.
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/qchem/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,8 +615,8 @@ def svp_template(svp: dict) -> str:
Returns:
str: the $svp section. Note that all parameters will be concatenated onto
a single line formatted as a FORTRAN namelist. This is necessary
because the isodensity SS(V)PE model in Q-Chem calls a secondary code.
a single line formatted as a FORTRAN namelist. This is necessary
because the isodensity SS(V)PE model in Q-Chem calls a secondary code.
"""
svp_list = []
svp_list.append("$svp")
Expand Down
6 changes: 2 additions & 4 deletions pymatgen/io/shengbte.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,11 @@ def __init__(self, ngrid: list[int] | None = None, temperature: float | dict[str
for ShengBTE to run - we have listed these parameters below:
- nelements (int): number of different elements in the compound
- natoms (int): number of atoms in the unit cell
- lattvec (size 3x3 array): real-space lattice vectors, in units
of lfactor
- lattvec (size 3x3 array): real-space lattice vectors, in units of lfactor
- lfactor (float): unit of measurement for lattice vectors (nm).
I.e., set to 0.1 if lattvec given in Angstrom.
- types (size natom list): a vector of natom integers, ranging
from 1 to nelements, assigning an element to each atom in the
system
from 1 to nelements, assigning an element to each atom in the system
- elements (size natom list): a vector of element names
- positions (size natomx3 array): atomic positions in lattice
coordinates
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/vasp/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def __init__(
where no hashes will be determined and the potcar_spec dictionaries
will read {"symbol": ElSymbol, "hash": None}. By Default, looks in
the same directory as the vasprun.xml, with same extensions as
Vasprun.xml. If a string is provided, looks at that filepath.
Vasprun.xml. If a string is provided, looks at that filepath.
occu_tol (float): Sets the minimum tol for the determination of the
vbm and cbm. Usually the default of 1e-8 works well enough,
but there may be pathological cases.
Expand Down Expand Up @@ -1443,7 +1443,7 @@ def __init__(
where no hashes will be determined and the potcar_spec dictionaries
will read {"symbol": ElSymbol, "hash": None}. By Default, looks in
the same directory as the vasprun.xml, with same extensions as
Vasprun.xml. If a string is provided, looks at that filepath.
Vasprun.xml. If a string is provided, looks at that filepath.
occu_tol: Sets the minimum tol for the determination of the
vbm and cbm. Usually the default of 1e-8 works well enough,
but there may be pathological cases.
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/io/vasp/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -3072,16 +3072,16 @@ def batch_write_input(
in addition to structure.
"""
output_dir = Path(output_dir)
for i, s in enumerate(structures):
formula = re.sub(r"\s+", "", s.formula)
for idx, site in enumerate(structures):
formula = re.sub(r"\s+", "", site.formula)
if subfolder is not None:
subdir = subfolder(s)
subdir = subfolder(site)
d = output_dir / subdir
else:
d = output_dir / f"{formula}_{i}"
d = output_dir / f"{formula}_{idx}"
if sanitize:
s = s.copy(sanitize=True)
v = vasp_input_set(s, **kwargs)
site = site.copy(sanitize=True)
v = vasp_input_set(site, **kwargs)
v.write_input(
str(d),
make_dir_if_not_present=make_dir_if_not_present,
Expand Down Expand Up @@ -3195,7 +3195,7 @@ def __init__(
Need to be tested for convergence.
reciprocal_density: the k-points density
nkred: the reduced number of kpoints to calculate, equal to the k-mesh. Only applies in "RPA" mode
because of the q->0 limit.
because of the q->0 limit.
nedos: the density of DOS, default: 2001.
**kwargs: All kwargs supported by DictSet. Typically, user_incar_settings is a commonly used option.
"""
Expand Down
17 changes: 8 additions & 9 deletions pymatgen/io/zeopp.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,13 +336,12 @@ def get_high_accuracy_voronoi_nodes(structure, rad_dict, probe_rad=0.1):
for el in rad_dict:
print(f"{el} {rad_dict[el].real}", file=fp)

atmnet = AtomNetwork.read_from_CSSR(zeo_inp_filename, rad_flag=rad_flag, rad_file=rad_file)
# vornet, vor_edge_centers, vor_face_centers = \
# atmnet.perform_voronoi_decomposition()
red_ha_vornet = prune_voronoi_network_close_node(atmnet)
# generate_simplified_highaccuracy_voronoi_network(atmnet)
# get_nearest_largest_diameter_highaccuracy_vornode(atmnet)
red_ha_vornet.analyze_writeto_XYZ(name, probe_rad, atmnet)
atom_net = AtomNetwork.read_from_CSSR(zeo_inp_filename, rad_flag=rad_flag, rad_file=rad_file)
# vornet, vor_edge_centers, vor_face_centers = atom_net.perform_voronoi_decomposition()
red_ha_vornet = prune_voronoi_network_close_node(atom_net)
# generate_simplified_highaccuracy_voronoi_network(atom_net)
# get_nearest_largest_diameter_highaccuracy_vornode(atom_net)
red_ha_vornet.analyze_writeto_XYZ(name, probe_rad, atom_net)
voro_out_filename = name + "_voro.xyz"
voro_node_mol = ZeoVoronoiXYZ.from_file(voro_out_filename).molecule

Expand Down Expand Up @@ -403,9 +402,9 @@ def get_free_sphere_params(structure, rad_dict=None, probe_rad=0.1):
for el in rad_dict:
fp.write(f"{el} {rad_dict[el].real}\n")

atmnet = AtomNetwork.read_from_CSSR(zeo_inp_filename, rad_flag=rad_flag, rad_file=rad_file)
atom_net = AtomNetwork.read_from_CSSR(zeo_inp_filename, rad_flag=rad_flag, rad_file=rad_file)
out_file = "temp.res"
atmnet.calculate_free_sphere_parameters(out_file)
atom_net.calculate_free_sphere_parameters(out_file)
if os.path.isfile(out_file) and os.path.getsize(out_file) > 0:
with open(out_file) as fp:
output = fp.readline()
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/symmetry/kpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance=
"""
if "magmom" in structure.site_properties:
warn(
"'magmom' entry found in site properties but will be ignored \
for the Setyawan and Curtarolo convention."
"'magmom' entry found in site properties but will be ignored for the Setyawan and Curtarolo convention."
)

super().__init__(structure, symprec=symprec, angle_tolerance=angle_tolerance, atol=atol)
Expand Down
Loading

0 comments on commit 6e94085

Please sign in to comment.