Skip to content

Commit

Permalink
Merge pull request #2285 from janosh/str-fixes
Browse files Browse the repository at this point in the history
Fix oddly split strings and a few typos
  • Loading branch information
mkhorton committed Nov 9, 2021
2 parents 39612af + b180cac commit 9276567
Show file tree
Hide file tree
Showing 120 changed files with 396 additions and 508 deletions.
17 changes: 9 additions & 8 deletions dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
"""

import json
import re
from itertools import product

import ruamel.yaml as yaml
import re

from monty.serialization import loadfn, dumpfn
from monty.serialization import dumpfn, loadfn

from pymatgen.core import Element
from pymatgen.core.periodic_table import get_el_sp
Expand Down Expand Up @@ -88,7 +87,7 @@ def parse_ionic_radii():

ionic_radii = {}
for j in range(3, len(toks)):
m = re.match("^\s*([0-9\.]+)", toks[j])
m = re.match(r"^\s*([0-9\.]+)", toks[j])
if m:
ionic_radii[int(header[j])] = float(m.group(1))

Expand All @@ -109,7 +108,7 @@ def parse_radii():
radiidata = f.read()
f.close()
radiidata = radiidata.split("\r")
header = radiidata[0].split(",")

for i in range(1, len(radiidata)):
line = radiidata[i]
toks = line.strip().split(",")
Expand Down Expand Up @@ -164,9 +163,10 @@ def update_ionic_radii():
def parse_shannon_radii():
with open("periodic_table.yaml", "r") as f:
data = yaml.load(f)
from openpyxl import load_workbook
import collections

from openpyxl import load_workbook

wb = load_workbook("Shannon Radii.xlsx")
print(wb.get_sheet_names())
sheet = wb["Sheet1"]
Expand Down Expand Up @@ -259,8 +259,8 @@ def add_electron_affinities():
"""
Update the periodic table data file with electron affinities.
"""
from bs4 import BeautifulSoup
import requests
from bs4 import BeautifulSoup

req = requests.get("https://en.wikipedia.org/wiki/Electron_affinity_(data_page)")
soup = BeautifulSoup(req.text, "html.parser")
Expand All @@ -287,9 +287,10 @@ def add_ionization_energies():
"""
Update the periodic table data file with ground level and ionization energies from NIST.
"""
from bs4 import BeautifulSoup
import collections

from bs4 import BeautifulSoup

with open("NIST Atomic Ionization Energies Output.html") as f:
soup = BeautifulSoup(f.read(), "html.parser")
for t in soup.find_all("table"):
Expand Down
4 changes: 2 additions & 2 deletions docs_rst/conf-docset.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
Expand All @@ -22,7 +22,7 @@
sys.path.insert(0, os.path.dirname("../pymatgen"))
sys.path.insert(0, os.path.dirname("../.."))

from pymatgen.core import __version__, __author__
from pymatgen.core import __author__, __version__

# -- General configuration -----------------------------------------------------

Expand Down
4 changes: 2 additions & 2 deletions docs_rst/conf-normal.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import sys

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
Expand All @@ -22,7 +22,7 @@
sys.path.insert(0, os.path.dirname("../pymatgen"))
sys.path.insert(0, os.path.dirname("../.."))

from pymatgen.core import __version__, __author__, __file__
from pymatgen.core import __author__, __file__, __version__

# -- General configuration -----------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion pre-commit
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/bash
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def undo_last_change(self):
if len(self.history) == 0:
raise IndexError("Can't undo. Already at oldest change.")
if "input_structure" not in self.history[-1]:
raise IndexError("Can't undo. Latest history has no " "input_structure")
raise IndexError("Can't undo. Latest history has no input_structure")
h = self.history.pop()
self._undone.append((h, self.final_structure))
s = h["input_structure"]
Expand Down Expand Up @@ -301,7 +301,7 @@ def from_poscar_string(poscar_string, transformations=None):
p = Poscar.from_string(poscar_string)
if not p.true_names:
raise ValueError(
"Transformation can be craeted only from POSCAR " "strings with proper VASP5 element symbols."
"Transformation can be created only from POSCAR strings with proper VASP5 element symbols."
)
raw_string = re.sub(r"'", '"', poscar_string)
s = p.structure
Expand Down Expand Up @@ -341,7 +341,7 @@ def to_snl(self, authors, **kwargs):
:return: StructureNL
"""
if self.other_parameters:
warn("Data in TransformedStructure.other_parameters discarded " "during type conversion to SNL")
warn("Data in TransformedStructure.other_parameters discarded during type conversion to SNL")
hist = []
for h in self.history:
snl_metadata = h.pop("_snl", {})
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/alchemy/tests/test_materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def test_snl(self):
self.assertEqual(
len(w),
1,
"Warning not raised on type conversion " "with other_parameters",
"Warning not raised on type conversion with other_parameters",
)
ts = TransformedStructure.from_snl(snl)
self.assertEqual(ts.history[-1]["@class"], "SubstitutionTransformation")
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,4 +514,4 @@ def add_oxidation_state_by_site_fraction(structure, oxidation_states):
structure[i] = new_sp
return structure
except IndexError:
raise ValueError("Oxidation state of all sites must be " "specified in the list.")
raise ValueError("Oxidation state of all sites must be specified in the list.")
Original file line number Diff line number Diff line change
Expand Up @@ -838,7 +838,7 @@ def _edgekey_to_edgedictkey(key):
if isinstance(key, str):
try:
int(key)
raise RuntimeError("Cannot pass an edge key which is a str " "representation of an int.")
raise RuntimeError("Cannot pass an edge key which is a str representation of an int.")
except ValueError:
return key
raise ValueError("Edge key should be either a str or an int.")
Expand All @@ -853,9 +853,7 @@ def _edgedictkey_to_edgekey(key):
except ValueError:
return key
else:
raise ValueError(
"Edge key in a dict of dicts representation of a graph" "should be either a str or an int."
)
raise ValueError("Edge key in a dict of dicts representation of a graph should be either a str or an int.")

@staticmethod
def _retuplify_edgedata(edata):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def get_structure_connectivity(self, light_structure_environments):
if len(site_neighbors_sets) > 1:
if self.multiple_environments_choice is None:
raise ValueError(
"Local environment of site {:d} is a mix and " "nothing is asked about it".format(isite)
"Local environment of site {:d} is a mix and nothing is asked about it".format(isite)
)
if self.multiple_environments_choice == "TAKE_HIGHEST_FRACTION":
imax = np.argmax(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ def compute_structure_environments(
for isite, site in enumerate(self.structure):
if isite not in sites_indices:
logging.debug(
" ... in site #{:d}/{:d} ({}) : " "skipped".format(isite, len(self.structure), site.species_string)
" ... in site #{:d}/{:d} ({}) : skipped".format(isite, len(self.structure), site.species_string)
)
continue
if breakit:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1514,7 +1514,7 @@ def __ne__(self, other):
def __str__(self):
out = "Neighbors Set for site #{:d} :\n".format(self.isite)
out += " - Coordination number : {:d}\n".format(len(self))
out += " - Neighbors sites indices : {}" "\n".format(
out += " - Neighbors sites indices : {}\n".format(
", ".join(["{:d}".format(nb_list_index) for nb_list_index in self.all_nbs_sites_indices])
)
return out
Expand Down Expand Up @@ -1647,7 +1647,7 @@ def from_structure_environments(cls, strategy, structure_environments, valences=
rounddiff = np.round(diff)
if not np.allclose(diff, rounddiff):
raise ValueError(
"Weird, differences between one site in a periodic image cell is not " "integer ..."
"Weird, differences between one site in a periodic image cell is not integer ..."
)
nb_image_cell = np.array(rounddiff, np.int_)
nb_allnbs_sites_index = len(_all_nbs_sites)
Expand Down Expand Up @@ -2135,9 +2135,7 @@ def from_dict(cls, d):
diff = site.frac_coords - structure[nb_site["index"]].frac_coords
rounddiff = np.round(diff)
if not np.allclose(diff, rounddiff):
raise ValueError(
"Weird, differences between one site in a periodic image cell is not " "integer ..."
)
raise ValueError("Weird, differences between one site in a periodic image cell is not integer ...")
image_cell = np.array(rounddiff, np.int_)
all_nbs_sites.append({"site": site, "index": nb_site["index"], "image_cell": image_cell})
neighbors_sets = [
Expand Down Expand Up @@ -2177,7 +2175,7 @@ def __init__(self, coord_geoms=None):
self.coord_geoms = {}
else:
raise NotImplementedError(
"Constructor for ChemicalEnvironments with the coord_geoms argument is not" "yet implemented"
"Constructor for ChemicalEnvironments with the coord_geoms argument is not yet implemented"
)

def __getitem__(self, mp_symbol):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_algorithms(self):

self.assertEqual(
sepplane_algos_oct[0].__str__(),
"Separation plane algorithm with the following reference separation :\n" "[[4]] | [[0, 2, 1, 3]] | [[5]]",
"Separation plane algorithm with the following reference separation :\n[[4]] | [[0, 2, 1, 3]] | [[5]]",
)

def test_hints(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def test_structure_environments_neighbors_sets(self):

self.assertEqual(
nb_set.__str__(),
"Neighbors Set for site #6 :\n" " - Coordination number : 4\n" " - Voronoi indices : 1, 4, 5, 6\n",
"Neighbors Set for site #6 :\n - Coordination number : 4\n - Voronoi indices : 1, 4, 5, 6\n",
)

self.assertFalse(nb_set.__ne__(nb_set))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def setup_voronoi_list(self, indices, voronoi_cutoff):
ridge_vertices_indices = voro.ridge_vertices[iridge]
if -1 in ridge_vertices_indices:
raise RuntimeError(
"This structure is pathological," " infinite vertex in the voronoi " "construction"
"This structure is pathological, infinite vertex in the voronoi construction"
)

ridge_point2 = max(ridge_points)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/chemenv/utils/chemenv_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(self, cosinus):
self.cosinus = cosinus

def __str__(self):
return "Value of cosinus ({}) from which an angle should be retrieved" "is not between -1.0 and 1.0".format(
return "Value of cosinus ({}) from which an angle should be retrieved is not between -1.0 and 1.0".format(
self.cosinus
)

Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/chemenv/utils/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def get_delta(node1, node2, edge_data):
return np.array(edge_data["delta"], dtype=np.int_)
if node2.isite == edge_data["start"] and node1.isite == edge_data["end"]:
return -np.array(edge_data["delta"], dtype=np.int_)
raise ValueError("Trying to find a delta between two nodes with an edge " "that seems not to link these nodes.")
raise ValueError("Trying to find a delta between two nodes with an edge that seems not to link these nodes.")


def get_all_simple_paths_edges(graph, source, target, cutoff=None, data=True):
Expand Down Expand Up @@ -229,7 +229,7 @@ def order(self, raise_on_fail=True):
node_classes = set(n.__class__ for n in self.nodes)
if len(node_classes) > 1:
if raise_on_fail:
raise ValueError("Could not order simple graph cycle as the nodes " "are of different classes.")
raise ValueError("Could not order simple graph cycle as the nodes are of different classes.")
self.ordered = False
return

Expand Down Expand Up @@ -420,7 +420,7 @@ def order(self, raise_on_fail=True):
node_classes = set(n.__class__ for n in self.nodes)
if len(node_classes) > 1:
if raise_on_fail:
raise ValueError("Could not order simple graph cycle as the nodes " "are of different classes.")
raise ValueError("Could not order simple graph cycle as the nodes are of different classes.")
self.ordered = False
return

Expand Down
Loading

0 comments on commit 9276567

Please sign in to comment.