Debian Codegraph @

ncrystal_python/ncrystal_inspectfile

raw
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 ####### Common code for all NCrystal cmdline scripts needing to import NCrystal modules ########
25 import sys
26 pyversion = sys.version_info[0:3]
27 _minpyversion=(3,6,0)
28 if pyversion < _minpyversion:
29 raise SystemExit('Unsupported python version %i.%i.%i detected (needs %i.%i.%i or later).'%(pyversion+_minpyversion))
30 import os
31 import pathlib
32
33 def maybeThisIsConda():
34 return ( os.environ.get('CONDA_PREFIX',None) or
35 os.path.exists(os.path.join(sys.base_prefix, 'conda-meta')) )
36
37 def fixSysPathAndImportNCrystal( *, allowfail = False ):
38 thisdir = pathlib.Path( __file__ ).parent
39 def extract_cmake_pymodloc():
40 p = thisdir / 'ncrystal-config'
41 if not p.exists():
42 return
43 with p.open('rt') as fh:
44 for i,l in enumerate(fh):
45 if i==30:
46 break
47 if l.startswith('#CMAKE_RELPATH_TO_PYMOD:'):
48 l = l[24:].strip()
49 return ( thisdir / l ) if l else None
50 pml = extract_cmake_pymodloc()
51 hack_syspath = pml and ( pml / 'NCrystal' / '__init__.py' ).exists()
52 if hack_syspath:
53 sys.path.insert(0,str(pml.absolute().resolve()))
54 try:
55 import NCrystal
56 except ImportError:
57 if allowfail:
58 return
59 msg = 'ERROR: Could not import the NCrystal Python module'
60 if maybeThisIsConda():
61 msg += ' (if using conda it might help to close your terminal and activate your environment again)'
62 elif not hack_syspath:
63 msg += ' (perhaps your PYTHONPATH is misconfigured)'
64 raise SystemExit(msg)
65 return NCrystal
66 ################################################################################################
67 NC = fixSysPathAndImportNCrystal()
68
69 #########################################################################
70 ########################### System setup ################################
71 #########################################################################
72
73 import argparse
74 import math
75
76 #in unit tests we dont display interactive images and we reduce cpu consumption
77 #by watching for special env var:
78 _unittest = bool(os.environ.get('NCRYSTAL_INSPECTFILE_UNITTESTS',''))
79
80 #Function for importing required python modules which may be missing, to provide
81 #a somewhat more helpful error to the user:
82 def import_optpymod(name):
83 import importlib
84 try:
85 themod = importlib.import_module(name)
86 except ImportError:
87 msg = 'ERROR: Could not import a required python module: %s'%name
88 if maybeThisIsConda() and name in ('matplotlib','numpy'):
89 msg += ' (looks like you are using conda so you might solve this by running "conda install %s")'%name
90 raise SystemExit(msg)
91 return themod
92
93
94 #########################################################################
95 #########################################################################
96 #########################################################################
97
98 def parse_cmdline():
99 descr="""
100
101 The most common usage of this tool is to load input data (usually .ncmat files)
102 with NCrystal (v%s) and plot resulting isotropic cross sections for thermal
103 neutrons. This is done by specifying one or more configurations ("cfg-strings"),
104 which indicates data names (e.g. file names) and optionally cfg parameters
105 (e.g. temperatures). Specifying more than one configuration, results in a single
106 comparison plot of the total scattering cross section based on the different
107 materials. Specifying just a single file, results in a more detailed cross
108 section plot as well as a 2D plot of generated scatter angles. Other behaviours
109 can be obtained by specifying flags as indicated below.
110
111 """%NC.__version__
112
113 descr=descr.strip()
114
115 epilog="""
116 examples:
117 $ %(prog)s Al_sg225.ncmat
118 plot aluminium cross sections and scatter-angles versus neutron wavelength.
119 $ %(prog)s Al_sg225.ncmat Ge_sg227.ncmat --common temp=200
120 cross sections for aluminium and germanium at T=200K
121 $ %(prog)s "Al_sg225.ncmat;dcutoff=0.1" "Al_sg225.ncmat;dcutoff=0.4" "Al_sg225.ncmat;dcutoff=0.8"
122 effect of d-spacing cut-off on aluminium cross sections
123 $ %(prog)s "Al_sg225.ncmat;temp=20" "Al_sg225.ncmat;temp=293.15" "Al_sg225.ncmat;temp=600"
124 effect of temperature on aluminium cross sections
125 $ %(prog)s "phases<0.65*Al_sg225.ncmat&0.35*MgO_sg225_Periclase.ncmat>;temp=100K"
126 investigate multiphase material at 100K"""
127
128 parser = argparse.ArgumentParser(description=descr,
129 epilog=epilog,
130 formatter_class=argparse.RawDescriptionHelpFormatter)
131 parser.add_argument('input_cfgs', metavar='CFGSTR', type=str, nargs='*',
132 help="""Input data (cfg-strings) to investigate. This
133 can just be simple file-names or full-blown cfg-strings
134 in the usual NCrystal syntax (see also examples
135 below).""")
136 parser.add_argument('--version', action='version', version=str(NC.__version__))
137 parser.add_argument('-d','--dump', action='count',default=0,
138 help='Dump derived information rather than displaying plots. Specify multiple times to increase verbosity.')
139 parser.add_argument('--common','-c', metavar='CFG', type=str, default=[],
140 help='Common configuration items that will be applied to all input cfg strings',action='append')
141 parser.add_argument('--coh_elas','--bragg', action='store_true',
142 help="""Only generate coherent-elastic (Bragg diffraction) component""")
143 parser.add_argument('--incoh_elas', action='store_true',
144 help="""Only generate incoherent-elastic component""")
145 parser.add_argument('--sans', action='store_true',
146 help="""Only generate SANS component""")
147 parser.add_argument('--elastic', action='store_true',
148 help="""Only generate elastic components (including SANS)""")
149 parser.add_argument('--inelastic', action='store_true',
150 help="""Only generate inelastic components""")
151 parser.add_argument('-a','--absorption', action='store_true',
152 help="""Include absorption in cross section plots""")
153 parser.add_argument('--phases', action='store_true',
154 help="""Show cross section breakdown of a single multiphase material by phase rather than physics process""")
155 parser.add_argument('-x','--xrange', type=str,nargs='?',
156 help='Override plot range, e.g. "1e-5:1e2" or "0:10"')
157 parser.add_argument('--logy', action='store_true',
158 help='Force y-axis to use logarithmic scale.')
159 parser.add_argument('--liny', action='store_true',
160 help='Force y-axis to use linear scale.')
161 parser.add_argument('-e','--energy', action='store_true',
162 help="""Show plots versus neutron energy rather than wavelength""")
163 parser.add_argument('-p','--pdf', action='store_true',
164 help="""Generate PDF file rather than launching an interactive plot viewer.""")
165 parser.add_argument('--test', action='store_true',
166 help="""Perform quick validation of NCrystal installation.""")
167 parser.add_argument('--doc', action='count',default=0,
168 help="""Print documentation about the available cfg-str variables. Specify twice for more detailed help.""")
169 dpi_default=200
170 parser.add_argument('--dpi', default=-1,type=int,
171 help="""Change plot resolution. Set to 0 to leave matplotlib defaults alone.
172 (default value is %i, or whatever the NCRYSTAL_DPI env var is set to)."""%dpi_default)
173 parser.add_argument('--cfg',action='store_true',
174 help='Print normalised cfg-string and dump meta-data about loaded physics processes.')
175 parser.add_argument('--plugins', action='store_true',
176 help='List currently enabled loaded plugins.')
177 parser.add_argument('-b','--browse', action='store_true',
178 help='List data available in standard locations (e.g. the files in the current directory or search path)')
179 parser.add_argument('--extract', type=str, default=None, metavar="DATANAME",
180 help='''Extract contents of DATANAME (e.g. a file name) using the same lookup mechanism as used for data
181 specified in NCrystal cfg strings. This can therefore also be used to inspect
182 in-memory (or on-demand created) data.''')
183
184 args=parser.parse_args()
185
186 if args.logy and args.liny:
187 parser.error('Do not specify both --liny and --logy')
188 if not args.logy and not args.liny:
189 args.logy = args.energy
190
191 if args.xrange:
192 try:
193 _=args.xrange.split(':')
194 if not len(_)==2:
195 raise ValueError
196 _ = ( float(_[0]), float(_[1]) )
197 if not ( _[0]>=0.0 and _[1]>_[0]):
198 raise ValueError
199 except ValueError:
200 parser.error(f'Invalid --xrange argument: "{args.xrange}"')
201 args.xrange = _
202
203 has_single_cfgstr = args.input_cfgs and len(args.input_cfgs)==1
204 if args.cfg and not has_single_cfgstr:
205 parser.error('Option --cfg requires exactly one cfg-string to be specified.')
206
207 if args.phases and not has_single_cfgstr:
208 parser.error('Option --phase requires exactly one cfg-string to be specified.')
209
210 if args.dump and not has_single_cfgstr:
211 parser.error('Option --dump requires exactly one cfg-string to be specified.')
212
213 if args.extract or args.plugins or args.doc or args.browse:
214 return args
215
216 if args.dpi>3000:
217 parser.error('Too high DPI value requested.')
218
219 if args.dpi==-1:
220 _=os.environ.get('NCRYSTAL_DPI',None)
221 if _:
222 try:
223 _=int(_)
224 if _<0:
225 raise ValueError
226 except ValueError:
227 print("ERROR: NCRYSTAL_DPI environment variable must be set to integer >=0")
228 raise SystemExit
229 if _>3000:
230 parser.error('Too high DPI value requested via NCRYSTAL_DPI environment variable.')
231 args.dpi=_
232 else:
233 args.dpi=dpi_default
234
235 if args.test:
236 if any((args.cfg,args.input_cfgs,args.dump,args.coh_elas,args.incoh_elas,args.sans,args.elastic,args.inelastic,args.absorption,args.pdf,args.phases)):
237 parser.error('Do not specify other arguments with --test.')
238
239 ncomp_select = sum((1 if _ else 0) for _ in (args.coh_elas,args.incoh_elas,args.sans,args.elastic,args.inelastic))
240 if ncomp_select > 1:
241 parser.error('Do not specify more than one of: --coh_elas/--bragg, --incoh_elas, --sans, --elastic or --inelastic.')
242
243 if args.coh_elas: args.comp = 'coh_elas'
244 elif args.incoh_elas: args.comp = 'incoh_elas'
245 elif args.sans: args.comp = 'sans'
246 elif args.elastic: args.comp = 'elastic'
247 elif args.inelastic: args.comp = 'inelastic'
248 else: args.comp = 'all'
249
250 if args.absorption and ncomp_select>0:
251 parser.error('Do not specify --absorption with either of: --coh_elas/--bragg, --incoh_elas, --sans, --elastic or --inelastic.')
252
253 if args.dump and (ncomp_select>0 or args.absorption):
254 parser.error('Do not specify --dump with either of: --coh_elas/--bragg, --incoh_elas, --sans, --elastic, --inelastic or --absorption.')
255
256 if args.dump and len(args.input_cfgs)>1:
257 parser.error('Do not specify more than one input cfg string with --dump [-d].')
258
259 args.common=';'.join(args.common)
260 return args
261
262 def create_ekins(npoints,range_override):
263 if range_override:
264 if range_override[0]<=0.0:
265 range_override = ( range_override[1]*1e-10, range_override[1] )
266 return NC._np_geomspace(*range_override,npoints)
267 else:
268 return NC._np_geomspace(1e-5,1e2,npoints)
269
270 def create_wavelengths(np,cfgs,npoints,range_override):
271 if range_override:
272 wls_min,wls_max = range_override
273 else:
274 bragg_thresholds = [c.braggthreshold() or 0.0 for c in cfgs]
275 fallback = 10.0#materials with no bragg threshold
276 max_bragg_threshold = ( max(bragg_thresholds) if bragg_thresholds else None ) or fallback
277 wls_max = 1.2 * ( float(int(max_bragg_threshold*1.01+1.0)) if not math.isinf(max_bragg_threshold) else fallback )
278 wls_min = 1e-4
279 return NC._np_linspace( wls_min, wls_max, npoints )
280
281 _mpldpi=[None]
282 _pdffilename='ncrystal.pdf'
283 _npplt = None
284 def import_npplt(pdf=False):
285 global _npplt
286 if _npplt:
287 #pdf par must be same as last call:
288 assert bool(pdf)==bool(_npplt[2] is not None)
289 return _npplt
290 np = import_optpymod('numpy')
291 mpl = import_optpymod('matplotlib')
292 ##Commenting checks below since mpl.compare_versions is deprecated, and I am anyway not sure exactly which versions we support:
293 ##if not mpl.compare_versions(mpl.__version__, '0.99.1.1'):
294 ## raise SystemExit("ERROR: Your version of matplotlib (%s) is too ancient to work - aborting plotting!"%mpl.__version__)
295 ##if not mpl.compare_versions(mpl.__version__, '1.3'):
296 ## if not _unittest:
297 ## print("WARNING: Your version of matplotlib (%s) is unsupported - expect trouble! (needs at least version 1.3)."%mpl.__version__)
298
299 if _mpldpi[0]:
300 mpl.rcParams['figure.dpi']=_mpldpi[0]
301
302 #ability to quit plot windows with Q:
303 if 'keymap.quit' in mpl.rcParams and not 'q' in mpl.rcParams['keymap.quit']:
304 mpl.rcParams['keymap.quit'] = tuple(list(mpl.rcParams['keymap.quit'])+['q','Q'])
305
306 if _unittest or pdf:
307 mpl.use('agg')
308 if pdf:
309 try:
310 from matplotlib.backends.backend_pdf import PdfPages
311 except ImportError:
312 raise SystemExit("ERROR: Your installation of matplotlib does not have the required support for PDF output.")
313 plt = import_optpymod('matplotlib.pyplot')
314
315 _npplt = (np,plt,PdfPages(_pdffilename) if pdf else None)
316 return _npplt
317
318 #functions for creating labels and title:
319
320 def _remove_common_keyvals(dicts):
321 """remove any key from the passed dicts which exists with identical value in all
322 the dicts. Returns a single dictionary with entries thus removed."""
323 sets=[set((k,v) for k,v in list(d.items())) for d in dicts]
324 common = dict(set.intersection(*sets)) if sets else {}
325 for k in list(common.keys()):
326 for d in dicts:
327 d.pop(k,None)
328 return common
329
330 def _serialise_cfg(part):
331 #transform to list of tuples [(key,value),..] where entries can be
332 #(parname,value) or compname/filename.
333
334 mpstart = 'phases<'
335 if part._cfg.cfgstr.startswith(mpstart):
336 assert part._cfg.cfgstr.count('>')==1
337 _=part._cfg.cfgstr[7:].split('>')
338 main,trailing_common_cfg = _ if len(_)>1 else (_[0],'')
339 else:
340 _=part._cfg.cfgstr.split(';',1)
341 main,trailing_common_cfg = _ if len(_)>1 else (_[0],'')
342 l = [ ('[FILENAME]', main.strip() ), #using '[]' in special keys avoids clashes
343 ('[COMPNAME]', part._compname ) ] #(cfg strs can't contain such chars)
344 for e in trailing_common_cfg.split(';'):
345 e=e.strip()
346 if e == 'ignorefilecfg':
347 raise SystemExit('ERROR: The ignorefilecfg keyword is no longer supported')
348 elif e:
349 k,v=e.split('=')
350 l.append( (k.strip(),v.strip()) )
351 return l
352
353 def _classify_differences(parts):
354 l=[]
355 for p in parts:
356 l.append( dict(_serialise_cfg(p)) )
357 common = _remove_common_keyvals(l)
358 return common,l
359
360 def _cfgdict_to_str(cfgdict):
361 fn = cfgdict.pop('[FILENAME]','')
362 if '*' in fn:
363 #multiphase, fix up a bit
364 _=''
365 for phase in fn.split('&'):
366 fraction,phcfg = phase.split('*')
367 if _:
368 _ += ' + '
369 multsymb = '\u00D7'
370 _ += '%s%s(%s)'%(fraction,multsymb,phcfg)
371 fn = '{%s}'%_
372 o = [fn] if fn else []
373 cn = cfgdict.pop('[COMPNAME]','')
374 if cfgdict:
375 o += [', '.join('%s=%s'%(k,v) for k,v in sorted(cfgdict.items()))]
376 if cn:
377 o += [ { 'coh_elas':'Coherent elastic',
378 'incoh_elas':'Incoherent elastic',
379 'elastic':'Elastic',
380 'inelastic':'Inelastic',
381 'sans':'SANS',
382 'absorption':'Absorption',
383 'all':'Total scattering',
384 'scattering+absorption':'Total scattering+Absorption'}[cn] ]
385 return ' '.join(b%a for a,b in zip(o,['%s','[%s]','(%s)']))
386
387 def create_title_and_labels(parts):
388 partscfg_common,partscfg_unique = _classify_differences(parts)
389 return _cfgdict_to_str(partscfg_common),[(_cfgdict_to_str(uc) or 'default') for uc in partscfg_unique]
390
391 def _end_plot(plt,pdf):
392 if _unittest:
393 plt.savefig(open(os.devnull,'wb'),format='raw',dpi=10)
394 plt.close()
395 elif pdf:
396 pdf.savefig()
397 plt.close()
398 else:
399 plt.show()
400
401 def comp2cfgpars(comp):
402 assert comp in ('coh_elas','incoh_elas','elastic','inelastic','sans','all')
403 return { 'coh_elas' : 'incoh_elas=0;inelas=0;sans=0',
404 'incoh_elas' : 'coh_elas=0;inelas=0;sans=0',
405 'elastic' : 'inelas=0',
406 'inelastic' : 'elas=0',
407 'sans' : 'coh_elas=0;incoh_elas=0;inelas=0',
408 'all' : '' }[comp]
409
410 def plot_xsect(cfgs,comp,absorption,pdf,versus_energy,xrange,logy,breakdown_by_phases):
411 assert comp in ('coh_elas','incoh_elas','elastic','inelastic','sans','all')
412 assert not absorption or comp=='all'
413 scalefactors = None
414
415 if breakdown_by_phases:
416 assert len(cfgs)==1
417 if cfgs[0].nPhases()==0:
418 print("WARNING: --phases ignored for a single phase material")
419 breakdown_by_phases = False
420 else:
421 mothercfg = cfgs[0]
422 scalefactors = list(mothercfg.getChildPhaseNumberFraction(i) for i in range(mothercfg.nPhases()))
423 assert abs(sum(scalefactors)-1.0)<1e-10
424 cfgs = list(mothercfg.getChildPhaseCfg(i) for i in range(mothercfg.nPhases()))
425
426 np,plt,pdf = import_npplt(pdf)
427 if versus_energy:
428 plt.xlabel('Neutron energy [eV]')
429 else:
430 plt.xlabel('Neutron wavelength [angstrom]')
431 plt.ylabel('Cross section [barn/atom]')
432 if len(cfgs)==1 and comp in ('all','elastic'):
433 if comp=='all':
434 parts=[cfgs[0].get_scatter('coh_elas'),cfgs[0].get_scatter('incoh_elas'),
435 cfgs[0].get_scatter('inelastic'),cfgs[0].get_scatter('sans')]
436 else:
437 assert comp=='elastic'
438 parts=[cfgs[0].get_scatter('coh_elas'),cfgs[0].get_scatter('incoh_elas'),cfgs[0].get_scatter('sans')]
439 if absorption:
440 assert comp=='all'
441 parts += [cfgs[0].get_absorption()]
442 else:
443 if absorption:
444 assert comp=='all'
445 parts=[c.get_totalxsect() for c in cfgs]
446 else:
447 parts=[c.get_scatter(comp) for c in cfgs]
448
449 if breakdown_by_phases:
450 sc_sans = mothercfg.get_scatter('sans')
451 if not sc_sans._nullprocess:
452 scalefactors += [1.0]
453 parts += [sc_sans]
454
455 if not breakdown_by_phases:
456 #trim unused process types (but always show all in case of breakdown_by_phases):
457 parts = [p for p in parts if not p._nullprocess]
458
459 if not breakdown_by_phases:
460 title,labels = create_title_and_labels(parts)
461 if len(set(labels))!=len(labels):
462 print("WARNING: Comparing identical setups?")
463 else:
464 title,labels = create_title_and_labels(parts)
465
466 npts = 3000
467 if versus_energy:
468 ekins = create_ekins(npts,xrange)
469 else:
470 wavelengths = create_wavelengths(np,cfgs,npts,xrange)
471 ekins = NC.wl2ekin(wavelengths)
472 need_tot = (len(cfgs)==1 and len(parts)>1) or breakdown_by_phases
473 xsects_tot = None
474 max_len_label = 0
475
476 #colors inspired by http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
477 col_red = "#F15854"
478 partcols = [
479 "#5DA5DA", # (blue)
480 "#FAA43A", # (orange)
481 "#60BD68", # (green)
482 #"#B2912F", # (brown)
483 "#B276B2", # (purple)
484 #"#DECF3F", # (yellow)
485 #"#F17CB0", # (pink)
486 "#4D4D4D", # (gray)
487 ]
488 if not need_tot:
489 partcols = [col_red]+partcols
490
491 linewidth = 2.0
492
493 xvar = ekins if versus_energy else wavelengths
494
495 ydatarange = {}
496 def update_ydatarange(xsects):
497 ynz = xsects[np.nonzero(xsects)]
498 y0nonzero,y0,y1 = ( ynz.min() if len(ynz) else None), xsects.min(), xsects.max()
499 if y0 < ydatarange.get('ymin',float('inf')):
500 ydatarange['ymin'] = y0
501 if y0nonzero is not None and y0nonzero < ydatarange.get('ymin_nonzero',float('inf')):
502 ydatarange['ymin_nonzero'] = y0nonzero
503 if y1 > ydatarange.get('ymax',float('-inf')):
504 ydatarange['ymax'] = y1
505
506 for ipart,part in enumerate(parts):
507 cfg = part._cfg
508 compname = part._compname
509 if part.isOriented():
510 raise SystemExit("ERROR: This script can not produce quick cross-section plots for oriented processes (but you can still inspect the material with --dump)")
511 xsects = part.crossSectionIsotropic(ekins)
512 if scalefactors is not None:
513 xsects *= scalefactors[ipart]
514 if need_tot:
515 if xsects_tot is None:
516 xsects_tot = np.zeros(len(xsects))
517 xsects_tot += xsects
518 label=labels[ipart]
519 max_len_label = max(max_len_label,len(label))
520 ls={0:'-',1:'--',2:':'}.get(ipart//len(partcols),'-.')
521 plt.plot(xvar,xsects,label=label,color=partcols[ipart%len(partcols)],lw=linewidth,ls=ls)
522 update_ydatarange(xsects)
523 if need_tot:
524 if comp=='all' and len(cfgs)==1 and not breakdown_by_phases:
525 #sanity check
526 if absorption:
527 xsects_tot_direct = cfgs[0].get_totalxsect().crossSectionIsotropic(ekins)
528 else:
529 xsects_tot_direct = cfgs[0].get_scatter('all').crossSectionIsotropic(ekins)
530 xsects_discrepancy = xsects_tot_direct-xsects_tot
531 discr_lvl = max(abs(xsects_discrepancy))
532 if discr_lvl > 1e-10:
533 print("WARNING: Discrepancy in breakdown into components detected (at the"
534 +f" {discr_lvl} level)!! Some plugins might be incorrectly programmed.")
535 plt.plot(xvar,xsects_discrepancy,
536 label='WARNING: Discrepancy!',
537 color="cyan",lw=linewidth)
538
539 update_ydatarange(xsects_tot)
540 plt.plot(xvar,xsects_tot,
541 label={'all':'Total','elastic':'Total elastic'}[comp],
542 color="#F15854",lw=linewidth)#red-ish colour (see above)
543 leg_fsize = 'large'
544 if max_len_label > 40: leg_fsize = 'medium'
545 if max_len_label > 60: leg_fsize = 'small'
546 if max_len_label > 80: leg_fsize = 'smaller'
547 try:
548 if len(parts)>1:
549 leg=plt.legend(loc='best',fontsize=leg_fsize)
550 if hasattr(leg,'set_draggable'):
551 leg.set_draggable(True)
552 else:
553 leg.draggable(True)
554 except TypeError:
555 plt.legend(loc='best')
556 plt.grid()
557 single_yval = bool(ydatarange.get('ymin','n/a')==ydatarange.get('ymax','n/a'))
558 if single_yval and ydatarange.get('ymin','n/a')==0.0:
559 if logy:
560 print('WARNING: Could not set log scale since curves are 0.0 everywhere')
561 plt.gca().set_ylim(0.0,1.0)
562 elif logy:
563 if ydatarange.get('ymin',1.0) <= 0.0:
564 _=ydatarange.get('ymin_nonzero',ydatarange.get('ymax',1.0)*1e-10)
565 if _:
566 plt.gca().set_ylim(_,None)
567 plt.gca().set_yscale('log')
568 else:
569 plt.gca().set_ylim(0,None)
570
571 if versus_energy:
572 plt.gca().set_xlim(ekins[0],ekins[-1])
573 plt.gca().set_xscale('log')
574 else:
575 if wavelengths[0]*100<wavelengths[-1]:
576 plt.gca().set_xlim(0.0,wavelengths[-1])
577 else:
578 plt.gca().set_xlim(wavelengths[0],wavelengths[-1])
579 if title:
580 if len(title)>30:
581 plt.title(title,fontsize='smaller')
582 else:
583 plt.title(title)
584 _end_plot(plt,pdf)
585
586 def plot_2d_scatangle(cfg,comp,pdf,versus_energy,xrange):
587 assert comp in ('coh_elas','incoh_elas','elastic','inelastic','sans','all')
588 part=cfg.get_scatter(comp)
589
590 np,plt,pdf = import_npplt(pdf)
591
592 #reproducible plots:
593 import random
594 random.seed(123456)
595
596 #higher granularity wavelengths than for 1D plot to avoid artifacts:
597 npts = 100 if _unittest else 30000
598 if versus_energy:
599 ekins = create_ekins(npts,xrange)
600 else:
601 wavelengths = create_wavelengths(np,[cfg],npts,xrange)
602 ekins = NC.wl2ekin(wavelengths)
603
604 #get title (label should be uninteresting for a single part):
605 title,labels = create_title_and_labels([part])
606
607 #First figure out how many points to put at each wavelength (or energy)
608 if not part._nullprocess:
609 xsects = part.crossSectionIsotropic(ekins)
610 n2d = 100 if _unittest else 25000
611 sumxs = np.sum(xsects)
612 if sumxs:
613 n_at_xvar = np.random.poisson(xsects*n2d/np.sum(xsects))
614 else:
615 n_at_xvar = np.zeros(len(xsects))
616 else:
617 n_at_xvar = np.zeros(len(wavelengths))
618
619 xvar = ekins if versus_energy else wavelengths
620
621 n2d=int(np.sum(n_at_xvar))#correction for random fluctuations
622 if n2d>0:
623 plot_angles = np.zeros(n2d)
624 plot_xvar = np.zeros(n2d)
625 j = 0
626 for i,n in enumerate(n_at_xvar):
627 i,n = int(i),int(n)
628 evalue = xvar[i] if versus_energy else NC.wl2ekin(xvar[i])
629 ekinfinal,mu = part.sampleScatterIsotropic(evalue,repeat=int(n))
630 plot_angles[j:j+n] = np.arccos(mu)
631 plot_xvar[j:j+n].fill(xvar[i])
632 j+=n
633 plot_angles *= (180./np.pi)
634 else:
635 plot_angles = None
636 plot_xvar = None
637
638 if plot_xvar is not None:
639 try:
640 plt.scatter(plot_xvar,plot_angles,alpha=0.2,marker='.',edgecolor=None,color='black',s=2,zorder=1)
641 except ValueError:
642 plt.scatter(plot_xvar,plot_angles,alpha=0.2,edgecolor=None,color='black',s=2,zorder=1)
643
644 if versus_energy:
645 plt.gca().set_xlim(ekins[0],ekins[-1])
646 plt.gca().set_xscale('log')
647 else:
648 if wavelengths[0]*100<wavelengths[-1]:
649 plt.gca().set_xlim(0.0,wavelengths[-1])
650 else:
651 plt.gca().set_xlim(wavelengths[0],wavelengths[-1])
652 plt.gca().set_ylim(0,180)
653 if versus_energy:
654 plt.xlabel('Neutron energy [eV]')
655 else:
656 plt.xlabel('Neutron wavelength [angstrom]')
657 plt.ylabel('Scattering angle [degrees]')
658 if title:
659 plt.title(title)
660 plt.grid()
661 _end_plot(plt,pdf)
662
663 class XSSum:
664 #Combine scatter+absorption processes (hence no sampleScatterIsotropic method).
665 def __init__(self,*processes):
666 self._p = processes[:]
667 def crossSectionIsotropic(self,ekin):
668 return sum(p.crossSectionIsotropic(ekin) for p in self._p)
669 def isOriented(self):
670 return any(p.isOriented() for p in self._p)
671
672 class Cfg:
673 def __init__(self,cfgstr, commoncfgstr):
674 self._cfgstr = NC.normaliseCfg('%s;%s'%(cfgstr,commoncfgstr))
675 self._sc = {}
676 self._abs = None
677 self._totxs = None
678 self._info = None
679 self._bt = 'not_init'
680 self._iphase = None
681
682 def nPhases(self):
683 return len(self.get_info().phases)
684
685 def getChildPhaseCfg(self,iphase):
686 assert( iphase < self.nPhases() )
687 childcfg = Cfg( self._cfgstr,'phasechoice=%i'%iphase )
688 childcfg._iphase = iphase
689 return childcfg
690
691 def getChildPhaseNumberFraction(self,iphase):
692 #fraction of atoms in phase
693 i = self.get_info()
694 i.numberdensity;
695 volfrac,iph = i.phases[iphase]
696 return volfrac*iph.numberdensity / i.numberdensity
697
698 def braggthreshold(self):
699 """in Aa (or None). Largest BT value for any crystalline phase."""
700 if self._bt != 'not_init':
701 return self._bt
702 def largestbtrecursive(info):
703 if info.isSinglePhase():
704 return info.braggthreshold
705 bts = [ largestbtrecursive(ph[1]) for ph in info.phases ]
706 bts = [ e for e in bts if e ]
707 return max(bts) if bts else None
708 self._bt = largestbtrecursive( self.get_info() )
709 return self._bt
710
711 def get_scatter(self,comp = 'all', allowfail = False):
712 if not comp in self._sc:
713 extra_cfg = comp2cfgpars(comp)
714 cstr = ';'.join([self._cfgstr,extra_cfg])
715 try:
716 sc = NC.createScatter(cstr)
717 except NC.NCException:
718 if allowfail:
719 return None
720 else:
721 raise
722 sc._nullprocess = sc.isNull()
723 sc._cfg = self
724 sc._compname = comp
725 self._sc[comp] = sc
726 return self._sc[comp]
727
728 def get_absorption(self):
729 if not self._abs:
730 a = NC.createAbsorption(self._cfgstr)
731 a._nullprocess = a.isNull()
732 a._cfg = self
733 a._compname = 'absorption'
734 self._abs = a
735 return self._abs
736
737 def get_totalxsect(self):
738 if not self._totxs:
739 a,s = self.get_absorption(),self.get_scatter('all')
740 t = XSSum(a,s)
741 t._nullprocess = a._nullprocess and s._nullprocess
742 t._cfg = self
743 t._compname = 'scattering+absorption'
744 self._totxs = t
745 return self._totxs
746
747 def get_info(self):
748 if not self._info:
749 self._info = NC.createInfo(self._cfgstr)
750 return self._info
751
752 @property
753 def cfgstr(self):
754 return self._cfgstr
755
756 def main():
757 args = parse_cmdline()
758
759 if args.doc:
760 full = (args.doc >= 2)
761 print(NC.generateCfgStrDoc( 'txt_full' if full else 'txt_short' ),end='')
762 if not full:
763 print("NOTE: Condensed output generated. Specify --doc twice for more details.")
764 raise SystemExit
765
766 if args.extract:
767 s = NC.createTextData(args.extract).rawData
768 if s is None:
769 raise SystemExit('Error: unknown file "%s"'%args.extract)
770 print(s,end='')
771 raise SystemExit
772
773 if args.plugins:
774 NC.browsePlugins(dump=True)
775 raise SystemExit
776
777 if args.browse:
778 NC.browseFiles(dump=True)
779 raise SystemExit
780
781 if args.test:
782 NC.test()
783 raise SystemExit
784
785 if args.cfg or ( len(args.input_cfgs)==1 and not args.dump ):
786 #Dump cfg debug info if requested or running with just 1 file.
787 assert len(args.input_cfgs)==1
788 origcfg=args.input_cfgs[0]
789 if args.common:
790 origcfg += f';{args.common}'
791 print(f'==> Debugging cfg-string: "{origcfg}"')
792 _ = comp2cfgpars(args.comp)
793 if _:
794 assert args.comp != 'all'
795 print(f'==> Adding due to --{args.comp} flag specified: "{_}"')
796 origcfg += ';' + _
797 normcfg = NC.normaliseCfg(origcfg)
798 print(f'==> Normalised cfg-string : "{normcfg}"')
799 abs_obj=NC.createAbsorption(normcfg)
800 sc_obj = NC.createScatter(normcfg)
801 print( '==> Absorption process (code level objects):')
802 proc_a = abs_obj
803 proc_a.dump(' '*27)
804 print( '==> Scattering process (code level objects):')
805 proc_s = sc_obj
806 proc_s.dump(' '*27)
807 if args.cfg:
808 raise SystemExit(0)
809
810 _mpldpi[0] = args.dpi
811
812 cfgs=[Cfg(e,args.common) for e in args.input_cfgs]
813 cfgs_normalisedstrings = [c.cfgstr for c in cfgs]
814 for cstr in set(cfgs_normalisedstrings):
815 if cfgs_normalisedstrings.count(cstr)!=1:
816 print("WARNING: Configuration specified more than once: \"%s\""%cstr)
817 if args.dump:
818 assert len(cfgs)==1
819 cfgs[0].get_info().dump(verbose = int(args.dump)-1 )
820 return
821 if not cfgs:
822 raise SystemExit('Error: nothing selected. Please run with --help for usage instructions.')
823
824 plot_xsect( cfgs, comp = args.comp, absorption = args.absorption, pdf=args.pdf,
825 versus_energy=args.energy, xrange = args.xrange, logy = args.logy,
826 breakdown_by_phases = args.phases )
827 if len(cfgs)==1 and not bool(os.environ.get('NCRYSTAL_INSPECTFILE_NO2DSCATTER',0)):
828 plot_2d_scatangle( cfgs[0], comp = args.comp, pdf=args.pdf, versus_energy=args.energy, xrange = args.xrange )
829 if args.pdf:
830 _,_,pdf = import_npplt(True)
831 import datetime
832 try:
833 d = pdf.infodict()
834 except AttributeError:
835 d={}
836 d['Title'] = 'Plots made with NCrystal-inspectfile from file%s %s'%('' if len(args.input_cfgs)==1 else 's',
837 ','.join(os.path.basename(f) for f in args.input_cfgs))
838 d['Author'] = 'NCrystal %s (via inspectfile)'%NC.__version__
839 d['Subject'] = 'NCrystal plots'
840 d['Keywords'] = 'NCrystal'
841 d['CreationDate'] = datetime.datetime.today()
842 d['ModDate'] = datetime.datetime.today()
843 pdf.close()
844 print("created %s"%_pdffilename)
845
846 if __name__=='__main__':
847 main()
848
849 # TODO:
850 # - allow tuning of n2d and alpha pars for 2D plot?
851 # - show hkl values in 1d and 2d plot?
852 # - option to show mfp rather than xsect?
853 # - deltaE/wl_out plots as well (todo). Perhaps --wl=... option, resulting in plots for that wl.