| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
################################################################################ |
| 4 |
## ## |
| 5 |
## This file is part of NCrystal (see https://mctools.github.io/ncrystal/) ## |
| 6 |
## ## |
| 7 |
## Copyright 2015-2022 NCrystal developers ## |
| 8 |
## ## |
| 9 |
## Licensed under the Apache License, Version 2.0 (the "License"); ## |
| 10 |
## you may not use this file except in compliance with the License. ## |
| 11 |
## You may obtain a copy of the License at ## |
| 12 |
## ## |
| 13 |
## http://www.apache.org/licenses/LICENSE-2.0 ## |
| 14 |
## ## |
| 15 |
## Unless required by applicable law or agreed to in writing, software ## |
| 16 |
## distributed under the License is distributed on an "AS IS" BASIS, ## |
| 17 |
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## |
| 18 |
## See the License for the specific language governing permissions and ## |
| 19 |
## limitations under the License. ## |
| 20 |
## ## |
| 21 |
################################################################################ |
| 22 |
|
| 23 |
""" |
| 24 |
Script which can be used to generate NCMAT files from crystal structures in |
| 25 |
online databases, and optionally also compare existing NCMAT files with online |
| 26 |
structures indicated in their comments. |
| 27 |
""" |
| 28 |
|
| 29 |
################################################################################################ |
| 30 |
####### Common code for all NCrystal cmdline scripts needing to import NCrystal modules ######## |
| 31 |
import sys |
| 32 |
pyversion = sys.version_info[0:3] |
| 33 |
_minpyversion=(3,6,0) |
| 34 |
if pyversion < _minpyversion: |
| 35 |
raise SystemExit('Unsupported python version %i.%i.%i detected (needs %i.%i.%i or later).'%(pyversion+_minpyversion)) |
| 36 |
import os |
| 37 |
import pathlib |
| 38 |
|
| 39 |
def maybeThisIsConda(): |
| 40 |
return ( os.environ.get('CONDA_PREFIX',None) or |
| 41 |
os.path.exists(os.path.join(sys.base_prefix, 'conda-meta')) ) |
| 42 |
|
| 43 |
def fixSysPathAndImportNCrystal( *, allowfail = False ): |
| 44 |
thisdir = pathlib.Path( __file__ ).parent |
| 45 |
def extract_cmake_pymodloc(): |
| 46 |
p = thisdir / 'ncrystal-config' |
| 47 |
if not p.exists(): |
| 48 |
return |
| 49 |
with p.open('rt') as fh: |
| 50 |
for i,l in enumerate(fh): |
| 51 |
if i==30: |
| 52 |
break |
| 53 |
if l.startswith('#CMAKE_RELPATH_TO_PYMOD:'): |
| 54 |
l = l[24:].strip() |
| 55 |
return ( thisdir / l ) if l else None |
| 56 |
pml = extract_cmake_pymodloc() |
| 57 |
hack_syspath = pml and ( pml / 'NCrystal' / '__init__.py' ).exists() |
| 58 |
if hack_syspath: |
| 59 |
sys.path.insert(0,str(pml.absolute().resolve())) |
| 60 |
try: |
| 61 |
import NCrystal |
| 62 |
except ImportError: |
| 63 |
if allowfail: |
| 64 |
return |
| 65 |
msg = 'ERROR: Could not import the NCrystal Python module' |
| 66 |
if maybeThisIsConda(): |
| 67 |
msg += ' (if using conda it might help to close your terminal and activate your environment again)' |
| 68 |
elif not hack_syspath: |
| 69 |
msg += ' (perhaps your PYTHONPATH is misconfigured)' |
| 70 |
raise SystemExit(msg) |
| 71 |
return NCrystal |
| 72 |
################################################################################################ |
| 73 |
NC = fixSysPathAndImportNCrystal() |
| 74 |
|
| 75 |
import argparse |
| 76 |
import functools |
| 77 |
import math |
| 78 |
import re |
| 79 |
import numpy as np |
| 80 |
|
| 81 |
fallback_debye_temp = 300.0 |
| 82 |
pdffn = 'ncrystal_onlinedb_validate.pdf' |
| 83 |
|
| 84 |
def classifySG(sgno): |
| 85 |
assert 1<=sgno<=230 |
| 86 |
l=[(195,'cubic'),(168,'hexagonal'),(143,'trigonal'), |
| 87 |
(75,'tetragonal'),(16,'orthorombic'),(3,'monoclinic'),(1,'triclinic')] |
| 88 |
for thr,nme in l: |
| 89 |
if sgno>=thr: |
| 90 |
return nme |
| 91 |
assert False |
| 92 |
|
| 93 |
def getMaterialsProjectAPIKEY(): |
| 94 |
apikey=os.environ.get('MATERIALSPROJECT_USER_API_KEY',None) |
| 95 |
if not apikey: |
| 96 |
raise SystemExit('ERROR: Missing API key for materialsproject.org access. To fix, ' |
| 97 |
+'please make sure the environment variable MATERIALSPROJECT_USER_API_KEY' |
| 98 |
+' contains your personal access key that you see on' |
| 99 |
+' https://www.materialsproject.org/dashboard (after logging in).') |
| 100 |
return apikey |
| 101 |
|
| 102 |
_fracdb=[None] |
| 103 |
def prettyFmtValue(x): |
| 104 |
"""Recognises common fractions in truncated values like '0.33333333' or |
| 105 |
'0.4166667' and formats them as '1/3' and '5/12'. This not only saves space, |
| 106 |
but can also reinject accuracy in atom positions (ncrystal_verifyatompos can |
| 107 |
be used to check this, but it seems to be a clear improvement in all cases |
| 108 |
tested so far). |
| 109 |
""" |
| 110 |
global _fracdb |
| 111 |
assert 0.0 <= x < 1.0 |
| 112 |
if x==0.0: |
| 113 |
return '0' |
| 114 |
if x==0.5: |
| 115 |
return '1/2' |
| 116 |
def find_nearest_idx(arr,val): |
| 117 |
i = np.searchsorted(arr, val) |
| 118 |
if i == 0: |
| 119 |
return 0 |
| 120 |
if i == len(arr): |
| 121 |
return len(arr)-1 |
| 122 |
return i if abs(val-arr[i])<abs(val-arr[i-1]) else i-1 |
| 123 |
def initFractions(): |
| 124 |
fractions=set() |
| 125 |
nmax=40 |
| 126 |
for a in range(1,nmax): |
| 127 |
for b in range(a+1,nmax+1): |
| 128 |
g=math.gcd(a,b) |
| 129 |
fractions.add( (a//g, b//g ) ) |
| 130 |
fractions=list(sorted( (a/b,a,b) for a,b in fractions)) |
| 131 |
values = np.asarray( list(e for e,_,_ in fractions), dtype=float ) |
| 132 |
fmt = [ f'{a}/{b}' for _,a,b in fractions ] |
| 133 |
return values,fmt |
| 134 |
xfmt = '%.14g'%x |
| 135 |
if xfmt.startswith('0.'): |
| 136 |
xfmt = xfmt[1:] |
| 137 |
if _fracdb[0] is None: |
| 138 |
_fracdb[0] = initFractions() |
| 139 |
dbvals, dbfmt = _fracdb[0] |
| 140 |
i = find_nearest_idx(dbvals,x) |
| 141 |
v=dbvals[i] |
| 142 |
#check if credible that the numbers are identical (must be close AND the str |
| 143 |
#representations must be consistent with truncation): |
| 144 |
expected_at_prec = ((f'%.{len(xfmt)-1}g')%v)[1:] |
| 145 |
if abs(v-x)<1e-7 and expected_at_prec == xfmt: |
| 146 |
return dbfmt[i] |
| 147 |
if abs(v-x)<1e-14: |
| 148 |
return dbfmt[i] |
| 149 |
return xfmt |
| 150 |
|
| 151 |
def produceNCMAT(structure,srcdescr,dynamics,rawformat,atomdb,quiet): |
| 152 |
if not dynamics: |
| 153 |
dynamics = dict(comments=[],dyninfos=[]) |
| 154 |
|
| 155 |
#In case source had deuterium directly and we have to remap it via the |
| 156 |
#atomdb parameter, we must do a trick and assign the element another |
| 157 |
#name. This is because the @ATOMDB section can no reassign isotope names |
| 158 |
#another meaning according to the NCMAT format. |
| 159 |
remap_D = False |
| 160 |
if atomdb: |
| 161 |
_=atomdb.replace(':',' ').split() |
| 162 |
assert len(_)>=3 and _[1]=='is' |
| 163 |
remap_D = _[0]=='D' |
| 164 |
if remap_D: |
| 165 |
_[0] = 'X1' |
| 166 |
atomdb = ' '.join(_) |
| 167 |
|
| 168 |
elemNameRemap = lambda en : "X1" if (remap_D and en=="D") else en |
| 169 |
|
| 170 |
emitted_warnings = [] |
| 171 |
def produceWarning(w): |
| 172 |
if not quiet: |
| 173 |
print(f'WARNING: {w}') |
| 174 |
emitted_warnings.append(w) |
| 175 |
|
| 176 |
def elemName(site): |
| 177 |
species = site.species |
| 178 |
_=site.as_dict()['species'] |
| 179 |
if not species.is_element or not len(species.elements)==1 or not len(_)==1: |
| 180 |
raise SystemExit('Error: This script only supports a single well defined element at each site') |
| 181 |
occu=_[0]['occu'] |
| 182 |
if abs(occu-1.0)<0.1 and occu!=1.0: |
| 183 |
if abs(occu-1.0)>0.001: |
| 184 |
produceWarning( f"Encountered species with almost-but-not-quite unit occupancy ({occu}). Treating as 1.0" ) |
| 185 |
occu=1.0 |
| 186 |
if occu!=1.0: |
| 187 |
raise SystemExit(f'Error: This script only supports species with unit occupancies (encountered occupancy {occu})') |
| 188 |
return _[0]['element'] |
| 189 |
elems = [] |
| 190 |
formula_elem2count={} |
| 191 |
def apfmt(x): |
| 192 |
while x<0.0: |
| 193 |
x+=1 |
| 194 |
while x>=1.0: |
| 195 |
x-=1.0 |
| 196 |
return (fmt if rawformat else prettyFmtValue)(x) |
| 197 |
out_atompos_lines = '' |
| 198 |
for s in structure.sites: |
| 199 |
c=s.frac_coords |
| 200 |
en = elemName(s) |
| 201 |
elems += [en] |
| 202 |
out_atompos_lines += f' {elemNameRemap(en)} {apfmt(c[0])} {apfmt(c[1])} {apfmt(c[2])}\n' |
| 203 |
formula_elem2count[en] = formula_elem2count.get(en, 0) + 1 |
| 204 |
elems_unique = sorted(list(set(elems))) |
| 205 |
|
| 206 |
a,b,c = structure.lattice.abc |
| 207 |
alpha,beta,gamma = structure.lattice.angles |
| 208 |
sgsymb,sgno = structure.get_space_group_info() |
| 209 |
def fmt(x): |
| 210 |
s='%.14g'%x |
| 211 |
if s.startswith('0.'): |
| 212 |
s=s[1:] |
| 213 |
return s |
| 214 |
descr = ''.join('# %s\n'%e for e in srcdescr) |
| 215 |
|
| 216 |
if 195 <= sgno <= 230: |
| 217 |
cell=f'@CELL\n cubic {fmt(a)}' |
| 218 |
assert fmt(a)==fmt(b) and fmt(a)==fmt(c) |
| 219 |
assert fmt(alpha)=='90' and fmt(beta)=='90' and fmt(gamma)=='90' |
| 220 |
else: |
| 221 |
cell=f'@CELL\n lengths {fmt(a)} {fmt(b) if fmt(b)!=fmt(a) else "!!"} {fmt(c)}\n angles {fmt(alpha)} {fmt(beta)} {fmt(gamma)}' |
| 222 |
|
| 223 |
# |
| 224 |
elem2dyninfo={} |
| 225 |
elems_with_fallback_dyninfo = [] |
| 226 |
for en in elems_unique: |
| 227 |
#dynamics = dict(comments=[],dyninfos=[]) |
| 228 |
for di in dynamics['dyninfos']: |
| 229 |
if di.atomData.displayLabel() == en: |
| 230 |
elem2dyninfo[en] = di |
| 231 |
break |
| 232 |
if not en in elem2dyninfo: |
| 233 |
#Check if perhaps this is just an isotope issue (e.g. "D" instead of |
| 234 |
#"H"), and search for element with same Z: |
| 235 |
en_atomData = NC.atomDB(en) |
| 236 |
for di in dynamics['dyninfos']: |
| 237 |
if di.atomData.isElement() and di.atomData.Z()==en_atomData.Z(): |
| 238 |
elem2dyninfo[en] = di |
| 239 |
break |
| 240 |
if not en in elem2dyninfo: |
| 241 |
elems_with_fallback_dyninfo.append( en ) |
| 242 |
|
| 243 |
if dynamics['dyninfos'] and not elem2dyninfo: |
| 244 |
raise SystemExit('Error: was not able to transfer any dynamics from source.') |
| 245 |
|
| 246 |
formula=structure.composition.reduced_formula |
| 247 |
if remap_D: |
| 248 |
formula+='(WARNING:D was not changed automatically)' |
| 249 |
title=f'{formula} ({classifySG(sgno)}, SG-{sgno} / {sgsymb})' |
| 250 |
orig_comments='' |
| 251 |
if elems_with_fallback_dyninfo: |
| 252 |
orig_comments += '\n# WARNING: Dummy Debye temperature values were\n' |
| 253 |
orig_comments += '# inserted below for at least 1 element!\n' |
| 254 |
orig_comments += '#' |
| 255 |
if dynamics['comments']: |
| 256 |
orig_comments += '\n# NOTICE: For reference comments in the file used as source\n' |
| 257 |
orig_comments += '# for the @DYNINFO sections are repeated below.\n' |
| 258 |
orig_comments += '# (please extract relevant sections and merge with\n' |
| 259 |
orig_comments += '# comments above in order to finalise file).\n' |
| 260 |
orig_comments += '#\n' |
| 261 |
for e in dynamics['comments']: |
| 262 |
orig_comments += f'# ---> {e}\n' |
| 263 |
orig_comments+= '#' |
| 264 |
atomdb = '\n@ATOMDB\n %s'%(' '.join(atomdb.replace(':',' ').split())) if atomdb else '' |
| 265 |
out = f"""NCMAT v5 |
| 266 |
# |
| 267 |
# {title} |
| 268 |
# |
| 269 |
# Structure converted with ncrystal_onlinedb2ncmat from: |
| 270 |
# |
| 271 |
{descr}# |
| 272 |
# IMPORTANT NOTICE: This is an automatic conversion which has not |
| 273 |
# been verified! In particular the @DYNINFO sections might need |
| 274 |
# post-editing. Before distributing this file to other people, |
| 275 |
# please review this, amend the comments here to document anything |
| 276 |
# done, and remove this notice. |
| 277 |
#{orig_comments}{atomdb} |
| 278 |
{cell} |
| 279 |
@SPACEGROUP |
| 280 |
{sgno} |
| 281 |
@ATOMPOSITIONS |
| 282 |
""" |
| 283 |
out += out_atompos_lines |
| 284 |
#reduce chemical formula: |
| 285 |
gcd = functools.reduce(math.gcd,[v for k,v in formula_elem2count.items()]) |
| 286 |
for en in formula_elem2count.keys(): |
| 287 |
formula_elem2count[en] //= gcd |
| 288 |
chemform = ''.join(f'{en}{count if count>1 else ""}' for en,count in sorted(formula_elem2count.items())) |
| 289 |
|
| 290 |
assert len(elem2dyninfo)+len(elems_with_fallback_dyninfo) == len(elems_unique) |
| 291 |
for en in elems_unique: |
| 292 |
di = elem2dyninfo.get(en,None) |
| 293 |
fr_str = f'{formula_elem2count[en]}/{len(elems)//gcd}' if len(elems_unique)>1 else '1' |
| 294 |
out += f'@DYNINFO\n element {elemNameRemap(en)}\n fraction {fr_str}\n' |
| 295 |
if di is None: |
| 296 |
out += f' type vdosdebye\n debye_temp {fallback_debye_temp:g} # WARNING: Dummy fall-back value added here!!\n' |
| 297 |
elif isinstance(di,NC.Info.DI_VDOSDebye): |
| 298 |
di.debyeTemperature() |
| 299 |
out += f' type vdosdebye\n debye_temp {di.debyeTemperature():.14g}\n' |
| 300 |
else: |
| 301 |
assert isinstance(di,NC.Info.DI_VDOS) |
| 302 |
out += ' type vdos\n' |
| 303 |
out += NC.formatVectorForNCMAT('vdos_egrid',di.vdosOrigEgrid()) |
| 304 |
out += NC.formatVectorForNCMAT('vdos_density',di.vdosOrigDensity()) |
| 305 |
|
| 306 |
l = list(e.rstrip() for e in out.splitlines()) |
| 307 |
if emitted_warnings: |
| 308 |
l2 = [] |
| 309 |
l2.append( l[0] )#NCMAT vx line |
| 310 |
for w in emitted_warnings: |
| 311 |
l2.append(f'# WARNING: {w}') |
| 312 |
for e in l[1:]: |
| 313 |
l2.append( e ) |
| 314 |
l = l2 |
| 315 |
l.append('') |
| 316 |
return '\n'.join(l) |
| 317 |
|
| 318 |
##TODO: |
| 319 |
#def cif2msd(cif): |
| 320 |
# if any(e!='Uiso' for e in cif.get('_atom_site_thermal_displace_type',[])): |
| 321 |
# return {}#only support Uiso |
| 322 |
# lbls = cif.get('_atom_site_label',[]) |
| 323 |
# uiso = cif.get('_atom_site_U_iso_or_equiv',[]) |
| 324 |
# if lbls and len(lbls) == len(uiso): |
| 325 |
# return dict(zip(lbls,uiso)) |
| 326 |
# return {} |
| 327 |
|
| 328 |
def rawLoadCOD_CifAndStructure(codid): |
| 329 |
import requests |
| 330 |
import pymatgen.core.structure |
| 331 |
import pymatgen.io.cif |
| 332 |
r=requests.get("https://www.crystallography.net/cod/%i.cif"%codid) |
| 333 |
r.raise_for_status()#throw exception in case of e.g. 404 |
| 334 |
cif_obj=pymatgen.io.cif.CifFile.from_string(r.text) |
| 335 |
cif = list(cif_obj.data.items())[0][1].data |
| 336 |
structure = pymatgen.core.structure.Structure.from_str(r.text, fmt="cif") |
| 337 |
return cif,structure |
| 338 |
|
| 339 |
def cif2descr(cif): |
| 340 |
l=[] |
| 341 |
title = cif.get('_publ_section_title','').strip() |
| 342 |
authors = cif.get('_publ_author_name',[]) |
| 343 |
year = cif.get('_journal_year','').strip() |
| 344 |
doi = cif.get('_journal_paper_doi','').strip() |
| 345 |
codid = cif.get('_cod_database_code','').strip() |
| 346 |
if authors: |
| 347 |
if len(authors)==1: |
| 348 |
authors = authors[0] |
| 349 |
elif len(authors)==2: |
| 350 |
authors = f'{authors[0]} and {authors[1]}' |
| 351 |
else: |
| 352 |
authors = f'{authors[0]}, et al.' |
| 353 |
if title: |
| 354 |
l.append(f'"{title}"') |
| 355 |
if authors and year: |
| 356 |
l.append(f'{authors} ({year})') |
| 357 |
if doi: |
| 358 |
l.append(f'DOI: https://dx.doi.org/{doi}') |
| 359 |
if codid: |
| 360 |
l += [ f'Crystallography Open Database entry {codid}', |
| 361 |
f'https://www.crystallography.net/cod/{codid}.html' ] |
| 362 |
return l |
| 363 |
|
| 364 |
def lookupCODStructure(entryid,quiet): |
| 365 |
if not quiet: |
| 366 |
print(f"Querying the Crystallography Open Database for entry {entryid}") |
| 367 |
cif,structure = rawLoadCOD_CifAndStructure(entryid) |
| 368 |
descr = cif2descr(cif) |
| 369 |
url = f'https://www.crystallography.net/cod/{entryid}.html' |
| 370 |
if not any(url in e for e in descr): |
| 371 |
descr += [ f'Crystallography Open Database entry {entryid}', |
| 372 |
f'https://www.crystallography.net/cod/{entryid}.html' ] |
| 373 |
return structure,descr |
| 374 |
|
| 375 |
def lookupMPStructure(entryid,quiet): |
| 376 |
descr=['The Materials Project', |
| 377 |
f'https://www.materialsproject.org/materials/mp-{entryid}'] |
| 378 |
from pymatgen.ext.matproj import MPRester |
| 379 |
if not quiet: |
| 380 |
print(f"Querying the Materials Project for entry {entryid}") |
| 381 |
with MPRester(getMaterialsProjectAPIKEY()) as m: |
| 382 |
structure = m.get_structure_by_material_id("mp-%i"%entryid, |
| 383 |
conventional_unit_cell=True) |
| 384 |
return structure,descr |
| 385 |
|
| 386 |
_keepalive=[] |
| 387 |
def extractDynamics(cfgstr_or_info): |
| 388 |
#returns { 'comments':strlist, 'dyninfos':dyninfos } |
| 389 |
if hasattr(cfgstr_or_info,'dyninfos'): |
| 390 |
cfgstr, info = None, cfgstr_or_info |
| 391 |
else: |
| 392 |
cfgstr = cfgstr_or_info |
| 393 |
info = NC.createInfo(cfgstr) |
| 394 |
|
| 395 |
#DynInfos: |
| 396 |
_keepalive.append(info) |
| 397 |
dyninfos=[ di for di in info.dyninfos |
| 398 |
if ( isinstance(di,NC.Info.DI_VDOS) or isinstance(di,NC.Info.DI_VDOSDebye) ) ] |
| 399 |
|
| 400 |
#Comments: |
| 401 |
comments = [] |
| 402 |
for l in (NC.createTextData(cfgstr) if cfgstr else []): |
| 403 |
l=l.strip() |
| 404 |
if l.startswith('#'): |
| 405 |
comments.append(l[1:]) |
| 406 |
if l.startswith('@'): |
| 407 |
break |
| 408 |
#remove any common leading spaces: |
| 409 |
while ( comments |
| 410 |
and any(e.startswith(' ') for e in comments) |
| 411 |
and all((e.startswith(' ') or not e) for e in comments) ): |
| 412 |
for i in range(len(comments)): |
| 413 |
comments[i] = comments[i][1:] |
| 414 |
return dict( comments = comments, dyninfos=dyninfos ) |
| 415 |
|
| 416 |
def parse_args(): |
| 417 |
descr=""" |
| 418 |
Script which can be used to generate NCMAT files from crystal structures in |
| 419 |
online databases, and optionally also compare existing NCMAT files with online |
| 420 |
structures indicated in their comments. |
| 421 |
|
| 422 |
The script uses the pymatgen (Python Materials Genomics) module to query online |
| 423 |
databases. Currently this means either the Crystallography Open Database |
| 424 |
(https://www.crystallography.net/cod/) or the Materials Project |
| 425 |
(https://www.materialsproject.org/). Access to the Materials Project through |
| 426 |
this script requires an account and associated API key, which can be placed in |
| 427 |
the environment variable MATERIALSPROJECT_USER_API_KEY. |
| 428 |
""" |
| 429 |
parser = argparse.ArgumentParser(description=descr) |
| 430 |
parser.add_argument("--mpid",default=None,type=int, |
| 431 |
help=('Structure ID (integer) of material from the Materials' |
| 432 |
+' Project at https://www.materialsproject.org/.')) |
| 433 |
parser.add_argument("--codid",default=None,type=int, |
| 434 |
help=('Structure ID (integer) of material from the Crystallography' |
| 435 |
+' Open Database (COD) at https://www.crystallography.net/cod/')) |
| 436 |
parser.add_argument("--atomdb",default=None,type=str, |
| 437 |
help=('Use with --mpid or --codid to remap an atom via @ATOMDB "X is ..." ' |
| 438 |
+'syntax. Examples "H is D" and "B is 0.9 B10 0.1 B11". Colons can' |
| 439 |
+' be used in place of spaces if desired.')) |
| 440 |
parser.add_argument('--dynamics','-d',default=None, |
| 441 |
help=('The name of data file from which to copy over dynamics' |
| 442 |
+' information (based on Z-values to accommodate isotopic' |
| 443 |
+' variation). If this argument is not provided, or if a ' |
| 444 |
+'required element is not present in the indicated file, ' |
| 445 |
+'dynamics will be created with a simple Debye temperature' |
| 446 |
+f' of {fallback_debye_temp}K.')) |
| 447 |
parser.add_argument('--output','-o',default=None, |
| 448 |
help=('Name of output file (specify "stdout" to print to stdout). If not' |
| 449 |
+' supplied, a name will be automatically generated.')) |
| 450 |
parser.add_argument("--rawformat",default=False,action='store_true', |
| 451 |
help=('Set to disable the replacement of common fractions in atom positions ' |
| 452 |
+'(e.g. leaving "0.6666667" as it is instead of replacing it with "1/6").')) |
| 453 |
parser.add_argument("--validate",nargs='*',metavar="FILE", |
| 454 |
help=('List of existing NCMAT files which should be compared' |
| 455 |
+' to crystal structures directly taken from online DBs (thus verifying' |
| 456 |
+' that online DB references mentioned in comments in those files are' |
| 457 |
+' actually valid).')) |
| 458 |
parser.add_argument("--pdf",default=False,action='store_true', |
| 459 |
help=(f'Use with --validate to produce PDF file ({pdffn}) rather than interactive plots')) |
| 460 |
|
| 461 |
args=parser.parse_args() |
| 462 |
if args.atomdb and not (args.mpid or args.codid): |
| 463 |
parser.error('--atomdb requires --mpid or --codid') |
| 464 |
if int(args.mpid is not None)+int(args.codid is not None) + int(bool(args.validate)) != 1: |
| 465 |
parser.error('Must specify exactly one of --mpid, --codid, or --validate') |
| 466 |
if args.validate and (args.output or args.mpid or args.codid or args.dynamics): |
| 467 |
parser.error('Do not specify --output, --mpid, --codid, or --dynamics when running with --validate') |
| 468 |
if args.pdf and not args.validate: |
| 469 |
parser.error('Do not specify --pdf without --validate.') |
| 470 |
|
| 471 |
return args |
| 472 |
|
| 473 |
def lookupAndProduce(codid,mpid,dynamics,rawformat,atomdb=None,quiet=False): |
| 474 |
autofn=[] |
| 475 |
if codid: |
| 476 |
structure,descr=lookupCODStructure(codid,quiet=quiet) |
| 477 |
autofn.append(f'cod{args.codid}') |
| 478 |
else: |
| 479 |
structure,descr=lookupMPStructure(mpid,quiet=quiet) |
| 480 |
autofn.append(f'mp{mpid}') |
| 481 |
if atomdb: |
| 482 |
_adb=atomdb.replace(':',' ').split() |
| 483 |
if not len(_adb)>=3 or _adb[1]!='is': |
| 484 |
raise SystemExit(f'Error: Invalid ATOMDB format encountered: "{atomdb}" (supports "X is ..." syntax only)') |
| 485 |
descr[-1] += f' [with {_adb[0]}->{" ".join(_adb[2:])}]' |
| 486 |
autofn.insert(0,f'sg{structure.get_space_group_info()[1]}') |
| 487 |
autofn.insert(0,structure.composition.reduced_formula) |
| 488 |
autofn.insert(0,'autogen') |
| 489 |
out = produceNCMAT(structure,descr, |
| 490 |
dynamics=dynamics, |
| 491 |
rawformat=rawformat, |
| 492 |
atomdb=atomdb, |
| 493 |
quiet=quiet) |
| 494 |
return '_'.join(autofn)+'.ncmat', out |
| 495 |
|
| 496 |
def validate( fn ): |
| 497 |
pass |
| 498 |
|
| 499 |
args=parse_args() |
| 500 |
args.dynamics = extractDynamics(args.dynamics) if args.dynamics else None |
| 501 |
|
| 502 |
try: |
| 503 |
import pymatgen |
| 504 |
except ImportError: |
| 505 |
raise SystemExit('Could not import pymatgen module (perhaps install with "python3 -mpip install pymatgen")') |
| 506 |
import os |
| 507 |
|
| 508 |
if not args.validate: |
| 509 |
assert args.codid or args.mpid |
| 510 |
fn = args.output |
| 511 |
quiet = (fn=='stdout') |
| 512 |
autofn, out = lookupAndProduce( args.codid, |
| 513 |
args.mpid,args. |
| 514 |
dynamics, |
| 515 |
args.rawformat, |
| 516 |
atomdb=args.atomdb, |
| 517 |
quiet = quiet ) |
| 518 |
if not fn: |
| 519 |
fn = autofn |
| 520 |
if not quiet: |
| 521 |
print("Verifying that resulting ncmat data can be loaded") |
| 522 |
NC.directMultiCreate(out,'vdoslux=0;dcutoff=0.3') |
| 523 |
if fn=='stdout': |
| 524 |
print(out,end='') |
| 525 |
else: |
| 526 |
print(f"Writing {fn}") |
| 527 |
pathlib.Path(fn).write_text(out) |
| 528 |
raise SystemExit |
| 529 |
|
| 530 |
_re_atomdbspecs = re.compile("\[ *with ([a-zA-Z ]+)->([ a-zA-Z0-9+-\.]+) *\]") |
| 531 |
def extractAtomDBSpec(s): |
| 532 |
#Look for remapping specs like "[with H->D]" and return in @ATOMDB format |
| 533 |
#(i.e. "H is D"). |
| 534 |
if not '->' in s: |
| 535 |
return |
| 536 |
m = _re_atomdbspecs.search(s) |
| 537 |
return ' '.join(('%s is %s'%m.groups()).split()) if m else None |
| 538 |
|
| 539 |
def extractID(s,pattern): |
| 540 |
if not pattern in s: |
| 541 |
return None |
| 542 |
l=s.split(pattern)[1:] |
| 543 |
while l: |
| 544 |
e,l = l[0],l[1:] |
| 545 |
d='' |
| 546 |
while e and e[0].isdigit(): |
| 547 |
d+=e[0] |
| 548 |
e=e[1:] |
| 549 |
if d and int(d)>0: |
| 550 |
yield int(d) |
| 551 |
|
| 552 |
pdf = None |
| 553 |
if args.pdf: |
| 554 |
import matplotlib |
| 555 |
matplotlib.use('agg') |
| 556 |
try: |
| 557 |
from matplotlib.backends.backend_pdf import PdfPages |
| 558 |
except ImportError: |
| 559 |
raise SystemExit("ERROR: Your installation of matplotlib does not have the required support for PDF output.") |
| 560 |
pdf = PdfPages(pdffn) |
| 561 |
|
| 562 |
import matplotlib.pyplot as plt |
| 563 |
|
| 564 |
for fn in args.validate: |
| 565 |
print(f'Attempting to validate {fn}') |
| 566 |
td = NC.createTextData(fn) |
| 567 |
ids = [] |
| 568 |
for l in td: |
| 569 |
atomdb = extractAtomDBSpec(l) |
| 570 |
for e in extractID(l,'materialsproject.org/materials/mp-'): |
| 571 |
ids.append( dict(dbtype='mp',entryid=e,atomdb=atomdb)) |
| 572 |
for e in extractID(l,'crystallography.net/cod/'): |
| 573 |
ids.append( dict(dbtype='cod',entryid=e,atomdb=atomdb)) |
| 574 |
|
| 575 |
#order-preserving remove duplicates: |
| 576 |
_seen = set() |
| 577 |
newids=[] |
| 578 |
for d in ids: |
| 579 |
key = tuple(sorted((k,v) for k,v in d.items())) |
| 580 |
if key in _seen: |
| 581 |
continue |
| 582 |
newids.append(d) |
| 583 |
_seen.add(key) |
| 584 |
ids = newids |
| 585 |
|
| 586 |
multcreate = lambda data : NC.directMultiCreate(data,cfg_params='inelas=0;incoh_elas=0') |
| 587 |
mc = multcreate(td) |
| 588 |
dynamics = extractDynamics(mc.info) |
| 589 |
cmps = [ (fn, mc ) ] |
| 590 |
for _ in ids: |
| 591 |
dbname = _['dbtype'] |
| 592 |
entryid = _['entryid'] |
| 593 |
atomdb = _['atomdb'] |
| 594 |
lpargs=dict(atomdb=atomdb,dynamics=dynamics,codid=None,mpid=None,rawformat=args.rawformat) |
| 595 |
if dbname=='mp': |
| 596 |
lpargs['mpid']=entryid |
| 597 |
else: |
| 598 |
assert dbname=='cod' |
| 599 |
lpargs['codid']=entryid |
| 600 |
_, out = lookupAndProduce(**lpargs) |
| 601 |
lbl=f'{dbname}-{entryid}' |
| 602 |
if atomdb: |
| 603 |
lbl = f'{lbl} with replacement "{atomdb}"' |
| 604 |
cmps.append( ( lbl, multcreate(out) ) ) |
| 605 |
wlmax = max(1.05*NC.ekin2wl(mc.scatter.domain()[0]) for _,mc in cmps) |
| 606 |
wls = np.linspace(0.001,wlmax,10000) |
| 607 |
if len(cmps)<=1: |
| 608 |
print(f"No online DB IDs found in {fn}") |
| 609 |
continue |
| 610 |
|
| 611 |
for i,(lbl,mc) in enumerate(cmps): |
| 612 |
if '/' in lbl: |
| 613 |
lbl=lbl.split('/')[-1] |
| 614 |
elif lbl.startswith('mp-'): |
| 615 |
lbl = 'Materials Project entry '+lbl[3:] |
| 616 |
elif lbl.startswith('cod-'): |
| 617 |
lbl = 'Crystallography Open Database entry '+lbl[4:] |
| 618 |
#lw=2 if i>0 else 4 |
| 619 |
lw=4 if i>0 else 2 |
| 620 |
if pdf: |
| 621 |
lw *= 0.5 |
| 622 |
args={} |
| 623 |
plt.plot(wls,mc.scatter.xsect(wl=wls), |
| 624 |
label=lbl, |
| 625 |
linewidth=lw, |
| 626 |
alpha=0.5 if i==0 else 0.5, |
| 627 |
color = 'black' if i==0 else None, |
| 628 |
dashes = [] if i==0 else [4 if len(cmps)>2 else 2,2]+[2,2]*i) |
| 629 |
plt.xlim(0.0) |
| 630 |
plt.ylim(0.0) |
| 631 |
plt.title('NB: This compares the crystal structure (space group, lattice, atom positions). Phonons/dynamics always taken from .ncmat file',fontsize=6) |
| 632 |
plt.xlabel('Neutron wavelength (%s)'%(b'\xc3\x85'.decode())) |
| 633 |
plt.ylabel('Coherent elastic cross section (barn)') |
| 634 |
plt.legend(loc='best',handlelength=5) |
| 635 |
plt.grid() |
| 636 |
plt.tight_layout() |
| 637 |
if pdf: |
| 638 |
pdf.savefig() |
| 639 |
plt.close() |
| 640 |
else: |
| 641 |
plt.show() |
| 642 |
|
| 643 |
if pdf: |
| 644 |
pdf.close() |
| 645 |
print("created %s"%pdffn) |