:return: Number of items processed
:rtype: int
"""
- _log . debug ( "_build, chunk_size= {:d} " . format ( chunk_size ))
+ _log . debug ( f "_build, chunk_size= { chunk_size : d } " )
n , i = 0 , 0
for i , item in enumerate ( items ):
if i == 0 :
@@ -496,7 +489,7 @@ Source code for pymatgen.db.builders.core
processes [ i ] . join ()
code = processes [ i ] . exitcode
self . _status . success ( i ) if 0 == code else self . _status . fail ( i )
- _log . debug ( "run.parallel.multiprocess.end states= {} " . format ( self . _status ))
+ _log . debug ( f "run.parallel.multiprocess.end states= { self . _status } " )
def _run ( self , index ):
"""Run method for one thread or process
@@ -513,7 +506,7 @@ Source code for pymatgen.db.builders.core
except Queue . Empty :
break
except Exception as err :
- _log . error ( "In _run(): {} " . format ( err ))
+ _log . error ( f "In _run(): { err } " )
if _log . isEnabledFor ( logging . DEBUG ):
_log . error ( traceback . format_exc ())
self . _status . fail ( index )
@@ -595,16 +588,12 @@ Source code for pymatgen.db.builders.core
"""
sep = " \n " + " " * depth * indent
return "" . join (
- (
" {} : {}{} " . format (
k ,
- alphadump ( d [ k ], depth = depth + 1 )
- if isinstance ( d [ k ], dict )
- else str ( d [ k ]),
+ alphadump ( d [ k ], depth = depth + 1 ) if isinstance ( d [ k ], dict ) else str ( d [ k ]),
sep ,
)
for k in sorted ( d . keys ())
- )
)
@@ -624,7 +613,7 @@ Source code for pymatgen.db.builders.core
Quick search
diff --git a/docs/_modules/pymatgen/db/builders/examples/copy_builder.html b/docs/_modules/pymatgen/db/builders/examples/copy_builder.html
index 97b794e..eb7dadb 100644
--- a/docs/_modules/pymatgen/db/builders/examples/copy_builder.html
+++ b/docs/_modules/pymatgen/db/builders/examples/copy_builder.html
@@ -5,7 +5,7 @@
- pymatgen.db.builders.examples.copy_builder — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.builders.examples.copy_builder — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.examples.copy_builder
@@ -91,11 +91,7 @@
Source code for pymatgen.db.builders.examples.copy_builder if not crit : # reduce any False-y crit value to None
crit = None
cur = source . query ( criteria = crit )
- _log . info (
- "source.collection= {} crit= {} source_records= {:d} " . format (
- source . collection , crit , len ( cur )
- )
- )
+ _log . info ( f "source.collection= { source . collection } crit= { crit } source_records= { len ( cur ) : d } " )
return cur
[docs] def process_item ( self , item ):
@@ -119,7 +115,7 @@
Source code for pymatgen.db.builders.examples.copy_builder Quick search
diff --git a/docs/_modules/pymatgen/db/builders/examples/file_builders.html b/docs/_modules/pymatgen/db/builders/examples/file_builders.html
index 49ab0e5..3f393c4 100644
--- a/docs/_modules/pymatgen/db/builders/examples/file_builders.html
+++ b/docs/_modules/pymatgen/db/builders/examples/file_builders.html
@@ -5,7 +5,7 @@
-
pymatgen.db.builders.examples.file_builders — pymatgen-db 2021.5.28 documentation
+
pymatgen.db.builders.examples.file_builders — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@
Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.examples.file_builders
@@ -73,10 +73,9 @@
Source code for pymatgen.db.builders.examples.file_builders return { "input_file" : { "type" : "str" , "desc" : "Input file path" }}
[docs] def get_items ( self , input_file = None ):
-
with open ( input_file , "r" ) as f :
+
with open ( input_file ) as f :
# print("Reading from {}".format(f.name))
-
for line in f :
-
yield line
+
yield from f
[docs] def process_item ( self , item ):
self . num_chars += len ( item )
@@ -85,7 +84,7 @@
Source code for pymatgen.db.builders.examples.file_builders # self.num_lines, self.num_chars))
[docs] def finalize ( self , errors ):
-
print ( " {:d} lines, {:d} characters" . format ( self . num_lines , self . num_chars ))
+
print ( f " { self . num_lines : d } lines, { self . num_chars : d } characters" )
return True
@@ -105,7 +104,7 @@
Source code for pymatgen.db.builders.examples.file_builders Quick search
diff --git a/docs/_modules/pymatgen/db/builders/examples/maxvalue_builder.html b/docs/_modules/pymatgen/db/builders/examples/maxvalue_builder.html
index 353762b..6ace071 100644
--- a/docs/_modules/pymatgen/db/builders/examples/maxvalue_builder.html
+++ b/docs/_modules/pymatgen/db/builders/examples/maxvalue_builder.html
@@ -5,7 +5,7 @@
-
pymatgen.db.builders.examples.maxvalue_builder — pymatgen-db 2021.5.28 documentation
+
pymatgen.db.builders.examples.maxvalue_builder — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@
Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.examples.maxvalue_builder
@@ -126,7 +126,7 @@
Source code for pymatgen.db.builders.examples.maxvalue_builder Quick search
diff --git a/docs/_modules/pymatgen/db/builders/incr.html b/docs/_modules/pymatgen/db/builders/incr.html
index 3c6e974..f064371 100644
--- a/docs/_modules/pymatgen/db/builders/incr.html
+++ b/docs/_modules/pymatgen/db/builders/incr.html
@@ -5,7 +5,7 @@
-
pymatgen.db.builders.incr — pymatgen-db 2021.5.28 documentation
+
pymatgen.db.builders.incr — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@
Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.incr
@@ -187,9 +187,7 @@
Source code for pymatgen.db.builders.incr
"""
self . _collection_name = value
self . _mongo_coll = self . db [ value ]
- self . collection = TrackedCollection (
- self . _mongo_coll , operation = self . _t_op , field = self . _t_field
- )
+ self . collection = TrackedCollection ( self . _mongo_coll , operation = self . _t_op , field = self . _t_field )
[docs] def set_mark ( self ):
"""See :meth:`TrackingInterface.set_mark`"""
@@ -230,7 +228,7 @@
Source code for pymatgen.db.builders.incr
return getattr ( self . _coll , item )
def __str__ ( self ):
- return "Tracked collection ( {} )" . format ( self . _coll )
+ return f "Tracked collection ( { self . _coll } )"
[docs] def tracked_find ( self , * args , ** kwargs ):
"""Replacement for regular ``find()``."""
@@ -250,11 +248,7 @@
Source code for pymatgen.db.builders.incr
# update filter with tracker query
filt . update ( self . _mark . query )
# delegate to "real" find()
- _log . info (
- "tracked_find.end, call: {} .find(args= {} kwargs= {} )" . format (
- self . _coll . name , args , kwargs
- )
- )
+ _log . info ( f "tracked_find.end, call: { self . _coll . name } .find(args= { args } kwargs= { kwargs } )" )
return self . _coll_find ( * args , ** kwargs )
[docs] def set_mark ( self ):
@@ -318,11 +312,7 @@
Source code for pymatgen.db.builders.incr
if rec is None :
self . _pos = self . _empty_pos ()
elif not self . _fld in rec :
- _log . error (
- "Tracking field not found. field= {} collection= {} " . format (
- self . _fld , self . _c . name
- )
- )
+ _log . error ( f "Tracking field not found. field= { self . _fld } collection= { self . _c . name } " )
_log . warn ( "Continuing without tracking" )
self . _pos = self . _empty_pos ()
else :
@@ -435,10 +425,10 @@ Source code for pymatgen.db.builders.incr
# Make a 'filter' to find/update existing record, which uses
# the field name and operation (but not the position).
filt = { k : obj [ k ] for k in ( mark . FLD_FLD , mark . FLD_OP )}
- _log . debug ( "save: upsert-spec= {} upsert-obj= {} " . format ( filt , obj ))
+ _log . debug ( f "save: upsert-spec= { filt } upsert-obj= { obj } " )
self . _track . update ( filt , obj , upsert = True )
except pymongo . errors . PyMongoError as err :
- raise DBError ( " {} " . format ( err ))
+ raise DBError ( f " { err } " )
[docs] def retrieve ( self , operation , field = None ):
"""Retrieve a position in this collection.
@@ -490,7 +480,7 @@
Source code for pymatgen.db.builders.incr
Quick search
diff --git a/docs/_modules/pymatgen/db/builders/schema.html b/docs/_modules/pymatgen/db/builders/schema.html
index 3751938..20542c9 100644
--- a/docs/_modules/pymatgen/db/builders/schema.html
+++ b/docs/_modules/pymatgen/db/builders/schema.html
@@ -5,7 +5,7 @@
- pymatgen.db.builders.schema — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.builders.schema — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.schema
@@ -77,7 +77,7 @@
Source code for pymatgen.db.builders.schema
# Regex for values
# Note that the special prefix/suffix is optional
-VALUE_RE = re . compile ( "(?: {spec} )?([a-zA-Z]+)(?: {spec} )?\s*(.*)" . format ( spec = SPECIAL ))
+VALUE_RE = re . compile ( r "(?: {spec} )?([a-zA-Z]+)(?: {spec} )?\s*(.*)" . format ( spec = SPECIAL ))
# Global obj with all collected schemas
schemata = {}
@@ -91,7 +91,7 @@ Source code for pymatgen.db.builders.schema
[docs] class SchemaTypeError ( SchemaError ):
def __init__ ( self , typename ):
-
SchemaError . __init__ ( self , "bad type ( {} )" . format ( typename ))
+ SchemaError . __init__ ( self , f "bad type ( { typename } )" )
[docs] class SchemaPathError ( SchemaError ):
@@ -119,11 +119,11 @@
Source code for pymatgen.db.builders.schema
raise SchemaPathError ()
filepat = "*." + ext if ext else "*"
for f in glob . glob ( os . path . join ( path , filepat )):
- with open ( f , "r" ) as fp :
+ with open ( f ) as fp :
try :
schema = json . load ( fp )
except ValueError :
- raise SchemaParseError ( "error parsing ' {} '" . format ( f ))
+ raise SchemaParseError ( f "error parsing ' { f } '" )
name = os . path . splitext ( os . path . basename ( f ))[ 0 ]
schemata [ name ] = Schema ( schema )
@@ -148,7 +148,7 @@
Source code for pymatgen.db.builders.schema
:raise: IOError if file cannot be opened or read, ValueError if
file is not valid JSON or JSON is not a valid schema.
"""
- fp = open ( file_or_fp , "r" ) if isinstance ( file_or_fp , str ) else file_or_fp
+ fp = open ( file_or_fp ) if isinstance ( file_or_fp , str ) else file_or_fp
obj = json . load ( fp )
schema = Schema ( obj )
return schema
@@ -203,9 +203,7 @@
Source code for pymatgen.db.builders.schema
[docs] def validate ( self , doc , path = "(root)" ):
t = self . _whatis ( doc )
if t != self . _type :
-
return self . _vresult (
-
path , "type mismatch: {} != {} " , self . _typestr ( t ), self
-
)
+
return self . _vresult ( path , "type mismatch: {} != {} " , self . _typestr ( t ), self )
if t == self . IS_LIST :
if len ( doc ) == 0 :
return None
@@ -213,13 +211,9 @@
Source code for pymatgen.db.builders.schema
elif t == self . IS_DICT :
# fail if document is missing any required keys
dkeys = set ( doc . keys ())
- skeys = set (
- filter ( lambda k : not self . _schema [ k ] . is_optional , self . _schema . keys ())
- )
+ skeys = set ( filter ( lambda k : not self . _schema [ k ] . is_optional , self . _schema . keys ()))
if skeys - dkeys :
- return self . _vresult (
- path , "missing keys: ( {} )" . format ( ", " . join ( skeys - dkeys ))
- )
+ return self . _vresult ( path , "missing keys: ( {} )" . format ( ", " . join ( skeys - dkeys )))
# check each item in document
for k , v in doc . items ():
if k in self . _schema :
@@ -231,9 +225,7 @@ Source code for pymatgen.db.builders.schema
# return self._vresult(path, "missing key: {}", k)
else :
if not self . _schema . check ( doc ):
- return self . _vresult (
- path , "bad value ' {} ' for type {} " , doc , self . _schema
- )
+ return self . _vresult ( path , "bad value ' {} ' for type {} " , doc , self . _schema )
[docs] def json_schema ( self , ** add_keys ):
"""Convert our compact schema representation to the standard, but more verbose,
@@ -287,7 +279,7 @@
Source code for pymatgen.db.builders.schema
meta_info = ""
if self . meta and "desc" in self . meta :
meta_info = '=" {} "' . format ( self . meta [ "desc" ])
- return " {}{} : " . format ( path , meta_info ) + fmt . format ( * args )
+ return f " { path }{ meta_info } : " + fmt . format ( * args )
def _parse ( self , value ):
t = self . _type = self . _whatis ( value )
@@ -317,9 +309,7 @@ Source code for pymatgen.db.builders.schema
optional = True
vinfo = VALUE_RE . match ( value )
if not vinfo :
- raise ValueError (
- "bad type format, must be __<type>__ got {} " . format ( value )
- )
+ raise ValueError ( f "bad type format, must be __<type>__ got { value } " )
dtype , meta = vinfo . groups ()
return Scalar ( dtype , optional = optional , meta = meta )
@@ -337,7 +327,7 @@ Source code for pymatgen.db.builders.schema
return self . _typestr ( self . _type )
def __repr__ ( self ):
- return "document:: {} " . format ( self )
+ return f "document:: { self } "
def _is_datetime ( d ):
@@ -388,7 +378,7 @@ Source code for pymatgen.db.builders.schema
return self . _type
def __repr__ ( self ):
- return "scalar:: {} " . format ( self )
+ return f "scalar:: { self } "
@@ -407,7 +397,7 @@
Source code for pymatgen.db.builders.schema
Quick search
diff --git a/docs/_modules/pymatgen/db/builders/util.html b/docs/_modules/pymatgen/db/builders/util.html
index d6d1a61..2e73cd9 100644
--- a/docs/_modules/pymatgen/db/builders/util.html
+++ b/docs/_modules/pymatgen/db/builders/util.html
@@ -5,7 +5,7 @@
- pymatgen.db.builders.util — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.builders.util — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.builders.util
@@ -111,8 +111,8 @@
Source code for pymatgen.db.builders.util
:raise: IOError, if file is not found or not accessible
"""
d = get_schema_dir ( db_version = db_version )
- schemafile = " {} . {} .json" . format ( db , collection )
- f = open ( os . path . join ( d , schemafile ), "r" )
+ schemafile = f " { db } . { collection } .json"
+ f = open ( os . path . join ( d , schemafile ))
return f
@@ -144,7 +144,7 @@
Source code for pymatgen.db.builders.util
Quick search
diff --git a/docs/_modules/pymatgen/db/creator.html b/docs/_modules/pymatgen/db/creator.html
index 6449ab2..8fa0410 100644
--- a/docs/_modules/pymatgen/db/creator.html
+++ b/docs/_modules/pymatgen/db/creator.html
@@ -5,7 +5,7 @@
- pymatgen.db.creator — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.creator — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.creator
@@ -225,7 +225,7 @@
Source code for pymatgen.db.creator
db = conn [ self . database ]
if self . user :
db . authenticate ( self . user , self . password )
- if db . counter . find ({ "_id" : "taskid" }) . count () == 0 :
+ if db . counter . count_documents ({ "_id" : "taskid" }) == 0 :
db . counter . insert_one ({ "_id" : "taskid" , "c" : 1 })
[docs] def assimilate ( self , path ):
@@ -252,7 +252,7 @@
Source code for pymatgen.db.creator
[docs] def calculate_stability ( self , d ):
m = MPRester ( self . mapi_key )
functional = d [ "pseudo_potential" ][ "functional" ]
-
syms = [ " {} {} " . format ( functional , l ) for l in d [ "pseudo_potential" ][ "labels" ]]
+
syms = [ f " { functional } { l } " for l in d [ "pseudo_potential" ][ "labels" ]]
entry = ComputedEntry (
Composition ( d [ "unit_cell_formula" ]),
d [ "output" ][ "final_energy" ],
@@ -266,7 +266,7 @@
Source code for pymatgen.db.creator
"""
Get the entire task doc for a path, including any post-processing.
"""
- logger . info ( "Getting task doc for base dir : {} " . format ( path ))
+ logger . info ( f "Getting task doc for base dir : { path } " )
files = os . listdir ( path )
vasprun_files = OrderedDict ()
if "STOPCAR" in files :
@@ -279,7 +279,7 @@ Source code for pymatgen.db.creator
vasprun_files [ r ] = os . path . join ( r , f )
else : # try extension schema
for f in files :
- if fnmatch ( f , "vasprun.xml. {} *" . format ( r )):
+ if fnmatch ( f , f "vasprun.xml. { r } *" ):
vasprun_files [ r ] = f
if len ( vasprun_files ) == 0 :
for f in files : # get any vasprun from the folder
@@ -291,9 +291,7 @@ Source code for pymatgen.db.creator
if not d :
d = self . process_killed_run ( path )
self . post_process ( path , d )
- elif (
- not ( path . endswith ( "relax1" ) or path . endswith ( "relax2" ))
- ) and contains_vasp_input ( path ):
+ elif ( not ( path . endswith ( "relax1" ) or path . endswith ( "relax2" ))) and contains_vasp_input ( path ):
# If not Materials Project style, process as a killed run.
logger . warning ( path + " contains killed run" )
d = self . process_killed_run ( path )
@@ -324,9 +322,7 @@ Source code for pymatgen.db.creator
if "dos" in calc :
dos = json . dumps ( calc [ "dos" ], cls = MontyEncoder )
if self . compress_dos :
- dos = zlib . compress (
- dos . encode ( "utf-8" ), self . compress_dos
- )
+ dos = zlib . compress ( dos . encode ( "utf-8" ), self . compress_dos )
calc [ "dos_compression" ] = "zlib"
fs = gridfs . GridFS ( db , "dos_fs" )
dosid = fs . put ( dos )
@@ -336,22 +332,12 @@ Source code for pymatgen.db.creator
d [ "last_updated" ] = datetime . datetime . today ()
if result is None :
if ( "task_id" not in d ) or ( not d [ "task_id" ]):
- result = db . counter . find_one_and_update (
- filter = { "_id" : "taskid" }, update = { "$inc" : { "c" : 1 }}
- )
+ result = db . counter . find_one_and_update ( filter = { "_id" : "taskid" }, update = { "$inc" : { "c" : 1 }})
d [ "task_id" ] = result [ "c" ]
- logger . info (
- "Inserting {} with taskid = {} " . format (
- d [ "dir_name" ], d [ "task_id" ]
- )
- )
+ logger . info ( "Inserting {} with taskid = {} " . format ( d [ "dir_name" ], d [ "task_id" ]))
elif self . update_duplicates :
d [ "task_id" ] = result [ "task_id" ]
- logger . info (
- "Updating {} with taskid = {} " . format (
- d [ "dir_name" ], d [ "task_id" ]
- )
- )
+ logger . info ( "Updating {} with taskid = {} " . format ( d [ "dir_name" ], d [ "task_id" ]))
coll . update_one ({ "dir_name" : d [ "dir_name" ]}, { "$set" : d }, upsert = True )
return d [ "task_id" ]
@@ -359,11 +345,7 @@ Source code for pymatgen.db.creator
logger . info ( "Skipping duplicate {} " . format ( d [ "dir_name" ]))
else :
d [ "task_id" ] = 0
- logger . info (
- "Simulated insert into database for {} with task_id {} " . format (
- d [ "dir_name" ], d [ "task_id" ]
- )
- )
+ logger . info ( "Simulated insert into database for {} with task_id {} " . format ( d [ "dir_name" ], d [ "task_id" ]))
return d
[docs] def post_process ( self , dir_name , d ):
@@ -378,7 +360,7 @@
Source code for pymatgen.db.creator
d:
Current doc generated.
"""
- logger . info ( "Post-processing dir: {} " . format ( dir_name ))
+ logger . info ( f "Post-processing dir: { dir_name } " )
fullpath = os . path . abspath ( dir_name )
@@ -393,7 +375,7 @@ Source code for pymatgen.db.creator
with zopen ( filenames [ 0 ], "rt" ) as f :
transformations = json . load ( f )
try :
- m = re . match ( "(\d+)-ICSD" , transformations [ "history" ][ 0 ][ "source" ])
+ m = re . match ( r "(\d+)-ICSD" , transformations [ "history" ][ 0 ][ "source" ])
if m :
d [ "icsd_id" ] = int ( m . group ( 1 ))
except Exception as ex :
@@ -438,7 +420,7 @@ Source code for pymatgen.db.creator
d [ "calculations" ][ i ][ "output" ][ "outcar" ] = outcar . as_dict ()
run_stats [ taskname ] = outcar . run_stats
except :
- logger . error ( "Bad OUTCAR for {} ." . format ( fullpath ))
+ logger . error ( f "Bad OUTCAR for { fullpath } ." )
try :
overall_run_stats = {}
@@ -448,10 +430,10 @@ Source code for pymatgen.db.creator
"System time (sec)" ,
"Elapsed time (sec)" ,
]:
- overall_run_stats [ key ] = sum ([ v [ key ] for v in run_stats . values ()])
+ overall_run_stats [ key ] = sum ( v [ key ] for v in run_stats . values ())
run_stats [ "overall" ] = overall_run_stats
except :
- logger . error ( "Bad run stats for {} ." . format ( fullpath ))
+ logger . error ( f "Bad run stats for { fullpath } ." )
d [ "run_stats" ] = run_stats
@@ -495,17 +477,13 @@ Source code for pymatgen.db.creator
d [ "run_type" ] = "GGA"
except Exception as ex :
print ( str ( ex ))
- logger . error (
- "Unable to parse INCAR for killed run {} ." . format ( dir_name )
- )
+ logger . error ( f "Unable to parse INCAR for killed run { dir_name } ." )
elif fnmatch ( f , "KPOINTS*" ):
try :
kpoints = Kpoints . from_file ( filename )
d [ "kpoints" ] = kpoints . as_dict ()
except :
- logger . error (
- "Unable to parse KPOINTS for killed run {} ." . format ( dir_name )
- )
+ logger . error ( f "Unable to parse KPOINTS for killed run { dir_name } ." )
elif fnmatch ( f , "POSCAR*" ):
try :
s = Poscar . from_file ( filename ) . structure
@@ -525,9 +503,7 @@ Source code for pymatgen.db.creator
)
d [ "poscar" ] = s . as_dict ()
except :
- logger . error (
- "Unable to parse POSCAR for killed run {} ." . format ( dir_name )
- )
+ logger . error ( f "Unable to parse POSCAR for killed run { dir_name } ." )
elif fnmatch ( f , "POTCAR*" ):
try :
potcar = Potcar . from_file ( filename )
@@ -537,27 +513,18 @@ Source code for pymatgen.db.creator
"labels" : potcar . symbols ,
}
except :
- logger . error (
- "Unable to parse POTCAR for killed run in {} ." . format ( dir_name )
- )
+ logger . error ( f "Unable to parse POTCAR for killed run in { dir_name } ." )
elif fnmatch ( f , "OSZICAR" ):
try :
d [ "oszicar" ][ "root" ] = Oszicar ( os . path . join ( dir_name , f )) . as_dict ()
except :
- logger . error (
- "Unable to parse OSZICAR for killed run in {} ." . format ( dir_name )
- )
- elif re . match ( "relax\d" , f ):
+ logger . error ( f "Unable to parse OSZICAR for killed run in { dir_name } ." )
+ elif re . match ( r "relax\d" , f ):
if os . path . exists ( os . path . join ( dir_name , f , "OSZICAR" )):
try :
- d [ "oszicar" ][ f ] = Oszicar (
- os . path . join ( dir_name , f , "OSZICAR" )
- ) . as_dict ()
+ d [ "oszicar" ][ f ] = Oszicar ( os . path . join ( dir_name , f , "OSZICAR" )) . as_dict ()
except :
- logger . error (
- "Unable to parse OSZICAR for killed "
- "run in {} ." . format ( dir_name )
- )
+ logger . error ( "Unable to parse OSZICAR for killed " "run in {} ." . format ( dir_name ))
return d
[docs] def process_vasprun ( self , dir_name , taskname , filename ):
@@ -565,27 +532,21 @@
Source code for pymatgen.db.creator
Process a vasprun.xml file.
"""
vasprun_file = os . path . join ( dir_name , filename )
- if self . parse_projected_eigen and (
- self . parse_projected_eigen != "final" or taskname == self . runs [ - 1 ]
- ):
+ if self . parse_projected_eigen and ( self . parse_projected_eigen != "final" or taskname == self . runs [ - 1 ]):
parse_projected_eigen = True
else :
parse_projected_eigen = False
r = Vasprun ( vasprun_file , parse_projected_eigen = parse_projected_eigen )
d = r . as_dict ()
d [ "dir_name" ] = os . path . abspath ( dir_name )
- d [ "completed_at" ] = str (
- datetime . datetime . fromtimestamp ( os . path . getmtime ( vasprun_file ))
- )
+ d [ "completed_at" ] = str ( datetime . datetime . fromtimestamp ( os . path . getmtime ( vasprun_file )))
d [ "cif" ] = str ( CifWriter ( r . final_structure ))
d [ "density" ] = r . final_structure . density
if self . parse_dos and ( self . parse_dos != "final" or taskname == self . runs [ - 1 ]):
try :
d [ "dos" ] = r . complete_dos . as_dict ()
except Exception :
- logger . warning (
- "No valid dos data exist in {} . \n Skipping dos" . format ( dir_name )
- )
+ logger . warning ( f "No valid dos data exist in { dir_name } . \n Skipping dos" )
if taskname == "relax1" or taskname == "relax2" :
d [ "task" ] = { "type" : "aflow" , "name" : taskname }
else :
@@ -607,8 +568,7 @@ Source code for pymatgen.db.creator
d [ "dir_name" ] = fullpath
d [ "schema_version" ] = VaspToDbTaskDrone . __version__
d [ "calculations" ] = [
- self . process_vasprun ( dir_name , taskname , filename )
- for taskname , filename in vasprun_files . items ()
+ self . process_vasprun ( dir_name , taskname , filename ) for taskname , filename in vasprun_files . items ()
]
d1 = d [ "calculations" ][ 0 ]
d2 = d [ "calculations" ][ - 1 ]
@@ -642,9 +602,7 @@ Source code for pymatgen.db.creator
"xc_override" : xc ,
}
vals = sorted ( d2 [ "reduced_cell_formula" ] . values ())
- d [ "anonymous_formula" ] = {
- string . ascii_uppercase [ i ]: float ( vals [ i ]) for i in range ( len ( vals ))
- }
+ d [ "anonymous_formula" ] = { string . ascii_uppercase [ i ]: float ( vals [ i ]) for i in range ( len ( vals ))}
d [ "output" ] = {
"crystal" : d2 [ "output" ][ "crystal" ],
"final_energy" : d2 [ "output" ][ "final_energy" ],
@@ -659,13 +617,8 @@ Source code for pymatgen.db.creator
"pot_type" : pot_type . lower (),
"labels" : d2 [ "input" ][ "potcar" ],
}
- if (
- len ( d [ "calculations" ]) == len ( self . runs )
- or list ( vasprun_files . keys ())[ 0 ] != "relax1"
- ):
- d [ "state" ] = (
- "successful" if d2 [ "has_vasp_completed" ] else "unsuccessful"
- )
+ if len ( d [ "calculations" ]) == len ( self . runs ) or list ( vasprun_files . keys ())[ 0 ] != "relax1" :
+ d [ "state" ] = "successful" if d2 [ "has_vasp_completed" ] else "unsuccessful"
else :
d [ "state" ] = "stopped"
d [ "analysis" ] = get_basic_analysis_and_error_checks ( d )
@@ -686,9 +639,7 @@ Source code for pymatgen.db.creator
import traceback
print ( traceback . format_exc ())
- logger . error (
- "Error in " + os . path . abspath ( dir_name ) + ". \n " + traceback . format_exc ()
- )
+ logger . error ( "Error in " + os . path . abspath ( dir_name ) + ". \n " + traceback . format_exc ())
return None
@@ -744,9 +695,7 @@ Source code for pymatgen.db.creator
-[docs] def get_basic_analysis_and_error_checks (
-
d , max_force_threshold = 0.5 , volume_change_threshold = 0.2
-
):
+
[docs] def get_basic_analysis_and_error_checks ( d , max_force_threshold = 0.5 , volume_change_threshold = 0.2 ):
initial_vol = d [ "input" ][ "crystal" ][ "lattice" ][ "volume" ]
final_vol = d [ "output" ][ "crystal" ][ "lattice" ][ "volume" ]
@@ -763,34 +712,24 @@
Source code for pymatgen.db.creator
error_msgs = []
if abs ( percent_delta_vol ) > volume_change_threshold :
- warning_msgs . append ( "Volume change > {} %" . format ( volume_change_threshold * 100 ))
+ warning_msgs . append ( f "Volume change > { volume_change_threshold * 100 } %" )
bv_struct = Structure . from_dict ( d [ "output" ][ "crystal" ])
try :
bva = BVAnalyzer ()
bv_struct = bva . get_oxi_state_decorated_structure ( bv_struct )
except ValueError as e :
- logger . error ( "Valence cannot be determined due to {e} ." . format ( e = e ))
+ logger . error ( f "Valence cannot be determined due to { e } ." )
except Exception as ex :
- logger . error ( "BVAnalyzer error {e} ." . format ( e = str ( ex )))
+ logger . error ( f "BVAnalyzer error { str ( ex ) } ." )
max_force = None
- if (
- d [ "state" ] == "successful"
- and d [ "calculations" ][ 0 ][ "input" ][ "parameters" ] . get ( "NSW" , 0 ) > 0
- ):
+ if d [ "state" ] == "successful" and d [ "calculations" ][ 0 ][ "input" ][ "parameters" ] . get ( "NSW" , 0 ) > 0 :
# handle the max force and max force error
- max_force = max (
- [
- np . linalg . norm ( a )
- for a in d [ "calculations" ][ - 1 ][ "output" ][ "ionic_steps" ][ - 1 ][ "forces" ]
- ]
- )
+ max_force = max ( np . linalg . norm ( a ) for a in d [ "calculations" ][ - 1 ][ "output" ][ "ionic_steps" ][ - 1 ][ "forces" ])
if max_force > max_force_threshold :
- error_msgs . append (
- "Final max force exceeds {} eV" . format ( max_force_threshold )
- )
+ error_msgs . append ( f "Final max force exceeds { max_force_threshold } eV" )
d [ "state" ] = "error"
s = Structure . from_dict ( d [ "output" ][ "crystal" ])
@@ -826,9 +765,7 @@ Source code for pymatgen.db.creator
KPOINTS and POTCAR).
"""
for f in [ "INCAR" , "POSCAR" , "POTCAR" , "KPOINTS" ]:
- if not os . path . exists ( os . path . join ( dir_name , f )) and not os . path . exists (
- os . path . join ( dir_name , f + ".orig" )
- ):
+ if not os . path . exists ( os . path . join ( dir_name , f )) and not os . path . exists ( os . path . join ( dir_name , f + ".orig" )):
return False
return True
@@ -876,7 +813,7 @@ Source code for pymatgen.db.creator
hostname = socket . gethostbyaddr ( socket . gethostname ())[ 0 ]
except :
hostname = socket . gethostname ()
- return " {} : {} " . format ( hostname , fullpath )
+ return f " { hostname } : { fullpath } "
@@ -895,7 +832,7 @@
Source code for pymatgen.db.creator
Quick search
diff --git a/docs/_modules/pymatgen/db/dbconfig.html b/docs/_modules/pymatgen/db/dbconfig.html
index 4ab8fd5..99b5021 100644
--- a/docs/_modules/pymatgen/db/dbconfig.html
+++ b/docs/_modules/pymatgen/db/dbconfig.html
@@ -5,7 +5,7 @@
- pymatgen.db.dbconfig — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.dbconfig — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.dbconfig
@@ -67,7 +67,7 @@
Source code for pymatgen.db.dbconfig
__date__ = "4/25/14"
import os
-import yaml
+import ruamel.yaml as yaml
# Constants for keys
HOST_KEY = "host"
@@ -81,7 +81,7 @@ Source code for pymatgen.db.dbconfig
[docs] class ConfigurationFileError ( Exception ):
def __init__ ( self , filename , err ):
-
msg = "reading ' {} ': {} " . format ( filename , err )
+
msg = f "reading ' { filename } ': { err } "
Exception . __init__ ( self , msg )
@@ -193,7 +193,7 @@ Source code for pymatgen.db.dbconfig
"""
settings = yaml . safe_load ( _as_file ( infile ))
if not hasattr ( settings , "keys" ):
- raise ValueError ( "Settings not found in {} " . format ( infile ))
+ raise ValueError ( f "Settings not found in { infile } " )
# Processing of namespaced parameters in .pmgrc.yaml.
processed_settings = {}
@@ -280,7 +280,7 @@ Source code for pymatgen.db.dbconfig
Quick search
diff --git a/docs/_modules/pymatgen/db/dbgroup.html b/docs/_modules/pymatgen/db/dbgroup.html
index 10493a0..28ba9d1 100644
--- a/docs/_modules/pymatgen/db/dbgroup.html
+++ b/docs/_modules/pymatgen/db/dbgroup.html
@@ -5,7 +5,7 @@
- pymatgen.db.dbgroup — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.dbgroup — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.dbgroup
@@ -111,9 +111,9 @@
Source code for pymatgen.db.dbgroup
cfg = dbconfig . DBConfig ( config_file = config )
cs = cfg . settings
if dbconfig . DB_KEY not in cs :
- raise ValueError ( "No database in ' {} '" . format ( config ))
+ raise ValueError ( f "No database in ' { config } '" )
if dbconfig . COLL_KEY in cs :
- name = " {} . {} " . format ( cs [ dbconfig . DB_KEY ], cs [ dbconfig . COLL_KEY ])
+ name = f " { cs [ dbconfig . DB_KEY ] } . { cs [ dbconfig . COLL_KEY ] } "
else :
name = cs [ dbconfig . DB_KEY ]
self . add ( name , cfg )
@@ -223,11 +223,7 @@ Source code for pymatgen.db.dbgroup
for k , v in self . _d . re_get ( name ) . items ():
qe [ k ] = self . _get_qe ( k , v )
if not qe :
- raise KeyError (
- "No configuration found, name=' {} ' full-regex=' {} '" . format (
- orig_name , name
- )
- )
+ raise KeyError ( f "No configuration found, name=' { orig_name } ' full-regex=' { name } '" )
else :
qe = self . _get_qe ( name , self . _d [ name ])
return qe
@@ -329,7 +325,7 @@ Source code for pymatgen.db.dbgroup
Quick search
diff --git a/docs/_modules/pymatgen/db/query_engine.html b/docs/_modules/pymatgen/db/query_engine.html
index b3ac246..2cc0a19 100644
--- a/docs/_modules/pymatgen/db/query_engine.html
+++ b/docs/_modules/pymatgen/db/query_engine.html
@@ -5,7 +5,7 @@
- pymatgen.db.query_engine — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.query_engine — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.query_engine
@@ -69,7 +69,8 @@
Source code for pymatgen.db.query_engine
import os
import gridfs
import zlib
-from collections import OrderedDict , Iterable
+from collections import OrderedDict
+from collections.abc import Iterable
import pymongo
from pymongo import MongoClient
@@ -131,7 +132,7 @@ Source code for pymatgen.db.query_engine
result_post = None ,
connection = None ,
replicaset = None ,
- ** ignore
+ ** ignore ,
):
"""Constructor.
@@ -187,9 +188,7 @@ Source code for pymatgen.db.query_engine
if connection is None :
# can't pass replicaset=None to MongoClient (fails validation)
if self . replicaset :
- self . connection = MongoClient (
- self . host , self . port , replicaset = self . replicaset
- )
+ self . connection = MongoClient ( self . host , self . port , replicaset = self . replicaset )
else :
self . connection = MongoClient ( self . host , self . port )
else :
@@ -198,9 +197,7 @@ Source code for pymatgen.db.query_engine
if user :
self . db . authenticate ( user , password )
self . collection_name = collection
- self . set_aliases_and_defaults (
- aliases_config = aliases_config , default_properties = default_properties
- )
+ self . set_aliases_and_defaults ( aliases_config = aliases_config , default_properties = default_properties )
# Post-processing functions
self . query_post = query_post or []
self . result_post = result_post or []
@@ -260,9 +257,7 @@ Source code for pymatgen.db.query_engine
if default_properties is None :
self . _default_props , self . _default_prop_dict = None , None
else :
- self . _default_props , self . _default_prop_dict = self . _parse_properties (
- default_properties
- )
+ self . _default_props , self . _default_prop_dict = self . _parse_properties ( default_properties )
def __enter__ ( self ):
"""Allows for use with the 'with' context manager"""
@@ -375,7 +370,7 @@ Source code for pymatgen.db.query_engine
for c in self . query ( fields , criteria ):
func = c [ "pseudo_potential.functional" ]
labels = c [ "pseudo_potential.labels" ]
- symbols = [ " {} {} " . format ( func , label ) for label in labels ]
+ symbols = [ f " { func } { label } " for label in labels ]
parameters = {
"run_type" : c [ "run_type" ],
"is_hubbard" : c [ "is_hubbard" ],
@@ -435,7 +430,7 @@ Source code for pymatgen.db.query_engine
comp = Composition ( crit )
crit = comp . as_dict ()
for el , amt in crit . items ():
- parsed_crit [ " {} . {} " . format ( self . aliases [ key ], el )] = amt
+ parsed_crit [ f " { self . aliases [ key ] } . { el } " ] = amt
parsed_crit [ "nelements" ] = len ( crit )
parsed_crit [ "pretty_formula" ] = comp . reduced_formula
elif key in [ "$or" , "$and" ]:
@@ -449,7 +444,7 @@ Source code for pymatgen.db.query_engine
return self . collection . ensure_index ( key , unique = unique )
[docs] def query ( self , properties = None , criteria = None , distinct_key = None , ** kwargs ):
-
"""
+
r """
Convenience method for database access. All properties and criteria
can be specified using simplified names defined in Aliases. You can
use the supported_properties property to get the list of supported
@@ -494,8 +489,8 @@
Source code for pymatgen.db.query_engine
if distinct_key is not None :
cur = cur . distinct ( distinct_key )
return QueryListResults ( prop_dict , cur , postprocess = self . result_post )
- else :
- return QueryResults ( prop_dict , cur , postprocess = self . result_post )
+
+
return QueryResults ( prop_dict , cur , postprocess = self . result_post )
def _parse_properties ( self , properties ):
"""Make list of properties into 2 things:
@@ -551,16 +546,14 @@ Source code for pymatgen.db.query_engine
results = tuple ( self . query ([ field ], args ))
if len ( results ) > 1 :
- raise QueryError (
- "More than one result found for task_id {} !" . format ( task_id )
- )
+ raise QueryError ( f "More than one result found for task_id { task_id } !" )
elif len ( results ) == 0 :
- raise QueryError ( "No structure found for task_id {} !" . format ( task_id ))
+ raise QueryError ( f "No structure found for task_id { task_id } !" )
c = results [ 0 ]
return Structure . from_dict ( c [ field ])
def __repr__ ( self ):
- return "QueryEngine: {} : {} / {} " . format ( self . host , self . port , self . database_name )
+ return f "QueryEngine: { self . host } : { self . port } / { self . database_name } "
[docs] @staticmethod
def from_config ( config_file , use_admin = False ):
@@ -626,9 +619,7 @@
Source code for pymatgen.db.query_engine
for j in range ( len ( ados )):
orb = Orbital ( j )
odos = ados [ str ( orb )]
- all_ados [ orb ] = {
- Spin ( int ( k )): v for k , v in odos [ "densities" ] . items ()
- }
+ all_ados [ orb ] = { Spin ( int ( k )): v for k , v in odos [ "densities" ] . items ()}
pdoss [ structure [ i ]] = all_ados
return CompleteDos ( structure , tdos , pdoss )
return None
@@ -696,7 +687,7 @@ Source code for pymatgen.db.query_engine
def __len__ ( self ):
"""Return length as a `count()` on the MongoDB cursor."""
- return self . _results . count ()
+ return len ( list ( self . _results . clone ()))
def __getitem__ ( self , i ):
return self . _mapped_result ( self . _results [ i ])
@@ -779,7 +770,7 @@ Source code for pymatgen.db.query_engine
Quick search
diff --git a/docs/_modules/pymatgen/db/util.html b/docs/_modules/pymatgen/db/util.html
index 6d64c2c..c5ad6d8 100644
--- a/docs/_modules/pymatgen/db/util.html
+++ b/docs/_modules/pymatgen/db/util.html
@@ -5,7 +5,7 @@
- pymatgen.db.util — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.util — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.util
@@ -111,10 +111,7 @@
Source code for pymatgen.db.util
passwd = d [ "admin_password" ] if admin else d [ "readonly_password" ]
db . authenticate ( user , passwd )
except ( KeyError , TypeError , ValueError ):
- _log . warn (
- "No {admin,readonly}_user/password found in config. file, "
- "accessing DB without authentication"
- )
+ _log . warn ( "No {admin,readonly}_user/password found in config. file, " "accessing DB without authentication" )
return db
@@ -137,8 +134,7 @@
Source code for pymatgen.db.util
for k in x :
yield ( pre + k )
if isinstance ( x [ k ], dict ):
- for nested in _keys ( x [ k ], pre + k + sep ):
- yield nested
+ yield from _keys ( x [ k ], pre + k + sep )
return list ( _keys ( coll . find_one ()))
@@ -153,21 +149,19 @@
Source code for pymatgen.db.util
[docs] def quotable ( v ):
if isinstance ( v , int ) or isinstance ( v , float ):
return str ( v )
-
return "' {} '" . format ( v )
+ return f "' { v } '"
[docs] def csv_dict ( d ):
"""Format dict to a string with comma-separated values."""
if len ( d ) == 0 :
return " {} "
-
return (
-
"{" + ", " . join ([ "' {} ': {} " . format ( k , quotable ( v )) for k , v in d . items ()]) + "}"
-
)
+
return "{" + ", " . join ([ f "' { k } ': { quotable ( v ) } " for k , v in d . items ()]) + "}"
[docs] def kvp_dict ( d ):
"""Format dict to key=value pairs."""
-
return ", " . join ([ " {} = {} " . format ( k , quotable ( v )) for k , v in d . items ()])
+ return ", " . join ([ f " { k } = { quotable ( v ) } " for k , v in d . items ()])
@@ -186,7 +180,7 @@ Source code for pymatgen.db.util
Quick search
diff --git a/docs/_modules/pymatgen/db/vv/diff.html b/docs/_modules/pymatgen/db/vv/diff.html
index b5c1936..0ddd009 100644
--- a/docs/_modules/pymatgen/db/vv/diff.html
+++ b/docs/_modules/pymatgen/db/vv/diff.html
@@ -5,7 +5,7 @@
- pymatgen.db.vv.diff — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.vv.diff — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.vv.diff
@@ -148,9 +148,7 @@
Source code for pymatgen.db.vv.diff
for cfg in c1 , c2 :
settings = util . get_settings ( cfg )
if not normalize_auth ( settings ):
- _log . warn (
- "Config file {} does not have a username/password" . format ( cfg )
- )
+ _log . warn ( f "Config file { cfg } does not have a username/password" )
settings [ "aliases_config" ] = { "aliases" : {}, "defaults" : {}}
engine = QueryEngine ( ** settings )
engines . append ( engine )
@@ -170,12 +168,12 @@ Source code for pymatgen.db.vv.diff
info = {} # per-key information
has_info , has_props = bool ( self . _info ), bool ( self . _all_props )
has_numprops , has_eqprops = bool ( self . _prop_deltas ), bool ( self . _props )
- _log . info ( "query.start query= {} fields= {} " . format ( self . _filter , fields ))
+ _log . info ( f "query.start query= { self . _filter } fields= { fields } " )
t0 = time . time ()
# Main query loop.
for i , coll in enumerate ( engines ):
- _log . debug ( "collection {:d} " . format ( i ))
+ _log . debug ( f "collection { i : d } " )
count , missing_props = 0 , 0
for rec in coll . query ( criteria = self . _filter , properties = fields ):
count += 1
@@ -183,14 +181,10 @@ Source code for pymatgen.db.vv.diff
try :
key = rec [ self . _key_field ]
except KeyError :
- _log . critical (
- "Key ' {} ' not found in record: {} . Abort." . format (
- self . _key_field , rec
- )
- )
+ _log . critical ( f "Key ' { self . _key_field } ' not found in record: { rec } . Abort." )
return {}
if not allow_dup and key in keys [ i ]:
- raise ValueError ( "Duplicate key: {} " . format ( key ))
+ raise ValueError ( f "Duplicate key: { key } " )
keys [ i ] . add ( key )
# Extract numeric properties.
if has_numprops :
@@ -212,7 +206,7 @@ Source code for pymatgen.db.vv.diff
# Extract properties for exact match.
if has_eqprops :
try :
- propval = tuple ([( p , str ( rec [ p ])) for p in self . _props ])
+ propval = tuple (( p , str ( rec [ p ])) for p in self . _props )
except KeyError :
missing_props += 1
# print("@@ missing {} on {}".format(pkey, rec))
@@ -228,19 +222,13 @@ Source code for pymatgen.db.vv.diff
# Stop if we don't have properties on any record at all
if 0 < count == missing_props :
- _log . critical (
- "Missing one or more properties on all {:d} records" . format ( count )
- )
+ _log . critical ( f "Missing one or more properties on all { count : d } records" )
return {}
# ..but only issue a warning for partially missing properties.
elif missing_props > 0 :
- _log . warn (
- "Missing one or more properties for {:d} / {:d} records" . format (
- missing_props , count
- )
- )
+ _log . warn ( f "Missing one or more properties for { missing_props : d } / { count : d } records" )
t1 = time . time ()
- _log . info ( "query.end sec= {:f} " . format ( t1 - t0 ))
+ _log . info ( f "query.end sec= { t1 - t0 : f } " )
# Compute missing and new keys.
if only_values :
@@ -308,10 +296,10 @@ Source code for pymatgen.db.vv.diff
self . CHANGED_MATCH_KEY : self . CHANGED_MATCH_DELTA ,
self . _key_field : key ,
"property" : pkey ,
- self . CHANGED_OLD : " {:f} " . format ( oldval ),
- self . CHANGED_NEW : " {:f} " . format ( newval ),
+ self . CHANGED_OLD : f " { oldval : f } " ,
+ self . CHANGED_NEW : f " { newval : f } " ,
"rule" : self . _prop_deltas [ pkey ],
- self . CHANGED_DELTA : " {:f} " . format ( newval - oldval ),
+ self . CHANGED_DELTA : f " { newval - oldval : f } " ,
}
changed . append ( _up ( change , info [ key ]) if info else change )
# Exact property comparison.
@@ -342,11 +330,11 @@ Source code for pymatgen.db.vv.diff
...% Instead of (v2 - v1), use 100*(v2 - v1)/v1
"""
- _num = "\d+(\.\d+)?"
+ _num = r "\d+(\.\d+)?"
_expr = re . compile (
"(?:"
- "\+(?P<X> {n} )?-(?P<Y> {n} )?|" # both + and -
- "\+(?P<X2> {n} )?|" # only +
+ r "\+(?P<X> {n} )?-(?P<Y> {n} )?|" # both + and -
+ r "\+(?P<X2> {n} )?|" # only +
"-(?P<Y2> {n} )?" # only -
")"
"(?P<eq>=)?(?P<pct>%)?" . format ( n = _num )
@@ -362,10 +350,10 @@ Source code for pymatgen.db.vv.diff
# Match expression.
m = self . _expr . match ( s )
if m is None :
- raise ValueError ( "Bad syntax for delta ' {} '" . format ( s ))
+ raise ValueError ( f "Bad syntax for delta ' { s } '" )
if m . span ()[ 1 ] != len ( s ):
p = m . span ()[ 1 ]
- raise ValueError ( "Junk at end of delta ' {} ': {} " . format ( s , s [ p :]))
+ raise ValueError ( f "Junk at end of delta ' { s } ': { s [ p :] } " )
# Save a copy of orig.
self . _orig_expr = s
@@ -379,12 +367,12 @@ Source code for pymatgen.db.vv.diff
# Set parsed values.
d = m . groupdict ()
# print("@@ expr :: {}".format(d))
- if all (( d [ k ] is None for k in ( "X" , "Y" , "X2" , "Y2" ))):
+ if all ( d [ k ] is None for k in ( "X" , "Y" , "X2" , "Y2" )):
# Change in sign only
self . _sign = True
self . _eq = d [ "eq" ] is not None
elif d [ "X" ] is not None and d [ "Y" ] is None :
- raise ValueError ( "Missing value for negative delta ' {} '" . format ( s ))
+ raise ValueError ( f "Missing value for negative delta ' { s } '" )
else :
if d [ "X2" ] is not None :
# Positive only
@@ -492,7 +480,7 @@ Source code for pymatgen.db.vv.diff
Quick search
diff --git a/docs/_modules/pymatgen/db/vv/report.html b/docs/_modules/pymatgen/db/vv/report.html
index f0c3e26..b930273 100644
--- a/docs/_modules/pymatgen/db/vv/report.html
+++ b/docs/_modules/pymatgen/db/vv/report.html
@@ -5,7 +5,7 @@
- pymatgen.db.vv.report — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.vv.report — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.vv.report
@@ -164,9 +164,7 @@
Source code for pymatgen.db.vv.report
[docs] def add ( self , values ):
if len ( values ) != self . _width :
-
raise ValueError (
-
"expected {:d} values, got {:d} " . format ( self . _width , len ( values ))
-
)
+
raise ValueError ( f "expected { self . _width : d } values, got { len ( values ) : d } " )
self . _rows . append ( values )
for i , v in enumerate ( values ):
n = len ( str ( v ))
@@ -183,10 +181,10 @@
Source code for pymatgen.db.vv.report
try :
colnum = self . _colnames . index ( name )
except ValueError :
- raise ValueError ( "column {} not in {} " . format ( name , self . _colnames ))
+ raise ValueError ( f "column { name } not in { self . _colnames } " )
else :
if index < 0 or index >= self . _width :
- raise ValueError ( "index out of range 0.. {:d} " . format ( self . _width - 1 ))
+ raise ValueError ( f "index out of range 0.. { self . _width - 1 : d } " )
colnum = index
self . _rows . sort ( key = itemgetter ( colnum ))
@@ -195,9 +193,7 @@
Source code for pymatgen.db.vv.report
@property
def values ( self ):
- return [
- { self . _colnames [ i ]: r [ i ] for i in range ( self . _width )} for r in self . _rows
- ]
+ return [{ self . _colnames [ i ]: r [ i ] for i in range ( self . _width )} for r in self . _rows ]
@property
def column_names ( self ):
@@ -266,7 +262,7 @@ Source code for pymatgen.db.vv.report
text = []
text . append ( "<!DOCTYPE html>" )
text . append ( "<html>" )
- text . append ( "<title> {} </title>" . format ( report . header . title ))
+ text . append ( f "<title> { report . header . title } </title>" )
text . append ( "<head>" )
if self . _css :
text . append ( "<style>" )
@@ -274,30 +270,30 @@ Source code for pymatgen.db.vv.report
text . append ( "</style>" )
text . append ( "</head>" )
text . append ( "<body>" )
- text . append ( "<h1> {} </h1>" . format ( report . header . title ))
+ text . append ( f "<h1> { report . header . title } </h1>" )
text . append ( '<dl class="rptmeta">' )
for key , value in report . header :
- text . append ( "<dt> {} </dt>" . format ( key ))
- text . append ( "<dd> {} </dd>" . format ( value ))
+ text . append ( f "<dt> { key } </dt>" )
+ text . append ( f "<dd> { value } </dd>" )
text . append ( "</dl>" )
for section in report :
- text . append ( "<h2> {} </h2>" . format ( section . header . title ))
+ text . append ( f "<h2> { section . header . title } </h2>" )
text . append ( '<dl class="sectmeta">' )
for key , value in section . header :
- text . append ( "<dt> {} </dt>" . format ( key ))
- text . append ( "<dd> {} </dd>" . format ( value ))
+ text . append ( f "<dt> { key } </dt>" )
+ text . append ( f "<dd> { value } </dd>" )
text . append ( "</dl>" )
for cond_section in section :
- text . append ( "<h3> {} </h3>" . format ( cond_section . header . title ))
+ text . append ( f "<h3> { cond_section . header . title } </h3>" )
text . append ( '<dl class="subsectmeta">' )
for key , value in cond_section . header :
- text . append ( "<dt> {} </dt>" . format ( key ))
- text . append ( "<dd> {} </dd>" . format ( value ))
+ text . append ( f "<dt> { key } </dt>" )
+ text . append ( f "<dd> { value } </dd>" )
text . append ( "</dl>" )
text . append ( "<table>" )
text . append ( "<tr>" )
for name in cond_section . body . column_names :
- text . append ( "<th> {} </th>" . format ( name ))
+ text . append ( f "<th> { name } </th>" )
text . append ( "</tr>" )
prev_key , i = None , 0
for row in cond_section . body :
@@ -309,9 +305,9 @@ Source code for pymatgen.db.vv.report
prev_key = key
i += 1
rclass = ( "even" , "odd" )[ i % 2 ]
- text . append ( '<tr class=" {} ">' . format ( rclass ))
+ text . append ( f '<tr class=" { rclass } ">' )
for value in row :
- text . append ( "<td> {} </td>" . format ( value ))
+ text . append ( f "<td> { value } </td>" )
text . append ( "</tr>" )
text . append ( "</table>" )
text . append ( "</body>" )
@@ -336,10 +332,7 @@ Source code for pymatgen.db.vv.report
dict (
title = s . header . title ,
info = s . header ,
- conditions = [
- dict ( title = cs . header . title , info = cs . header , violations = cs . body )
- for cs in s
- ],
+ conditions = [ dict ( title = cs . header . title , info = cs . header , violations = cs . body ) for cs in s ],
)
for s in report
],
@@ -363,12 +356,10 @@ Source code for pymatgen.db.vv.report
self . _idcol = id_column
def _mapdump ( self , d ):
- return ", " . join ((( " {} = {} " . format ( k , v ) for k , v in d . items ())))
+ return ", " . join (( f " { k } = { v } " for k , v in d . items ()))
def _fixed_width ( self , values , widths ):
- s = "" . join (
- [ "{{: {:d} s}}" . format ( w + 1 ) . format ( str ( v )) for w , v in zip ( widths , values )]
- )
+ s = "" . join ([ f " {{ : { w + 1 : d } s }} " . format ( str ( v )) for w , v in zip ( widths , values )])
return s
[docs] def format ( self , report ):
@@ -389,12 +380,12 @@
Source code for pymatgen.db.vv.report
return
infodict = info . as_dict ()
if infodict :
- text = "Info: {} " . format ( self . _mapdump ( infodict ))
+ text = f "Info: { self . _mapdump ( infodict ) } "
lines . append ( text )
def _append_heading ( self , lines , level , title ):
hashes = "#" * level
- text = " \n {} {} {} \n " . format ( hashes , title , hashes )
+ text = f " \n { hashes } { title } { hashes } \n "
lines . append ( text )
def _append_violations ( self , lines , data ):
@@ -415,7 +406,7 @@ Source code for pymatgen.db.vv.report
subject = "Report" ,
server = "localhost" ,
port = None ,
- ** kwargs
+ ** kwargs ,
):
"""Send reports as email.
@@ -454,7 +445,7 @@ Source code for pymatgen.db.vv.report
elif sub_fmt . lower () == "html" :
msg = MIMEText ( text , "html" )
else :
- raise ValueError ( "Unknown message format: {} " . format ( fmt ))
+ raise ValueError ( f "Unknown message format: { fmt } " )
msg [ "Subject" ] = self . _subject
msg [ "From" ] = self . _sender
msg [ "To" ] = ", " . join ( self . _recipients )
@@ -462,25 +453,19 @@ Source code for pymatgen.db.vv.report
conn_kwargs = dict ( host = self . _server )
else :
conn_kwargs = dict ( host = self . _server , port = self . _port )
- self . _log . info ( "connect to email server {} " . format ( conn_kwargs ))
+ self . _log . info ( f "connect to email server { conn_kwargs } " )
try :
s = smtplib . SMTP ( ** conn_kwargs )
# s.set_debuglevel(2)
refused = s . sendmail ( self . _sender , self . _recipients , msg . as_string ())
if refused :
- self . _log . warn (
- "Email to {:d} recipients was refused" . format ( len ( refused ))
- )
+ self . _log . warn ( f "Email to { len ( refused ) : d } recipients was refused" )
for person , ( code , msg ) in refused . items ():
- self . _log (
- "Email to {p} was refused ( {c} ): {m} " . format (
- p = person , c = code , m = msg
- )
- )
+ self . _log ( f "Email to { person } was refused ( { code } ): { msg } " )
s . quit ()
n_recip = len ( self . _recipients )
except Exception as err :
- self . _log . error ( "connection to SMTP server failed: {} " . format ( err ))
+ self . _log . error ( f "connection to SMTP server failed: { err } " )
n_recip = 0
return n_recip
@@ -531,7 +516,7 @@ Source code for pymatgen.db.vv.report
if key not in maxwid :
maxwid [ key ] = [ len ( k ) for k in key ]
for i , k in enumerate ( key ):
- strlen = len ( " {} " . format ( r [ k ]))
+ strlen = len ( f " { r [ k ] } " )
maxwid [ key ][ i ] = max ( maxwid [ key ][ i ], strlen )
return keyset , maxwid
@@ -540,9 +525,7 @@ Source code for pymatgen.db.vv.report
columns = list ( columns ) # might be a tuple
fixed_cols = [ self . key ]
if section . lower () == "different" :
- fixed_cols . extend (
- [ Differ . CHANGED_MATCH_KEY , Differ . CHANGED_OLD , Differ . CHANGED_NEW ]
- )
+ fixed_cols . extend ([ Differ . CHANGED_MATCH_KEY , Differ . CHANGED_OLD , Differ . CHANGED_NEW ])
map ( columns . remove , fixed_cols )
columns . sort ()
return fixed_cols + columns
@@ -669,7 +652,7 @@ Source code for pymatgen.db.vv.report
:rtype: str
"""
css = " \n " . join ( self . css )
- content = " {}{} " . format ( self . _header (), self . _body ( result ))
+ content = f " { self . _header () }{ self . _body ( result ) } "
if self . _email :
text = """<!DOCTYPE html>
<html>
@@ -690,7 +673,7 @@ Source code for pymatgen.db.vv.report
def _header ( self ):
lines = [
- "<div class='header'><h1{{sh1}}> {t} </h1>" . format ( t = self . TITLE ),
+ f "<div class='header'><h1 {{ sh1 }} > { self . TITLE } </h1>" ,
"<p {sp} >Compared <em {sem} >{{db1}}</em> with <em {sem} >{{db2}}</em></p>" ,
"<p {sp} >Filter: <span class='fixed'>{{filter}}</span></p>" ,
"<p {sp} >Run time: <em {sem} >{{start_time}}</em> to <em {sem} >{{end_time}}</em> " ,
@@ -713,17 +696,13 @@ Source code for pymatgen.db.vv.report
def _body ( self , result ):
body = [ "<div class='content'>" ]
for section in result . keys ():
- body . append (
- "<div class='section'{{ssec}}><h2{{sh2}}> {t} </h2>" . format (
- t = section . title ()
- )
- )
+ body . append ( f "<div class='section' {{ ssec }} ><h2 {{ sh2 }} > { section . title () } </h2>" )
if len ( result [ section ]) == 0 :
body . append ( "<div class='empty'>Empty</div>" )
else :
@@ -754,9 +733,7 @@ Source code for pymatgen.db.vv.report
cols = self . ordered_cols ( subset , section )
# Format the table.
tables . extend (
- [ "<tr {tr1} >" . format ( ** inline )]
- + [ "<th {th} > {c} </th>" . format ( c = c , ** inline ) for c in cols ]
- + [ "</tr>" ]
+ [ "<tr {tr1} >" . format ( ** inline )] + [ "<th {th} > {c} </th>" . format ( c = c , ** inline ) for c in cols ] + [ "</tr>" ]
)
self . sort_rows ( rows , section )
for i , r in enumerate ( rows ):
@@ -764,11 +741,9 @@ Source code for pymatgen.db.vv.report
if tuple ( sorted ( r . keys ())) != subset :
continue
if self . _url is not None :
- r [ cols [ 0 ]] = "<a href=' {p}{v} '> {v} </a>" . format (
- p = self . _url , v = r [ cols [ 0 ]]
- )
+ r [ cols [ 0 ]] = "<a href=' {p}{v} '> {v} </a>" . format ( p = self . _url , v = r [ cols [ 0 ]])
tables . extend (
- [ "<tr {} >" . format ( tr ) . format ( ** inline )]
+ [ f "<tr { tr } >" . format ( ** inline )]
+ [ "<td {td} > {d} </td>" . format ( d = r [ c ], ** inline ) for c in cols ]
+ [ "</tr>" ]
)
@@ -799,14 +774,14 @@ Source code for pymatgen.db.vv.report
lines . append ( "* " + section . title ())
indent = " " * 4
if len ( result [ section ]) == 0 :
- lines . append ( " {} EMPTY" . format ( indent ))
+ lines . append ( f " { indent } EMPTY" )
else :
keyset , maxwid = self . result_subsets ( result [ section ])
for columns in keyset :
ocol = self . ordered_cols ( columns , section )
mw = maxwid [ columns ]
mw_i = [ columns . index ( c ) for c in ocol ] # reorder indexes
- fmt = " " . join ([ "{{: {:d} s}}" . format ( mw [ i ]) for i in mw_i ])
+ fmt = " " . join ([ f " {{ : { mw [ i ] : d } s }} " for i in mw_i ])
lines . append ( "" )
lines . append ( indent + fmt . format ( * ocol ))
lines . append ( indent + "-_" * ( sum ( mw ) / 2 + len ( columns )))
@@ -820,7 +795,7 @@ Source code for pymatgen.db.vv.report
def _record ( self , rec ):
- fields = [ " {} : {} " . format ( k , v ) for k , v in rec . items ()]
+ fields = [ f " { k } : { v } " for k , v in rec . items ()]
return "{" + ", " . join ( fields ) + "}"
@@ -840,7 +815,7 @@ Source code for pymatgen.db.vv.report
Quick search
diff --git a/docs/_modules/pymatgen/db/vv/util.html b/docs/_modules/pymatgen/db/vv/util.html
index f6620c5..b592c48 100644
--- a/docs/_modules/pymatgen/db/vv/util.html
+++ b/docs/_modules/pymatgen/db/vv/util.html
@@ -5,7 +5,7 @@
- pymatgen.db.vv.util — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.vv.util — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.vv.util
@@ -49,8 +49,7 @@
Navigation
Source code for pymatgen.db.vv.util
-# coding: utf-8
-"""
+"""
Utility functions and classes for validation.
"""
__author__ = "Dan Gunter"
@@ -61,16 +60,13 @@ Source code for pymatgen.db.vv.util
__status__ = "Development"
__date__ = "3/29/13"
-#!/usr/bin/env python3
-
-
from argparse import Action
from collections import deque
from itertools import chain
import logging
import time
from sys import getsizeof
-from yaml import load
+import ruamel.yaml as yaml
TRACE = logging . DEBUG - 1
@@ -83,7 +79,7 @@ Source code for pymatgen.db.vv.util
def __init__ ( self , name = None ):
if name is None :
if self . __module__ != "__main__" :
- name = " %s . %s " % ( self . __module__ , self . __class__ . __name__ )
+ name = f " { self . __module__ } . { self . __class__ . __name__ } "
else :
name = self . __class__ . __name__
self . _log = logging . getLogger ( name )
@@ -152,9 +148,7 @@ Source code for pymatgen.db.vv.util
do_foo2()
"""
- def __init__ (
- self , name = "event" , elapsed = None , log = None , level = logging . DEBUG , ** kwargs
- ):
+ def __init__ ( self , name = "event" , elapsed = None , log = None , level = logging . DEBUG , ** kwargs ):
self . name , self . kw , self . level = name , kwargs , level
self . elapsed = elapsed
self . _log = log
@@ -165,10 +159,8 @@ Source code for pymatgen.db.vv.util
def __exit__ ( self , type , value , tb ):
elapsed = time . time () - self . begin
if self . _log is not None :
- nvp = ", " . join ([ " {} = {} " . format ( k , v ) for k , v in self . kw . items ()])
- self . _log . log (
- self . level , "@ {n} = {s:f} s {kw} " . format ( n = self . name , s = elapsed , kw = nvp )
- )
+ nvp = ", " . join ([ f " { k } = { v } " for k , v in self . kw . items ()])
+ self . _log . log ( self . level , f "@ { self . name } = { elapsed : f } s { nvp } " )
if self . elapsed :
self . elapsed . value = elapsed
@@ -259,11 +251,11 @@ Source code for pymatgen.db.vv.util
config = self . _get_config_from_file ( values )
for key , value in config . items ():
setattr ( namespace , key , value )
- _alog . debug ( "YamlConfig.namespace= {} " . format ( namespace ))
+ _alog . debug ( f "YamlConfig.namespace= { namespace } " )
def _get_config_from_file ( self , filename ):
with open ( filename ) as f :
- config = load ( f )
+ config = yaml . load ( f )
return config
@@ -282,12 +274,12 @@ Source code for pymatgen.db.vv.util
try :
key , value = item . split ( "=" , 1 )
except ValueError :
- msg = "argument item ' {} ' not in form key=value" . format ( item )
+ msg = f "argument item ' { item } ' not in form key=value"
if _argparse_is_dumb :
_alog . warn ( msg )
raise ValueError ( msg )
if key in d :
- msg = "Duplicate key for ' {} ' not allowed" . format ( key )
+ msg = f "Duplicate key for ' { key } ' not allowed"
if _argparse_is_dumb :
_alog . warn ( msg )
raise ValueError ( msg )
@@ -323,7 +315,7 @@ Source code for pymatgen.db.vv.util
Quick search
diff --git a/docs/_modules/pymatgen/db/vv/validate.html b/docs/_modules/pymatgen/db/vv/validate.html
index d613db4..1022b05 100644
--- a/docs/_modules/pymatgen/db/vv/validate.html
+++ b/docs/_modules/pymatgen/db/vv/validate.html
@@ -5,7 +5,7 @@
- pymatgen.db.vv.validate — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.vv.validate — pymatgen-db 2022.3.17 documentation
@@ -37,7 +37,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Module code »
pymatgen.db.vv.validate
@@ -77,7 +77,7 @@
Source code for pymatgen.db.vv.validate
"Syntax error in configuration of Validator"
def __init__ ( self , target , desc ):
- msg = 'Invalid syntax: {} -> " {} "' . format ( desc , target )
+ msg = f 'Invalid syntax: { desc } -> " { target } "'
Exception . __init__ ( self , msg )
@@ -109,7 +109,7 @@
Source code for pymatgen.db.vv.validate
"""
if not self . _PATTERN . match ( text ):
raise ValidatorSyntaxError ( text , self . BAD_CONSTRAINT_ERR )
- tokens = re . split ( "@?\s+" , text )
+ tokens = re . split ( r "@?\s+" , text )
if len ( tokens ) < 1 :
raise ValidatorSyntaxError ( text , self . BAD_CONSTRAINT_ERR )
self . method = tokens [ 0 ]
@@ -280,9 +280,7 @@ Source code for pymatgen.db.vv.validate
self . _total += 1
if self . _n == 0 or self . _count < self . _n :
return
- sys . stderr . write (
- self . _fmt . format ( * args , subject = self . _subject , count = self . count )
- )
+ sys . stderr . write ( self . _fmt . format ( * args , subject = self . _subject , count = self . count ))
sys . stderr . write ( " \n " )
sys . stderr . flush ()
self . _count = 0
@@ -305,7 +303,7 @@
Source code for pymatgen.db.vv.validate
DoesLogging . __init__ ( self , name = "mg.ConstraintSpec" )
self . _sections , _slist = {}, []
for item in spec :
- self . _log . debug ( "build constraint from: {} " . format ( item ))
+ self . _log . debug ( f "build constraint from: { item } " )
if isinstance ( item , dict ):
self . _add_complex_section ( item )
else :
@@ -332,7 +330,7 @@ Source code for pymatgen.db.vv.validate
try :
fltr = item [ self . FILTER_SECT ]
except KeyError :
- raise ValueError ( "configuration requires ' {} '" . format ( self . FILTER_SECT ))
+ raise ValueError ( f "configuration requires ' { self . FILTER_SECT } '" )
sample = item . get ( self . SAMPLE_SECT , None )
constraints = item . get ( self . CONSTRAINT_SECT , None )
@@ -404,9 +402,7 @@ Source code for pymatgen.db.vv.validate
- def __init__ (
- self , max_violations = 50 , max_dberrors = 10 , aliases = None , add_exists = False
- ):
+ def __init__ ( self , max_violations = 50 , max_dberrors = 10 , aliases = None , add_exists = False ):
DoesLogging . __init__ ( self , name = "mg.validator" )
self . set_progress ( 0 )
self . _aliases = aliases if aliases else {}
@@ -426,9 +422,7 @@ Source code for pymatgen.db.vv.validate
:type num: int
:return: None
"""
- report_str = (
- "Progress for {subject} : {count:d} invalid, {:d} db errors, {:d} bytes"
- )
+ report_str = "Progress for {subject} : {count:d} invalid, {:d} db errors, {:d} bytes"
self . _progress = ProgressMeter ( num , report_str )
[docs] def num_violations ( self ):
@@ -481,8 +475,8 @@
Source code for pymatgen.db.vv.validate
query = parts . cond . to_mongo ( disjunction = False )
query . update ( parts . body . to_mongo ())
cvgroup . condition = parts . cond . to_mongo ( disjunction = False )
- self . _log . debug ( "Query spec: {} " . format ( query ))
- self . _log . debug ( "Query fields: {} " . format ( parts . report_fields ))
+ self . _log . debug ( f "Query spec: { query } " )
+ self . _log . debug ( f "Query fields: { parts . report_fields } " )
# Find records that violate 1 or more constraints
cursor = coll . find ( query , parts . report_fields , ** self . _find_kw )
if parts . sampler is not None :
@@ -504,7 +498,7 @@ Source code for pymatgen.db.vv.validate
num_dberr += 1
if num_dberr > self . _max_dberr > 0 :
raise DBError ( "Too many errors" )
- self . _log . warn ( "DB. {:d} : {} " . format ( num_dberr , err ))
+ self . _log . warn ( f "DB. { num_dberr : d } : { err } " )
continue
# report progress
@@ -537,26 +531,20 @@ Source code for pymatgen.db.vv.validate
fval = mongo_get ( record , key )
if fval is None :
expected = clause . constraint . value
- reasons . append (
- ConstraintViolation ( clause . constraint , "missing" , expected )
- )
+ reasons . append ( ConstraintViolation ( clause . constraint , "missing" , expected ))
continue
if op . is_variable ():
# retrieve value for variable
var_name = clause . constraint . value
value = mongo_get ( record , var_name , default = None )
if value is None :
- reasons . append (
- ConstraintViolation ( clause . constraint , "missing" , var_name )
- )
+ reasons . append ( ConstraintViolation ( clause . constraint , "missing" , var_name ))
continue
clause . constraint . value = value # swap out value, temporarily
# take length for size
if op . is_size ():
if isinstance ( fval , str ) or not hasattr ( fval , "__len__" ):
- reasons . append (
- ConstraintViolation ( clause . constraint , type ( fval ), "sequence" )
- )
+ reasons . append ( ConstraintViolation ( clause . constraint , type ( fval ), "sequence" ))
if op . is_variable ():
clause . constraint . value = var_name # put original value back
continue
@@ -612,9 +600,7 @@ Source code for pymatgen.db.vv.validate
cond_query = MongoQuery ()
if sval . filters is not None :
- cond_groups = self . _process_constraint_expressions (
- sval . filters , rev = False
- )
+ cond_groups = self . _process_constraint_expressions ( sval . filters , rev = False )
for cg in cond_groups . values ():
for c in cg :
cond_query . add_clause ( MongoClause ( c , rev = False ))
@@ -651,9 +637,7 @@ Source code for pymatgen.db.vv.validate
for field_name , group in groups . items ():
conflicts = group . get_conflicts ()
if conflicts :
- raise ValueError (
- "Conflicts for field {} : {} " . format ( field_name , conflicts )
- )
+ raise ValueError ( f "Conflicts for field { field_name } : { conflicts } " )
return groups
def _is_python ( self , constraint_list ):
@@ -664,13 +648,9 @@ Source code for pymatgen.db.vv.validate
:return: True if this refers to an import of code, False otherwise
:raises: ValidatorSyntaxError
"""
- if len ( constraint_list ) == 1 and PythonMethod . constraint_is_method (
- constraint_list [ 0 ]
- ):
+ if len ( constraint_list ) == 1 and PythonMethod . constraint_is_method ( constraint_list [ 0 ]):
return True
- if len ( constraint_list ) > 1 and any (
- filter ( PythonMethod . constraint_is_method , constraint_list )
- ):
+ if len ( constraint_list ) > 1 and any ( filter ( PythonMethod . constraint_is_method , constraint_list )):
condensed_list = "/" . join ( constraint_list )
err = PythonMethod . CANNOT_COMBINE_ERR
raise ValidatorSyntaxError ( condensed_list , err )
@@ -690,7 +670,7 @@ Source code for pymatgen.db.vv.validate
try :
self . aliases = new_value
except Exception as err :
- raise ValueError ( "invalid value: {} " . format ( err ))
+ raise ValueError ( f "invalid value: { err } " )
[docs] class Sampler ( DoesLogging ):
@@ -716,15 +696,11 @@
Source code for pymatgen.db.vv.validate
DoesLogging . __init__ ( self , "mg.sampler" )
# Sanity checks
if min_items < 0 :
- raise ValueError ( "min_items cannot be negative ( {:d} )" . format ( min_items ))
+ raise ValueError ( f "min_items cannot be negative ( { min_items : d } )" )
if ( max_items != 0 ) and ( max_items < min_items ):
- raise ValueError (
- "max_items must be zero or >= min_items ( {:d} < {:d} )" . format (
- max_items , min_items
- )
- )
+ raise ValueError ( f "max_items must be zero or >= min_items ( { max_items : d } < { min_items : d } )" )
if not ( 0.0 <= p <= 1.0 ):
- raise ValueError ( "probability, p, must be between 0 and 1 ( {:f} )" . format ( p ))
+ raise ValueError ( f "probability, p, must be between 0 and 1 ( { p : f } )" )
self . min_items = min_items
self . max_items = max_items
self . p = p
@@ -735,7 +711,7 @@ Source code for pymatgen.db.vv.validate
if distrib == self . DIST_RUNIF :
self . _keep = self . _keep_runif
else :
- raise ValueError ( "unrecognized distribution: {} " . format ( distrib ))
+ raise ValueError ( f "unrecognized distribution: { distrib } " )
@property
def is_empty ( self ):
@@ -817,7 +793,7 @@ Source code for pymatgen.db.vv.validate
Quick search
diff --git a/docs/_sources/pymatgen.rst.txt b/docs/_sources/pymatgen.rst.txt
index 601cd54..bca3246 100644
--- a/docs/_sources/pymatgen.rst.txt
+++ b/docs/_sources/pymatgen.rst.txt
@@ -1,6 +1,8 @@
pymatgen namespace
==================
+.. py:module:: pymatgen
+
Subpackages
-----------
diff --git a/docs/_static/basic.css b/docs/_static/basic.css
index aa9df31..bf18350 100644
--- a/docs/_static/basic.css
+++ b/docs/_static/basic.css
@@ -4,7 +4,7 @@
*
* Sphinx stylesheet -- basic theme.
*
- * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
+ * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
@@ -731,8 +731,9 @@ dl.glossary dt {
.classifier:before {
font-style: normal;
- margin: 0.5em;
+ margin: 0 0.5em;
content: ":";
+ display: inline-block;
}
abbr, acronym {
@@ -756,6 +757,7 @@ span.pre {
-ms-hyphens: none;
-webkit-hyphens: none;
hyphens: none;
+ white-space: nowrap;
}
div[class*="highlight-"] {
@@ -819,7 +821,7 @@ div.code-block-caption code {
table.highlighttable td.linenos,
span.linenos,
-div.doctest > div.highlight span.gp { /* gp: Generic.Prompt */
+div.highlight span.gp { /* gp: Generic.Prompt */
user-select: none;
-webkit-user-select: text; /* Safari fallback only */
-webkit-user-select: none; /* Chrome/Safari */
diff --git a/docs/_static/doctools.js b/docs/_static/doctools.js
index 61ac9d2..e509e48 100644
--- a/docs/_static/doctools.js
+++ b/docs/_static/doctools.js
@@ -4,7 +4,7 @@
*
* Sphinx JavaScript utilities for all documentation.
*
- * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
+ * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
@@ -264,6 +264,9 @@ var Documentation = {
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
+ var url = new URL(window.location);
+ url.searchParams.delete('highlight');
+ window.history.replaceState({}, '', url);
},
/**
@@ -301,12 +304,14 @@ var Documentation = {
window.location.href = prevHref;
return false;
}
+ break;
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
+ break;
}
}
});
diff --git a/docs/_static/documentation_options.js b/docs/_static/documentation_options.js
index 788a7d1..f6ac950 100644
--- a/docs/_static/documentation_options.js
+++ b/docs/_static/documentation_options.js
@@ -1,6 +1,6 @@
var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
- VERSION: '2021.5.28',
+ VERSION: '2022.3.17',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
BUILDER: 'html',
diff --git a/docs/_static/language_data.js b/docs/_static/language_data.js
index 863704b..ebe2f03 100644
--- a/docs/_static/language_data.js
+++ b/docs/_static/language_data.js
@@ -5,7 +5,7 @@
* This script contains the language-specific data used by searchtools.js,
* namely the list of stopwords, stemmer, scorer and splitter.
*
- * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
+ * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
diff --git a/docs/_static/searchtools.js b/docs/_static/searchtools.js
index e09f926..2d77859 100644
--- a/docs/_static/searchtools.js
+++ b/docs/_static/searchtools.js
@@ -4,7 +4,7 @@
*
* Sphinx JavaScript utilities for the full-text search.
*
- * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
+ * :copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
* :license: BSD, see LICENSE for details.
*
*/
@@ -282,7 +282,10 @@ var Search = {
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
if (data !== '' && data !== undefined) {
- listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
+ var summary = Search.makeSearchSummary(data, searchterms, hlterms);
+ if (summary) {
+ listItem.append(summary);
+ }
}
Search.output.append(listItem);
setTimeout(function() {
@@ -325,7 +328,9 @@ var Search = {
var results = [];
for (var prefix in objects) {
- for (var name in objects[prefix]) {
+ for (var iMatch = 0; iMatch != objects[prefix].length; ++iMatch) {
+ var match = objects[prefix][iMatch];
+ var name = match[4];
var fullname = (prefix ? prefix + '.' : '') + name;
var fullnameLower = fullname.toLowerCase()
if (fullnameLower.indexOf(object) > -1) {
@@ -339,7 +344,6 @@ var Search = {
} else if (parts[parts.length - 1].indexOf(object) > -1) {
score += Scorer.objPartialMatch;
}
- var match = objects[prefix][name];
var objname = objnames[match[1]][2];
var title = titles[match[0]];
// If more than one term searched for, we require other words to be
@@ -498,6 +502,9 @@ var Search = {
*/
makeSearchSummary : function(htmlText, keywords, hlwords) {
var text = Search.htmlToText(htmlText);
+ if (text == "") {
+ return null;
+ }
var textLower = text.toLowerCase();
var start = 0;
$.each(keywords, function() {
diff --git a/docs/_themes/README.html b/docs/_themes/README.html
index 545e204..52050ec 100644
--- a/docs/_themes/README.html
+++ b/docs/_themes/README.html
@@ -6,7 +6,7 @@
- krTheme Sphinx Style — pymatgen-db 2021.5.28 documentation
+ krTheme Sphinx Style — pymatgen-db 2022.3.17 documentation
@@ -38,7 +38,7 @@ Navigation
modules |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
krTheme Sphinx Style
@@ -96,7 +96,7 @@ This Page
Quick search
diff --git a/docs/builders.html b/docs/builders.html
index c6fc530..d66e418 100644
--- a/docs/builders.html
+++ b/docs/builders.html
@@ -6,7 +6,7 @@
- Database “Builders” — pymatgen-db 2021.5.28 documentation
+ Database “Builders” — pymatgen-db 2022.3.17 documentation
@@ -46,7 +46,7 @@ Navigation
previous |
-
pymatgen-db 2021.5.28 documentation »
+
pymatgen-db 2022.3.17 documentation »
Database “Builders”
@@ -686,8 +686,9 @@ Incremental builds
@@ -96,14 +96,14 @@
Symbols
- --config <file>
+ --config
- --db CONFIG
+ --db
mgvv-diff command line option
@@ -115,46 +115,31 @@ Symbols
-
- --email ADDR
-
-
- --email-server HOST
+ --email-server
- --file <file>
+ --file
-
- --file FILE
-
-
- --format <type>
+ --format
-
- --format FORMAT
-
-
@@ -168,21 +153,21 @@ Symbols
- --info INFO
+ --info
- --key KEY
+ --key
- --limit <num>
+ --limit
- --properties PROPS
+ --properties
- --query EXPR
+ --query
- --url URL
+ --url
- -c <file>
-
-
-
- -C <name>
+ -C
- -D CONFIG
+ -c
- -e <file or spec>
+ -D
- -E ADDR
+ -E
- -f <file>
+ -e
- -F <type>
+ -F
-
- -f FILE
-
-
- -F FORMAT
+ -f
@@ -321,14 +296,14 @@ Symbols
- -i INFO
+ -i
- -k KEY
+ -k
- -p PROPS
+ -p
- -q EXPR
+ -q
- -s HOST
+ -s
- -u URL
+ -u
--print
-
--properties PROPS
+ --properties
-
--query EXPR
+ --query
-
--url URL
+ --url
--verbose
-
-D CONFIG
+ -D
-
-E ADDR
+ -E
-
-f FILE
+ -f
-
-F FORMAT
+ -F
-h
-
-i INFO
+ -i
-
-k KEY
+ -k
-m
-n
-
-P
+ -p
-
-p PROPS
+ -P
-
-q EXPR
+ -q
-
-s HOST
+ -s
-
-u URL
+ -u
-v
@@ -1021,6 +991,8 @@
M
module
@@ -289,8 +289,9 @@ Indices and tables
@@ -65,7 +65,7 @@ Python Module Index
- pymatgen
+ pymatgen
@@ -194,7 +194,7 @@ Python Module Index
Quick search
diff --git a/docs/pymatgen.db.alchemy.html b/docs/pymatgen.db.alchemy.html
index 03e8ffc..7bda6a0 100644
--- a/docs/pymatgen.db.alchemy.html
+++ b/docs/pymatgen.db.alchemy.html
@@ -6,7 +6,7 @@
- pymatgen.db.alchemy package — pymatgen-db 2021.5.28 documentation
+ pymatgen.db.alchemy package — pymatgen-db 2022.3.17 documentation
@@ -46,7 +46,7 @@ Navigation
previous |
- pymatgen-db 2021.5.28 documentation »
+ pymatgen-db 2022.3.17 documentation »
pymatgen.db package »
pymatgen.db.alchemy package
@@ -74,7 +74,7 @@ Submodules[source]
Bases: pymatgen.alchemy.transmuters.StandardTransmuter
The QeTransmuter uses a QueryEngine to retrieve and generate new structures
from a database.
@@ -112,8 +112,9 @@ Submodules