Debian Codegraph @

ncrystal_python/ncrystal_ncmat2hkl

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
25 Script which can be used to create input files with reflections for McStas
26 crystalline sample components like PowderN and Single_crystal, based on NCrystal
27 cfg-strings (usually referring to NCMAT files with crystalline single-phase
28 materials).
29
30 """
31
32 ################################################################################################
33 ####### Common code for all NCrystal cmdline scripts needing to import NCrystal modules ########
34 import sys
35 pyversion = sys.version_info[0:3]
36 _minpyversion=(3,6,0)
37 if pyversion < _minpyversion:
38 raise SystemExit('Unsupported python version %i.%i.%i detected (needs %i.%i.%i or later).'%(pyversion+_minpyversion))
39 import os
40 import pathlib
41
42 def maybeThisIsConda():
43 return ( os.environ.get('CONDA_PREFIX',None) or
44 os.path.exists(os.path.join(sys.base_prefix, 'conda-meta')) )
45
46 def fixSysPathAndImportNCrystal( *, allowfail = False ):
47 thisdir = pathlib.Path( __file__ ).parent
48 def extract_cmake_pymodloc():
49 p = thisdir / 'ncrystal-config'
50 if not p.exists():
51 return
52 with p.open('rt') as fh:
53 for i,l in enumerate(fh):
54 if i==30:
55 break
56 if l.startswith('#CMAKE_RELPATH_TO_PYMOD:'):
57 l = l[24:].strip()
58 return ( thisdir / l ) if l else None
59 pml = extract_cmake_pymodloc()
60 hack_syspath = pml and ( pml / 'NCrystal' / '__init__.py' ).exists()
61 if hack_syspath:
62 sys.path.insert(0,str(pml.absolute().resolve()))
63 try:
64 import NCrystal
65 except ImportError:
66 if allowfail:
67 return
68 msg = 'ERROR: Could not import the NCrystal Python module'
69 if maybeThisIsConda():
70 msg += ' (if using conda it might help to close your terminal and activate your environment again)'
71 elif not hack_syspath:
72 msg += ' (perhaps your PYTHONPATH is misconfigured)'
73 raise SystemExit(msg)
74 return NCrystal
75 ################################################################################################
76 NC = fixSysPathAndImportNCrystal()
77 import NCrystal.mcstasutils as NC_mcstasutils
78
79 import argparse
80
81 def parseArgs():
82 import os
83 progname = os.path.basename(sys.argv[0])
84 progname_inspectfile=progname.replace(progname.split('_')[-1],'inspectfile').replace('ess_nctools_','ess_ncrystal_')
85 descr=f"""
86
87 Script which can be used to create input files with reflections for McStas
88 crystalline sample components like PowderN and Single_crystal, based on NCrystal
89 cfg-strings (usually referring to NCMAT files with crystalline single-phase
90 materials).
91
92 Example invocations:
93
94 $> {progname} "Y2SiO5_sg15_YSO.ncmat" --format=laz -o YSO.laz
95 $> {progname} "Y2SiO5_sg15_YSO.ncmat" --format=lau -o YSO.lau
96
97 It might be useful to set certain parameters in the cfg-string in addition to
98 the input file name. For more information about available parameters, refer to
99 https://github.com/mctools/ncrystal/wiki/CfgRefDoc, or run the cmd:
100
101 $> {progname_inspectfile} --doc
102
103 For instance, to change the material temperature from room temperature, and to
104 leave out reflections at dspacing<0.5Aa, run:
105
106 $> {progname} "Y2SiO5_sg15_YSO.ncmat;dcutoff=0.5;temp=200K" --format=laz -o YSO_200K_largedsp.laz
107 $> {progname} "Y2SiO5_sg15_YSO.ncmat;dcutoff=0.5;temp=200K" --format=lau -o YSO_200K_largedsp.lau
108
109 To browse materials which are available in default NCrystal installations,
110 refer to https://github.com/mctools/ncrystal/wiki/Data-library. To list
111 actually available files in your installation, run:
112
113 $> {progname_inspectfile} --browse
114
115 """
116 from argparse import RawTextHelpFormatter
117 parser = argparse.ArgumentParser(description=descr,
118 formatter_class=RawTextHelpFormatter)
119 parser.add_argument('CFGSTR', type=str,
120 help="""NCrystal cfg-string representing the material to load. For the
121 purposes of the present script, it might be particularly relevant to set
122 the temp and dcutoff parameters""")
123 parser.add_argument('--format','-f',default=None,choices=('laz','lau'),
124 help=f"""What types of output files to produce. Choices are "lau" for .lau files
125 for McStas PowderN or "laz" for .laz files for McStas Single_crystal.""")
126 parser.add_argument('--outfile','-o',type=str,default=None,
127 help="Name of output file (default: stdout)")
128
129 args=parser.parse_args()
130 if not args.format:
131 parser.error('Please specify output type with --format, either'
132 +' --format=laz or --format=lau (run with --help for details)')
133 if args.outfile is not None:
134 of = pathlib.Path(args.outfile)
135 if of.is_dir():
136 parser.error(f'Output destination is directory: {of}')
137 if of.exists():
138 parser.error(f'Output destination already exists: {of}')
139 ofr = of.resolve().absolute()
140 if not ofr.parent.exists() or not ofr.parent.is_dir():
141 parser.error(f'Output destination is in non-existing directory: {ofr.parent}')
142 args.outfile = ofr
143 return args
144
145
146 def main():
147 args=parseArgs()
148 content_iter = NC_mcstasutils.cfgstr_2_hkl( cfgstr = args.CFGSTR,
149 tgtformat = args.format,
150 verbose = True )
151 if args.outfile is None:
152 #stdout:
153 for l in content_iter:
154 print(l)
155 else:
156 #to file:
157 args.outfile.write_text( '\n'.join( content_iter ) + '\n' )
158 print(f"Wrote {args.outfile}")
159
160 if __name__ == '__main__':
161 main()