ncrystal-python 3.9.81__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. NCrystal/__init__.py +85 -0
  2. NCrystal/__main__.py +98 -0
  3. NCrystal/_chooks.py +854 -0
  4. NCrystal/_cli_cif2ncmat.py +269 -0
  5. NCrystal/_cli_endf2ncmat.py +503 -0
  6. NCrystal/_cli_hfg2ncmat.py +144 -0
  7. NCrystal/_cli_mcstasunion.py +74 -0
  8. NCrystal/_cli_ncmat2cpp.py +31 -0
  9. NCrystal/_cli_ncmat2hkl.py +180 -0
  10. NCrystal/_cli_nctool.py +1018 -0
  11. NCrystal/_cli_vdos2ncmat.py +463 -0
  12. NCrystal/_cli_verifyatompos.py +257 -0
  13. NCrystal/_cliimpl.py +307 -0
  14. NCrystal/_cliwrap_config.py +36 -0
  15. NCrystal/_common.py +499 -0
  16. NCrystal/_coreimpl.py +114 -0
  17. NCrystal/_hfgdata.py +546 -0
  18. NCrystal/_hklobjects.py +136 -0
  19. NCrystal/_is_std.py +0 -0
  20. NCrystal/_locatelib.py +210 -0
  21. NCrystal/_miscimpl.py +354 -0
  22. NCrystal/_mmc.py +757 -0
  23. NCrystal/_msg.py +60 -0
  24. NCrystal/_ncmat2cpp_impl.py +445 -0
  25. NCrystal/_ncmatimpl.py +2131 -0
  26. NCrystal/_numpy.py +76 -0
  27. NCrystal/_testimpl.py +579 -0
  28. NCrystal/api.py +56 -0
  29. NCrystal/atomdata.py +177 -0
  30. NCrystal/cfgstr.py +77 -0
  31. NCrystal/cifutils.py +1795 -0
  32. NCrystal/cli.py +96 -0
  33. NCrystal/constants.py +134 -0
  34. NCrystal/core.py +1910 -0
  35. NCrystal/datasrc.py +226 -0
  36. NCrystal/exceptions.py +66 -0
  37. NCrystal/hfg2ncmat.py +270 -0
  38. NCrystal/mcstasutils.py +438 -0
  39. NCrystal/misc.py +317 -0
  40. NCrystal/mmc.py +35 -0
  41. NCrystal/ncmat.py +778 -0
  42. NCrystal/ncmat2cpp.py +80 -0
  43. NCrystal/obsolete.py +67 -0
  44. NCrystal/plot.py +484 -0
  45. NCrystal/plugins.py +49 -0
  46. NCrystal/test.py +76 -0
  47. NCrystal/vdos.py +1034 -0
  48. ncrystal_python-3.9.81.dist-info/LICENSE +206 -0
  49. ncrystal_python-3.9.81.dist-info/METADATA +515 -0
  50. ncrystal_python-3.9.81.dist-info/RECORD +53 -0
  51. ncrystal_python-3.9.81.dist-info/WHEEL +5 -0
  52. ncrystal_python-3.9.81.dist-info/entry_points.txt +10 -0
  53. ncrystal_python-3.9.81.dist-info/top_level.txt +1 -0
NCrystal/_chooks.py ADDED
@@ -0,0 +1,854 @@
1
+
2
+ ################################################################################
3
+ ## ##
4
+ ## This file is part of NCrystal (see https://mctools.github.io/ncrystal/) ##
5
+ ## ##
6
+ ## Copyright 2015-2024 NCrystal developers ##
7
+ ## ##
8
+ ## Licensed under the Apache License, Version 2.0 (the "License"); ##
9
+ ## you may not use this file except in compliance with the License. ##
10
+ ## You may obtain a copy of the License at ##
11
+ ## ##
12
+ ## http://www.apache.org/licenses/LICENSE-2.0 ##
13
+ ## ##
14
+ ## Unless required by applicable law or agreed to in writing, software ##
15
+ ## distributed under the License is distributed on an "AS IS" BASIS, ##
16
+ ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ##
17
+ ## See the License for the specific language governing permissions and ##
18
+ ## limitations under the License. ##
19
+ ## ##
20
+ ################################################################################
21
+
22
+
23
+ """Internal module providing ctypes-based hooks into the compiled NCrystal
24
+ shared library"""
25
+
26
+ __all__ = ['_get_raw_cfcts','_str2cstr','_cstr2str']
27
+
28
+ _rawfcts = [None]
29
+ _namespace = [None]
30
+ def _get_raw_cfcts():
31
+ if _rawfcts[0] is None:
32
+ from ._locatelib import get_libpath_and_namespace
33
+ _rawfcts[0] = False
34
+ thelib, namespace = get_libpath_and_namespace()
35
+ _rawfcts[0] = _load(thelib, namespace)
36
+ assert _rawfcts[0] is not None
37
+ _namespace[0] = namespace or ''
38
+ return _rawfcts[0]
39
+
40
+ def _get_build_namespace():
41
+ if _namespace[0] is None:
42
+ _get_raw_cfcts()
43
+ return _namespace[0]
44
+
45
+ def _str2cstr(s):
46
+ #converts any string (str,bytes,unicode,path) to bytes
47
+ if hasattr(s,'__fspath__'):
48
+ s = str(s)
49
+ try:
50
+ return s if isinstance(s,bytes) else s.encode('utf8')
51
+ except UnicodeEncodeError as e:
52
+ from .exceptions import NCBadInput
53
+ raise NCBadInput("Only unicode strings are supported") from e
54
+
55
+ def _cstr2str(s):
56
+ #converts bytes object to str
57
+ try:
58
+ return s if isinstance(s,str) else s.decode('utf8')
59
+ except UnicodeDecodeError as e:
60
+ from .exceptions import NCBadInput
61
+ raise NCBadInput("Only UTF8-encoded C-strings are supported") from e
62
+
63
+ _keepalive = []#for python based callback functions which we need to keep alive
64
+
65
+ def _load(nclib_filename, ncrystal_namespace_protection ):
66
+
67
+ import ctypes
68
+ from ._numpy import _np, _ensure_numpy
69
+
70
+ try:
71
+ _nclib = ctypes.CDLL(nclib_filename)
72
+ except TypeError:
73
+ _nclib = None
74
+
75
+ if _nclib is None:
76
+ #For some reason, on windows we get a TypeError and must pass a string
77
+ #rather than a pathlib object:
78
+ _nclib = ctypes.CDLL(str(nclib_filename))
79
+
80
+ _int,_intp,_uint,_uintp,_dbl,_dblp,_cstr,_voidp = (ctypes.c_int, ctypes.POINTER(ctypes.c_int),
81
+ ctypes.c_uint,ctypes.POINTER(ctypes.c_uint), ctypes.c_double,
82
+ ctypes.POINTER(ctypes.c_double), ctypes.c_char_p, ctypes.c_void_p)
83
+ _ulong = ctypes.c_ulong
84
+ _charptr = ctypes.POINTER(ctypes.c_char)
85
+ _charptrptr = ctypes.POINTER(_charptr)
86
+
87
+ _cstrp = ctypes.POINTER(_cstr)
88
+ _cstrpp = ctypes.POINTER(_cstrp)
89
+ _dblpp = ctypes.POINTER(_dblp)
90
+ def ndarray_to_dblp(a):
91
+ return a.ctypes.data_as(_dblp)
92
+ def ndarray_to_uintp(a):
93
+ return a.ctypes.data_as(_uintp)
94
+ def ndarray_to_intp(a):
95
+ return a.ctypes.data_as(_intp)
96
+
97
+ def _create_numpy_double_array(n):
98
+ _ensure_numpy()
99
+ a=_np.empty(n,dtype=_dbl)
100
+ return a,ndarray_to_dblp(a)
101
+
102
+ def _create_numpy_unsigned_array(n):
103
+ _ensure_numpy()
104
+ a=_np.empty(n,dtype=_uint)
105
+ return a,ndarray_to_uintp(a)
106
+
107
+ def _create_numpy_int_array(n):
108
+ _ensure_numpy()
109
+ a=_np.empty(n,dtype=_int)
110
+ return a,ndarray_to_intp(a)
111
+
112
+ class ncrystal_info_t(ctypes.Structure):
113
+ _fields_ = [('internal', _voidp)]
114
+ class ncrystal_process_t(ctypes.Structure):
115
+ _fields_ = [('internal', _voidp)]
116
+ class ncrystal_scatter_t(ctypes.Structure):
117
+ _fields_ = [('internal', _voidp)]
118
+ class ncrystal_absorption_t(ctypes.Structure):
119
+ _fields_ = [('internal', _voidp)]
120
+ class ncrystal_atomdata_t(ctypes.Structure):
121
+ _fields_ = [('internal', _voidp)]
122
+
123
+ functions = {}
124
+
125
+ #Exceptions:
126
+ from .exceptions import NCException, NCFileNotFound, NCDataLoadError, NCMissingInfo, NCCalcError, NCLogicError, NCBadInput, nc_assert
127
+ _errmap = {'FileNotFound':NCFileNotFound,
128
+ 'DataLoadError':NCDataLoadError,
129
+ 'MissingInfo':NCMissingInfo,
130
+ 'CalcError':NCCalcError,
131
+ 'LogicError':NCLogicError,
132
+ 'BadInput':NCBadInput}
133
+
134
+ def _raise_err():
135
+ assert _ncerror()#checks there was an error
136
+ tm=(_cstr2str(_ncerror_type()),_cstr2str(_ncerror_msg()))
137
+ _ncerror_clear()
138
+ #TODO: Provide line number / file as well?
139
+ e=_errmap.get(tm[0],NCException)(tm[1])
140
+ e.message = tm[1]#to avoid warnings in py 2.6
141
+ raise e
142
+
143
+ #helper class for exporting the functions:
144
+ ncrystal_namespace_prefix = 'ncrystal_' if not ncrystal_namespace_protection else 'ncrystal%s_'%ncrystal_namespace_protection
145
+ def _wrap(fct_name,restype,argtypes,take_ref = False, hide=False, error_check=True):
146
+ assert isinstance(argtypes,tuple)
147
+ assert fct_name.startswith('ncrystal_')
148
+ if ncrystal_namespace_protection:
149
+ fct_name_actual = ncrystal_namespace_prefix + fct_name[9:]
150
+ else:
151
+ fct_name_actual = fct_name
152
+
153
+ raw=getattr(_nclib,fct_name_actual)
154
+ raw.argtypes=argtypes
155
+ raw.restype=restype
156
+
157
+ if take_ref:
158
+ assert len(argtypes)==1
159
+ def fct(arg):
160
+ return raw(ctypes.byref(arg))
161
+ else:
162
+ def fct(*args):
163
+ return raw(*args)
164
+ if error_check:
165
+ #NB: we should read about return types in the ctypes tutorial. Apparently one
166
+ #can just set an error checking function as the restype.
167
+ raw_fct = fct
168
+ def fcte(*aaa):
169
+ r = raw_fct(*aaa)
170
+ if _ncerror():
171
+ _raise_err()
172
+ return r
173
+ fct=fcte
174
+ if not hide:
175
+ functions[fct_name] = fct
176
+ return fct
177
+
178
+ lib_version = _cstr2str(_wrap('ncrystal_version_str',_cstr,tuple(),hide=True,error_check=False)())
179
+ from . import __version__ as _nc_version
180
+ if lib_version != _nc_version:
181
+ raise NCException("ERROR: Version mismatch detected between NCrystal python code (v%s)"
182
+ " and loaded binary"" library (v%s). Control which NCrystal library"
183
+ " to load with the NCRYSTAL_LIB env var."%(_nc_version,lib_version))
184
+
185
+ _wrap('ncrystal_sethaltonerror',_int,(_int,),hide=True,error_check=False)(False)
186
+ _wrap('ncrystal_setquietonerror',_int,(_int,),hide=True,error_check=False)(True)
187
+ _ncerror = _wrap('ncrystal_error',_int,tuple(),hide=True,error_check=False)
188
+ _ncerror_msg = _wrap('ncrystal_lasterror',_cstr,tuple(),hide=True,error_check=False)
189
+ _ncerror_type = _wrap('ncrystal_lasterrortype',_cstr,tuple(),hide=True,error_check=False)
190
+ _ncerror_clear = _wrap('ncrystal_clearerror',None,tuple(),hide=True,error_check=False)
191
+
192
+ _wrap('ncrystal_refcount',_int,(_voidp,),take_ref=True)
193
+ _wrap('ncrystal_valid',_int,(_voidp,),take_ref=True)
194
+
195
+ #NB: For ncrystal_unref we use take_ref=False, so RCBase.__del__ can cache
196
+ #the result of ctypes.byref(rawobj). This is needed since the ctypes module
197
+ #might have been unloaded before RCBase.__del__ is called:
198
+ _wrap('ncrystal_unref',None,(_voidp,),take_ref=False)
199
+
200
+ _wrap('ncrystal_cast_scat2proc',ncrystal_process_t,(ncrystal_scatter_t,))
201
+ _wrap('ncrystal_cast_abs2proc',ncrystal_process_t,(ncrystal_absorption_t,))
202
+
203
+ _wrap('ncrystal_dump',None,(ncrystal_info_t,))
204
+ _wrap('ncrystal_dump_verbose',None,(ncrystal_info_t,_uint))
205
+
206
+ _wrap('ncrystal_ekin2wl',_dbl,(_dbl,))
207
+ _wrap('ncrystal_wl2ekin',_dbl,(_dbl,))
208
+ _wrap('ncrystal_isnonoriented',_int,(ncrystal_process_t,))
209
+ _wrap('ncrystal_name',_cstr,(ncrystal_process_t,))
210
+
211
+ _wrap('ncrystal_debyetemp2msd',_dbl,(_dbl,_dbl,_dbl))
212
+ _wrap('ncrystal_msd2debyetemp',_dbl,(_dbl,_dbl,_dbl))
213
+
214
+ _wrap('ncrystal_create_atomdata_fromdb',ncrystal_atomdata_t,(_uint,_uint))
215
+ _wrap('ncrystal_create_atomdata_fromdbstr',ncrystal_atomdata_t,(_cstr,))
216
+
217
+ _raw_atomdb_getn = _wrap('ncrystal_atomdatadb_getnentries',_uint,tuple(), hide=True )
218
+ _raw_atomdb_getall = _wrap('ncrystal_atomdatadb_getallentries',_uint,(_uintp,_uintp), hide=True )
219
+ def atomdb_getall_za():
220
+ n = _raw_atomdb_getn()
221
+ zvals,zvalsptr = _create_numpy_unsigned_array(n)
222
+ avals,avalsptr = _create_numpy_unsigned_array(n)
223
+ _raw_atomdb_getall(zvalsptr,avalsptr)
224
+ za=_np.stack((zvals,avals)).T
225
+ return za
226
+ functions['atomdb_getall_za']=atomdb_getall_za
227
+
228
+ _wrap('ncrystal_info_natominfo',_uint,(ncrystal_info_t,))
229
+ _wrap('ncrystal_info_hasatommsd',_int,(ncrystal_info_t,))
230
+ _raw_info_getatominfo = _wrap('ncrystal_info_getatominfo',None,(ncrystal_info_t,_uint,_uintp,_uintp,_dblp,_dblp),hide=True)
231
+ def ncrystal_info_getatominfo(nfo,iatom):
232
+ atomidx,n,dt,msd=_uint(),_uint(),_dbl(),_dbl()
233
+ _raw_info_getatominfo(nfo,iatom,atomidx,n,dt,msd)
234
+ return (atomidx.value,n.value,dt.value,msd.value)
235
+ functions['ncrystal_info_getatominfo'] = ncrystal_info_getatominfo
236
+ _raw_info_getatompos = _wrap('ncrystal_info_getatompos',None,(ncrystal_info_t,_uint,_uint,_dblp,_dblp,_dblp),hide=True)
237
+ def ncrystal_info_getatompos(nfo,iatom,ipos):
238
+ x,y,z=_dbl(),_dbl(),_dbl()
239
+ _raw_info_getatompos(nfo,iatom,ipos,x,y,z)
240
+ return x.value, y.value, z.value
241
+ functions['ncrystal_info_getatompos'] = ncrystal_info_getatompos
242
+
243
+ for s in ('temperature','xsectabsorption','xsectfree','density','numberdensity','sld'):
244
+ _wrap('ncrystal_info_get%s'%s,_dbl,(ncrystal_info_t,))
245
+ _wrap('ncrystal_info_getstateofmatter',_int,( ncrystal_info_t,))
246
+ _raw_info_getstruct = _wrap('ncrystal_info_getstructure',_int,(ncrystal_info_t,_uintp,_dblp,_dblp,_dblp,_dblp,_dblp,_dblp,_dblp,_uintp))
247
+ def ncrystal_info_getstructure(nfo):
248
+ sg,natom=_uint(),_uint()
249
+ a,b,c,alpha,beta,gamma,vol = _dbl(),_dbl(),_dbl(),_dbl(),_dbl(),_dbl(),_dbl(),
250
+ if _raw_info_getstruct(nfo,sg,a,b,c,alpha,beta,gamma,vol,natom) == 0:
251
+ return {}
252
+ return dict(spacegroup=int(sg.value),a=a.value,b=b.value,c=c.value,alpha=alpha.value,
253
+ beta=beta.value,gamma=gamma.value,volume=vol.value,n_atoms=int(natom.value))
254
+ functions['ncrystal_info_getstructure'] = ncrystal_info_getstructure
255
+
256
+ _wrap('ncrystal_info_nphases',_int,(ncrystal_info_t,))
257
+ _wrap('ncrystal_info_getphase',ncrystal_info_t,(ncrystal_info_t,_int,_dblp))
258
+
259
+ _wrap('ncrystal_info_nhkl',_int,(ncrystal_info_t,))
260
+ _wrap('ncrystal_info_hkl_dlower',_dbl,(ncrystal_info_t,))
261
+ _wrap('ncrystal_info_hkl_dupper',_dbl,(ncrystal_info_t,))
262
+ _wrap('ncrystal_info_braggthreshold',_dbl,(ncrystal_info_t,))
263
+ _wrap('ncrystal_info_hklinfotype',_int,(ncrystal_info_t,))
264
+ _wrap('ncrystal_info_gethkl',None,(ncrystal_info_t,_int,_intp,_intp,_intp,_intp,_dblp,_dblp))
265
+ _wrap('ncrystal_info_dspacing_from_hkl',_dbl,(ncrystal_info_t,_int,_int,_int))
266
+ functions['ncrystal_info_gethkl_setuppars'] = lambda : (_int(),_int(),_int(),_int(),_dbl(),_dbl())
267
+
268
+ _raw_gethkl_allindices = _wrap('ncrystal_info_gethkl_allindices',None,(ncrystal_info_t,_int,_intp,_intp,_intp), hide=True )
269
+ def iter_hkllist(nfo,all_indices=False):
270
+ h,k,ll,mult,dsp,fsq = _int(),_int(),_int(),_int(),_dbl(),_dbl()
271
+ nhkl = int(functions['ncrystal_info_nhkl'](nfo))
272
+ for idx in range(nhkl):
273
+ functions['ncrystal_info_gethkl'](nfo,idx,h,k,ll,mult,dsp,fsq)
274
+ if not all_indices:
275
+ yield h.value,k.value,ll.value,mult.value,dsp.value,fsq.value
276
+ else:
277
+ nc_assert( mult.value % 2 == 0 )
278
+ n = mult.value // 2
279
+ hvals, hvalsptr = _create_numpy_int_array( n )
280
+ kvals, kvalsptr = _create_numpy_int_array( n )
281
+ lvals, lvalsptr = _create_numpy_int_array( n )
282
+ _raw_gethkl_allindices(nfo,idx,hvalsptr,kvalsptr,lvalsptr)
283
+ yield hvals,kvals,lvals,mult.value,dsp.value,fsq.value
284
+ functions['iter_hkllist']=iter_hkllist
285
+
286
+ _raw_dealloc_dblptr = _wrap('ncrystal_dealloc_doubleptr',None,(_dblp,),hide=True)
287
+ def _cptr_to_nparray( cptr, n, free_after_with_ncrystal_dealloc = True ):
288
+ import numpy.ctypeslib as _np_ctypeslib
289
+ np_arr = _np_ctypeslib.as_array(cptr,shape=(int(n.value if hasattr(n,'value') else n),)).copy()
290
+ if free_after_with_ncrystal_dealloc:
291
+ _raw_dealloc_dblptr(cptr)
292
+ return np_arr
293
+
294
+ _wrap('ncrystal_info_ndyninfo',_uint,(ncrystal_info_t,))
295
+ _raw_di_base = _wrap('ncrystal_dyninfo_base',None,(ncrystal_info_t,_uint,_dblp,_uintp,_dblp,_uintp),hide=True)
296
+ _raw_di_scatknl = _wrap('ncrystal_dyninfo_extract_scatknl',None,(ncrystal_info_t,_uint,_uint,_dblp,_uintp,_uintp,_uintp,
297
+ _dblpp,_dblpp,_dblpp,_dblpp),hide=True)
298
+ _raw_di_vdos = _wrap('ncrystal_dyninfo_extract_vdos',None,(ncrystal_info_t,_uint,_dblp,_dblp,_uintp,_dblpp),hide=True)
299
+ _raw_di_vdosdebye = _wrap('ncrystal_dyninfo_extract_vdosdebye',None,(ncrystal_info_t,_uint,_dblp),hide=True)
300
+ _raw_di_vdos_input = _wrap('ncrystal_dyninfo_extract_vdos_input',None,(ncrystal_info_t,_uint,_uintp,_dblpp,_uintp,_dblpp),hide=True)
301
+ _raw_vdos2gn = _wrap('ncrystal_raw_vdos2gn',None,(_dblp,_dblp,_uint,_uint,_dbl,_dbl,_dbl,_uint,_dblp,_dblp,_uintp,_dblpp),hide=True)
302
+
303
+ def raw_vdos2gn( egrid, density, scatxs, mass_amu, temperature, nvalue ):
304
+ _ensure_numpy()
305
+ _egrid = _np.asarray(egrid,dtype=float)
306
+ _density = _np.asarray(density,dtype=float)
307
+ _s = _dbl(float(scatxs))
308
+ _m = _dbl(float(mass_amu))
309
+ _t = _dbl(float(temperature))
310
+ _n = _uint(int(nvalue))
311
+ xmin, xmax, ny = _dbl(), _dbl(), _uint()
312
+ yraw = _dblp()
313
+ _raw_vdos2gn( ndarray_to_dblp(_egrid),
314
+ ndarray_to_dblp(_density),
315
+ _uint(len(_egrid)),
316
+ _uint(len(_density)),
317
+ _s,_m,_t,_n, xmin, xmax, ny, yraw )
318
+ return float(xmin.value), float(xmax.value), _cptr_to_nparray( yraw, ny )
319
+ functions['raw_vdos2gn'] = raw_vdos2gn
320
+
321
+ _ORDERWEIGHTFCTTYPE = ctypes.CFUNCTYPE( _dbl, _uint )
322
+ _raw_vdos2knl = _wrap('ncrystal_raw_vdos2knl',None,(_dblp,_dblp,_uint,_uint,_dbl,_dbl,_dbl,_uint,_ORDERWEIGHTFCTTYPE,_uintp,_uintp,_dblpp,_dblpp,_dblpp),hide=True)
323
+ def raw_vdos2knl( egrid, density, scatxs, mass_amu, temperature, vdoslux, order_weight_fct ):
324
+ _ensure_numpy()
325
+ _egrid,_density = _np.asarray(egrid,dtype=float),_np.asarray(density,dtype=float)
326
+ _s,_m,_t,_vdl = _dbl(float(scatxs)),_dbl(float(mass_amu)),_dbl(float(temperature)),_uint(int(vdoslux))
327
+ nalpha, nbeta,agrid, bgrid, sab = _uint(), _uint(),_dblp(), _dblp(), _dblp()
328
+ if order_weight_fct:
329
+ def owf(order):
330
+ return float(order_weight_fct( int(order.value
331
+ if hasattr(order,'value')
332
+ else order) ))
333
+ #NB: No need to keep owf alive, after our function exists, since it is only used during evaluation.
334
+ _owf = _ORDERWEIGHTFCTTYPE(owf)
335
+ else:
336
+ _owf = ctypes.cast(None, _ORDERWEIGHTFCTTYPE)
337
+ _raw_vdos2knl( ndarray_to_dblp(_egrid), ndarray_to_dblp(_density),
338
+ _uint(len(_egrid)),_uint(len(_density)),
339
+ _s,_m,_t,_vdl,_owf,nalpha, nbeta,
340
+ ctypes.byref(agrid), ctypes.byref(bgrid), ctypes.byref(sab) )
341
+ return ( _cptr_to_nparray( agrid, nalpha ),
342
+ _cptr_to_nparray( bgrid, nbeta ),
343
+ _cptr_to_nparray( sab, nalpha.value * nbeta.value ) )
344
+ functions['raw_vdos2knl'] = raw_vdos2knl
345
+
346
+ def ncrystal_dyninfo_base(key):
347
+ infoobj,dynidx = key
348
+ fr,tt,atomindex,ditype=_dbl(),_dbl(),_uint(),_uint()
349
+ _raw_di_base(infoobj,dynidx,fr,atomindex,tt,ditype)
350
+ return (fr.value,tt.value,atomindex.value,ditype.value)
351
+ def ncrystal_dyninfo_extract_scatknl(key,vdoslux):
352
+ infoobj,dynidx = key
353
+ sugEmax,ne,na,nb,e,a,b,sab = _dbl(),_uint(),_uint(),_uint(),_dblp(),_dblp(),_dblp(),_dblp()
354
+ _raw_di_scatknl(infoobj,dynidx,vdoslux,sugEmax,ne,na,nb,
355
+ ctypes.byref(e),ctypes.byref(a),ctypes.byref(b),ctypes.byref(sab))
356
+ return (sugEmax.value,ne.value,na.value,nb.value,e,a,b,sab)
357
+ def ncrystal_dyninfo_extract_vdos(key):
358
+ infoobj,dynidx = key
359
+ egrid_min,egrid_max,ndensity,densityptr = _dbl(),_dbl(),_uint(),_dblp()
360
+ _raw_di_vdos(infoobj,dynidx,egrid_min,egrid_max,ndensity,ctypes.byref(densityptr))
361
+ return (egrid_min.value,egrid_max.value,ndensity.value,densityptr)
362
+ def ncrystal_dyninfo_extract_vdosdebye(key):
363
+ infoobj,dynidx = key
364
+ td=_dbl()
365
+ _raw_di_vdosdebye(infoobj,dynidx,td)
366
+ return td.value
367
+ def ncrystal_dyninfo_extract_vdos_input(key):
368
+ infoobj,dynidx = key
369
+ negrid,egridptr,ndensity,densityptr = _uint(),_dblp(),_uint(),_dblp()
370
+ _raw_di_vdos_input(infoobj,dynidx,negrid,ctypes.byref(egridptr),ndensity,ctypes.byref(densityptr))
371
+ return (negrid.value,egridptr,ndensity.value,densityptr)
372
+ functions['ncrystal_dyninfo_base'] = ncrystal_dyninfo_base
373
+ functions['ncrystal_dyninfo_extract_scatknl'] = ncrystal_dyninfo_extract_scatknl
374
+ functions['ncrystal_dyninfo_extract_vdos'] = ncrystal_dyninfo_extract_vdos
375
+ functions['ncrystal_dyninfo_extract_vdosdebye'] = ncrystal_dyninfo_extract_vdosdebye
376
+ functions['ncrystal_dyninfo_extract_vdos_input'] = ncrystal_dyninfo_extract_vdos_input
377
+
378
+ _raw_vdoseval = _wrap('ncrystal_vdoseval',None,(_dbl,_dbl,_uint,_dblp,_dbl,_dbl,_dblp,_dblp,_dblp,_dblp,_dblp),hide=True)
379
+ def nc_vdoseval(emin,emax,density,temp,mass_amu):
380
+ msd,dt,g0,teff,oint=_dbl(),_dbl(),_dbl(),_dbl(),_dbl()
381
+ _raw_vdoseval(emin,emax,len(density),ndarray_to_dblp(density),temp,mass_amu,
382
+ msd,dt,g0,teff,oint)
383
+ return dict(msd=msd.value,debye_temp=dt.value,gamma0=g0.value,teff=teff.value,integral=oint.value)
384
+ functions['nc_vdoseval']=nc_vdoseval
385
+
386
+ _wrap('ncrystal_info_ncomponents',_uint,(ncrystal_info_t,))
387
+ _raw_info_getcomp=_wrap('ncrystal_info_getcomponent',None,(ncrystal_info_t,_uint,_uintp,_dblp),hide=True)
388
+ def ncrystal_info_getcomp(nfo,icomp):
389
+ aidx,fraction=_uint(),_dbl()
390
+ _raw_info_getcomp(nfo,icomp,aidx,fraction)
391
+ return aidx.value,fraction.value
392
+ functions['ncrystal_info_getcomp']=ncrystal_info_getcomp
393
+
394
+ _NEP_FCTTYPE = ctypes.CFUNCTYPE( _uint,_uint,_uintp,_dblp )# -> unsigned (*natelemprovider)(unsigned,unsigned*,double*)
395
+ _raw_info_getflatcompos = _wrap('ncrystal_get_flatcompos',_charptr,(ncrystal_info_t,_int,_NEP_FCTTYPE),hide=True)
396
+
397
+ def nc_info_getflatcompos( nfo, natelemprovider = None, prefernatelem = True ):
398
+ _prefnatelem = _int(1 if prefernatelem else 0)
399
+ if not natelemprovider:
400
+ _nullfct = ctypes.cast(None, _NEP_FCTTYPE)
401
+ raw_str = _raw_info_getflatcompos(nfo,_prefnatelem,_nullfct)
402
+ else:
403
+ #natelemprovider is function which takes integer Z and returns a list
404
+ #[(A,fraction),...]. Create a wrapper compatible with _NEP_FCTTYPE:
405
+ #unsigned (*natelemprovider)(unsigned,unsigned*,double*)
406
+ def nep_wrap(Z,bufA,bufFrac):
407
+ _ = natelemprovider(Z)
408
+ if not _:
409
+ #returned None or [], i.e. there is no info about the
410
+ #element:
411
+ return 0
412
+ assert len(_) < 128
413
+ for i,(A,f) in enumerate(_):
414
+ bufA[i] = A
415
+ bufFrac[i] = f
416
+ return len(_)
417
+ _c_nep_wrap = _NEP_FCTTYPE(nep_wrap)
418
+ raw_str = _raw_info_getflatcompos(nfo,_prefnatelem,_c_nep_wrap)
419
+ if raw_str is None:
420
+ return 'null'#None in json
421
+ res=_cstr2str(ctypes.cast(raw_str,_cstr).value)
422
+ _raw_deallocstr(raw_str)
423
+ return res
424
+ functions['nc_info_getflatcompos']=nc_info_getflatcompos
425
+
426
+ _wrap('ncrystal_create_atomdata',ncrystal_atomdata_t,(ncrystal_info_t,_uint))
427
+ _raw_atomdata_subcomp = _wrap('ncrystal_create_atomdata_subcomp',ncrystal_atomdata_t,
428
+ (ncrystal_atomdata_t,_uint,_dblp),hide=True)
429
+ _raw_atomdata_getfields=_wrap('ncrystal_atomdata_getfields',None,(ncrystal_atomdata_t,_cstrp,_cstrp,
430
+ _dblp,_dblp,_dblp,_dblp,
431
+ _uintp,_uintp,_uintp),hide=True)
432
+ _wrap('ncrystal_create_component_atomdata',ncrystal_atomdata_t,(ncrystal_info_t,_uint))
433
+
434
+ def ncrystal_atomdata_createsubcomp(ad,icomp):
435
+ fraction = _dbl()
436
+ comp_ad = _raw_atomdata_subcomp(ad,icomp,fraction)
437
+ return (comp_ad,fraction.value)
438
+ functions['ncrystal_atomdata_createsubcomp']=ncrystal_atomdata_createsubcomp
439
+ def ncrystal_atomdata_getfields(ad):
440
+ mass_amu,sigma_inc,scatlen_coh,sigma_abs=_dbl(),_dbl(),_dbl(),_dbl()
441
+ dl,descr=_cstr(),_cstr()
442
+ ncomp,zval,aval = _uint(),_uint(),_uint()
443
+ _raw_atomdata_getfields(ad,ctypes.byref(dl),ctypes.byref(descr),
444
+ mass_amu,sigma_inc,scatlen_coh,sigma_abs,
445
+ ncomp,zval,aval)
446
+ return dict(m=mass_amu.value,incxs=sigma_inc.value,cohsl_fm=scatlen_coh.value,absxs=sigma_abs.value,
447
+ dl=_cstr2str(dl.value),descr=_cstr2str(descr.value),
448
+ ncomp=ncomp.value,z=zval.value,a=aval.value)
449
+ functions['ncrystal_atomdata_getfields'] = ncrystal_atomdata_getfields
450
+
451
+ _raw_ncustom = _wrap('ncrystal_info_ncustomsections',_uint,(ncrystal_info_t,),hide=True)
452
+ _raw_csec_name = _wrap('ncrystal_info_customsec_name',_cstr,(ncrystal_info_t,_uint),hide=True)
453
+ _raw_csec_nlines = _wrap('ncrystal_info_customsec_nlines',_uint,(ncrystal_info_t,_uint),hide=True)
454
+ _raw_csec_nparts = _wrap('ncrystal_info_customline_nparts',_uint,(ncrystal_info_t,_uint,_uint),hide=True)
455
+ _raw_csec_part = _wrap('ncrystal_info_customline_getpart',_cstr,(ncrystal_info_t,_uint,_uint,_uint),hide=True)
456
+ def ncrystal_info_getcustomsections(nfo):
457
+ n=_raw_ncustom(nfo)
458
+ if n==0:
459
+ return tuple()
460
+ out=[]
461
+ for isec in range(n):
462
+ lines=[]
463
+ secname = _cstr2str(_raw_csec_name(nfo,isec))
464
+ nlines = _raw_csec_nlines(nfo,isec)
465
+ for iline in range(nlines):
466
+ nparts=_raw_csec_nparts(nfo,isec,iline)
467
+ parts=[]
468
+ for ipart in range(nparts):
469
+ parts.append(_cstr2str(_raw_csec_part(nfo,isec,iline,ipart)))
470
+ lines.append(tuple(parts))
471
+ out.append((secname,tuple(lines)))
472
+ return tuple(out)
473
+ functions['ncrystal_info_getcustomsections'] = ncrystal_info_getcustomsections
474
+
475
+ _raw_reginmemfd = _wrap('ncrystal_register_in_mem_file_data',None,(_cstr,_cstr),hide=True)
476
+ def ncrystal_register_in_mem_file_data(virtual_filename,data):
477
+ _raw_reginmemfd(_str2cstr(virtual_filename),
478
+ _str2cstr(data))
479
+ functions['ncrystal_register_in_mem_file_data']=ncrystal_register_in_mem_file_data
480
+
481
+ def _prepare_many(ekin,repeat):
482
+ if _np is None and repeat is not None:
483
+ raise NCBadInput('Can not use "repeat" parameter when Numpy is absent on the system')
484
+ if repeat is None and not hasattr(ekin,'__len__'):
485
+ return None#scalar case, array interface not triggered
486
+ repeat = 1 if repeat is None else repeat
487
+ ekin = (ekin if hasattr(ekin,'ctypes') else _np.asarray(ekin,dtype=float) ) if hasattr(ekin,'__len__') else _np.ones(1)*ekin
488
+ #NB: returning the ekin object itself is important in order to keep a reference to it after the call:
489
+ return ndarray_to_dblp(ekin),len(ekin),repeat,ekin
490
+
491
+ _raw_xs_no = _wrap('ncrystal_crosssection_nonoriented',None,(ncrystal_process_t,_dbl,_dblp),hide=True)
492
+ _raw_xs_no_many = _wrap('ncrystal_crosssection_nonoriented_many',None,(ncrystal_process_t,_dblp,_ulong,
493
+ _ulong,_dblp),hide=True)
494
+ _empty_arrayf = _np.empty(shape=(0,),dtype=float) if _np else tuple()
495
+ _empty_arrayf_2tuple = ( ( _np.empty(shape=(0,),dtype=float),
496
+ _np.empty(shape=(0,),dtype=float) )
497
+ if _np else (tuple(),tuple()) )
498
+
499
+ def ncrystal_crosssection_nonoriented(scat,ekin,repeat=None):
500
+ many = _prepare_many(ekin,repeat)
501
+ if many is None:
502
+ res = _dbl()
503
+ _raw_xs_no(scat,ekin,res)
504
+ return res.value
505
+ else:
506
+ ekin_ct,n_ekin,repeat,ekin_nparr = many
507
+ if repeat == 0:
508
+ return _empty_arrayf
509
+ xs, xs_ct = _create_numpy_double_array(n_ekin*repeat)
510
+ _raw_xs_no_many(scat,ekin_ct,n_ekin,repeat,xs_ct)
511
+ return xs
512
+ functions['ncrystal_crosssection_nonoriented'] = ncrystal_crosssection_nonoriented
513
+
514
+ _raw_domain = _wrap('ncrystal_domain',None,(ncrystal_process_t,_dblp,_dblp),hide=True)
515
+ def ncrystal_domain(proc):
516
+ a,b = _dbl(),_dbl()
517
+ _raw_domain(proc,a,b)
518
+ return (a.value,b.value)
519
+ functions['ncrystal_domain'] = ncrystal_domain
520
+
521
+ _raw_samplesct_iso =_wrap('ncrystal_samplescatterisotropic',None,(ncrystal_scatter_t,_dbl,_dblp,_dblp),hide=True)
522
+ _raw_samplesct_iso_many =_wrap('ncrystal_samplescatterisotropic_many',None,
523
+ (ncrystal_scatter_t,_dblp,_ulong,_ulong,_dblp,_dblp),hide=True)
524
+ _raw_samplescat = _wrap('ncrystal_samplescatter',None,( ncrystal_scatter_t, _dbl,_dbl*3,_dblp,_dbl*3),hide=True)
525
+ _raw_samplescat_many = _wrap('ncrystal_samplescatter_many',None,( ncrystal_scatter_t,_dbl,_dbl*3,_ulong,
526
+ _dblp,_dblp,_dblp,_dblp),hide=True)
527
+ def ncrystal_samplesct_iso(scat,ekin,repeat=None):
528
+ many = _prepare_many(ekin,repeat)
529
+ if many is None:
530
+ ekin_final,mu = _dbl(),_dbl()
531
+ _raw_samplesct_iso(scat,ekin,ekin_final,mu)
532
+ return ekin_final.value,mu.value
533
+ else:
534
+ ekin_ct,n_ekin,repeat,ekin_nparr = many
535
+ if repeat == 0:
536
+ #special case which happens often in our nctool usage:
537
+ return _empty_arrayf_2tuple
538
+ ekin_final, ekin_final_ct = _create_numpy_double_array(n_ekin*repeat)
539
+ mu, mu_ct = _create_numpy_double_array(n_ekin*repeat)
540
+ _raw_samplesct_iso_many(scat,ekin_ct,n_ekin,repeat,ekin_final_ct,mu_ct)
541
+ return ekin_final,mu
542
+ functions['ncrystal_samplesct_iso'] = ncrystal_samplesct_iso
543
+
544
+ def ncrystal_samplesct(scat, ekin, direction, repeat):
545
+ cdir = (_dbl * 3)(*direction)
546
+ if not repeat:
547
+ res_dir = (_dbl * 3)(0,0,0)
548
+ res_ekin = _dbl()
549
+ _raw_samplescat(scat,ekin,cdir,res_ekin,res_dir)
550
+ return res_ekin.value,(res_dir[0],res_dir[1],res_dir[2])
551
+ else:
552
+ assert repeat>=1
553
+ res_ekin, res_ekin_ct = _create_numpy_double_array(repeat)
554
+ res_ux, res_ux_ct = _create_numpy_double_array(repeat)
555
+ res_uy, res_uy_ct = _create_numpy_double_array(repeat)
556
+ res_uz, res_uz_ct = _create_numpy_double_array(repeat)
557
+ _raw_samplescat_many(scat,ekin,cdir,repeat,res_ekin_ct,res_ux_ct,res_uy_ct,res_uz_ct)
558
+ return res_ekin,(res_ux,res_uy,res_uz)
559
+ functions['ncrystal_samplesct']=ncrystal_samplesct
560
+
561
+ _raw_xs = _wrap('ncrystal_crosssection',None,(ncrystal_process_t,_dbl,_dbl*3,_dblp),hide=True)
562
+ def ncrystal_crosssection( proc, ekin, direction):
563
+ res = _dbl()
564
+ cdir = (_dbl * 3)(*direction)
565
+ if hasattr(ekin,'__len__'):
566
+ #Todo: this vectorises on the Python side which is slow!
567
+ _ensure_numpy()
568
+ def e2xs(e):
569
+ _raw_xs(proc,e,cdir,res)
570
+ return res.value
571
+ return _np.vectorize(e2xs)(ekin)
572
+ else:
573
+ _raw_xs(proc,ekin,cdir,res)
574
+ return res.value
575
+ functions['ncrystal_crosssection'] = ncrystal_crosssection
576
+
577
+ #Obsolete:
578
+ _raw_gs_no = _wrap('ncrystal_genscatter_nonoriented',None,(ncrystal_scatter_t,_dbl,_dblp,_dblp),hide=True)
579
+ _raw_gs_no_many = _wrap('ncrystal_genscatter_nonoriented_many',None,(ncrystal_scatter_t,_dblp,_ulong,
580
+ _ulong,_dblp,_dblp),hide=True)
581
+ def ncrystal_genscatter_nonoriented(scat,ekin,repeat=None):
582
+ many = _prepare_many(ekin,repeat)
583
+ if many is None:
584
+ angle,de = _dbl(),_dbl()
585
+ _raw_gs_no(scat,ekin,angle,de)
586
+ return angle.value,de.value
587
+ else:
588
+ ekin_ct,n_ekin,repeat,ekin_nparr = many
589
+ angle, angle_ct = _create_numpy_double_array(n_ekin*repeat)
590
+ de, de_ct = _create_numpy_double_array(n_ekin*repeat)
591
+ _raw_gs_no_many(scat,ekin_ct,n_ekin,repeat,angle_ct,de_ct)
592
+ return angle,de
593
+ functions['ncrystal_genscatter_nonoriented'] = ncrystal_genscatter_nonoriented
594
+ _raw_gs = _wrap('ncrystal_genscatter',None,(ncrystal_scatter_t,_dbl,_dbl*3,_dbl*3,_dblp),hide=True)
595
+ _raw_gs_many = _wrap('ncrystal_genscatter_many',None,(ncrystal_scatter_t,_dbl,_dbl*3,
596
+ _ulong,_dblp,_dblp,_dblp,_dblp),hide=True)
597
+ def ncrystal_genscatter(scat, ekin, direction, repeat):
598
+ cdir = (_dbl * 3)(*direction)
599
+ if not repeat:
600
+ res_dir = (_dbl * 3)(0,0,0)
601
+ res_de = _dbl()
602
+ _raw_gs(scat,ekin,cdir,res_dir,res_de)
603
+ return (res_dir[0],res_dir[1],res_dir[2]),res_de.value
604
+ else:
605
+ assert repeat>=1
606
+ res_ux, res_ux_ct = _create_numpy_double_array(repeat)
607
+ res_uy, res_uy_ct = _create_numpy_double_array(repeat)
608
+ res_uz, res_uz_ct = _create_numpy_double_array(repeat)
609
+ res_de, res_de_ct = _create_numpy_double_array(repeat)
610
+ _raw_gs_many(scat,ekin,cdir,repeat,res_ux_ct,res_uy_ct,res_uz_ct,res_de_ct)
611
+ return (res_ux,res_uy,res_uz),res_de
612
+ functions['ncrystal_genscatter']=ncrystal_genscatter
613
+
614
+ _wrap('ncrystal_create_info',ncrystal_info_t,(_cstr,))
615
+ _wrap('ncrystal_create_scatter',ncrystal_scatter_t,(_cstr,))
616
+ _wrap('ncrystal_create_scatter_builtinrng',ncrystal_scatter_t,(_cstr,_ulong))
617
+ _wrap('ncrystal_create_absorption',ncrystal_absorption_t,(_cstr,))
618
+
619
+ _raw_multicreate_direct = _wrap('ncrystal_multicreate_direct',None,
620
+ ( _cstr, _cstr, _cstr,
621
+ ctypes.POINTER(ncrystal_info_t),
622
+ ctypes.POINTER(ncrystal_scatter_t),
623
+ ctypes.POINTER(ncrystal_absorption_t) ),hide=True)
624
+ nullptr_ncrystal_info_t = ctypes.cast(None, ctypes.POINTER(ncrystal_info_t))
625
+ nullptr_ncrystal_scatter_t = ctypes.cast(None, ctypes.POINTER(ncrystal_scatter_t))
626
+ nullptr_ncrystal_absorption_t = ctypes.cast(None, ctypes.POINTER(ncrystal_absorption_t))
627
+
628
+ def multicreate_direct(data,dataType,cfg_params,doI,doS,doA):
629
+ rawi = ncrystal_info_t() if doI else None
630
+ raws = ncrystal_scatter_t() if doS else None
631
+ rawa = ncrystal_absorption_t() if doA else None
632
+ _raw_multicreate_direct( _str2cstr(data),_str2cstr(dataType or "" ),_str2cstr(cfg_params or ""),
633
+ ctypes.byref(rawi) if rawi else nullptr_ncrystal_info_t,
634
+ ctypes.byref(raws) if raws else nullptr_ncrystal_scatter_t,
635
+ ctypes.byref(rawa) if rawa else nullptr_ncrystal_absorption_t )
636
+ return rawi,raws,rawa
637
+ functions['multicreate_direct'] = multicreate_direct
638
+
639
+ _wrap('ncrystal_setbuiltinrandgen',None,tuple())
640
+
641
+ _RANDGENFCTTYPE = ctypes.CFUNCTYPE( _dbl )
642
+ _raw_setrand = _wrap('ncrystal_setrandgen',None,(_RANDGENFCTTYPE,),hide=True)
643
+ def ncrystal_setrandgen(randfct):
644
+ #Set random function, keeping references as needed (otherwise fct ptrs
645
+ #kept on C++ side will suddenly stop working!) and casting None to a null-ptr.
646
+ if not randfct:
647
+ keepalive=(None,ctypes.cast(None, _RANDGENFCTTYPE))
648
+ else:
649
+ keepalive=(randfct,_RANDGENFCTTYPE(randfct))#keep refs!
650
+ _keepalive.append(keepalive)
651
+ _raw_setrand(keepalive[1])
652
+ functions['ncrystal_setrandgen'] = ncrystal_setrandgen
653
+
654
+ _wrap('ncrystal_clone_absorption',ncrystal_absorption_t,(ncrystal_absorption_t,))
655
+ _wrap('ncrystal_clone_scatter',ncrystal_scatter_t,(ncrystal_scatter_t,))
656
+ _wrap('ncrystal_clone_scatter_rngbyidx',ncrystal_scatter_t,(ncrystal_scatter_t,_ulong))
657
+ _wrap('ncrystal_clone_scatter_rngforcurrentthread',ncrystal_scatter_t,(ncrystal_scatter_t,))
658
+ _wrap('ncrystal_decodecfg_vdoslux',_uint,(_cstr,))
659
+ _wrap('ncrystal_has_factory',_int,(_cstr,))
660
+ _wrap('ncrystal_clear_caches',None,tuple())
661
+
662
+ _wrap('ncrystal_rngsupportsstatemanip_ofscatter',_int,( ncrystal_scatter_t, ))
663
+ _wrap('ncrystal_setrngstate_ofscatter',None,(ncrystal_scatter_t, _cstr))
664
+ _raw_getrngstate_scat = _wrap('ncrystal_getrngstate_ofscatter',_charptr,( ncrystal_scatter_t,),hide=True)
665
+
666
+ def nc_getrngstate_scat(rawscatobj):
667
+ rawstate = _raw_getrngstate_scat(rawscatobj)
668
+ if not rawstate:
669
+ #null ptr, i.e. state manipulation is not supported
670
+ return None
671
+ state=_cstr2str(ctypes.cast(rawstate,_cstr).value)
672
+ _raw_deallocstr(rawstate)
673
+ return state
674
+ functions['nc_getrngstate_scat']=nc_getrngstate_scat
675
+
676
+ def _decode_and_dealloc_raw_str(raw_cstr):
677
+ if not raw_cstr:
678
+ return None
679
+ res=_cstr2str(ctypes.cast(raw_cstr,_cstr).value)
680
+ _raw_deallocstr(raw_cstr)
681
+ return res
682
+
683
+ _raw_dump_tostr = _wrap('ncrystal_dump_tostr',_charptr,(ncrystal_info_t,_uint),hide=True)
684
+ def nc_dump_tostr( raw_infoobj, verbosity ):
685
+ return _decode_and_dealloc_raw_str( _raw_dump_tostr( raw_infoobj, verbosity ) )
686
+ functions['nc_dump_tostr'] = nc_dump_tostr
687
+
688
+ _raw_dbg_process = _wrap('ncrystal_dbg_process',_charptr,(ncrystal_process_t,),hide=True)
689
+ def nc_dbg_proc(rawprocobj):
690
+ import json
691
+ return json.loads( _decode_and_dealloc_raw_str( _raw_dbg_process( rawprocobj ) ) )
692
+ functions['nc_dbg_proc']=nc_dbg_proc
693
+
694
+ _raw_decodecfg_json = _wrap('ncrystal_decodecfg_json',_charptr,(_cstr,),hide=True)
695
+ def nc_cfgstr2json(cfgstr):
696
+ return _decode_and_dealloc_raw_str( _raw_decodecfg_json(_str2cstr(cfgstr) ) )
697
+ functions['nc_cfgstr2json']=nc_cfgstr2json
698
+
699
+ _raw_ncmat2json = _wrap('ncrystal_ncmat2json',_charptr,(_cstr,),hide=True)
700
+ def nc_ncmat2json(tdname):
701
+ return _decode_and_dealloc_raw_str( _raw_ncmat2json(_str2cstr(tdname) ) )
702
+ functions['nc_ncmat2json']=nc_ncmat2json
703
+
704
+ raw_proc_uid = _wrap('ncrystal_process_uid',_charptr,(ncrystal_process_t,),hide=True)
705
+ functions['procuid'] = lambda rawproc : int(_decode_and_dealloc_raw_str(raw_proc_uid(rawproc)))
706
+ raw_info_uid = _wrap('ncrystal_info_uid',_charptr,(ncrystal_info_t,),hide=True)
707
+ functions['infouid'] = lambda rawinfo : int(_decode_and_dealloc_raw_str(raw_info_uid(rawinfo)))
708
+ raw_info_underlyinguid = _wrap('ncrystal_info_underlyinguid',_charptr,(ncrystal_info_t,),hide=True)
709
+ functions['infouid_underlying'] = lambda rawinfo : int(_decode_and_dealloc_raw_str(raw_info_underlyinguid(rawinfo)))
710
+
711
+ _raw_normcfgstr = _wrap('ncrystal_normalisecfg',_charptr,(_cstr,),hide=True)
712
+ def nc_normcfgstr(cfgstr):
713
+ raw_str = _raw_normcfgstr(_str2cstr(cfgstr))
714
+ if not raw_str:
715
+ return None
716
+ res=_cstr2str(ctypes.cast(raw_str,_cstr).value)
717
+ _raw_deallocstr(raw_str)
718
+ return res
719
+ functions['nc_normcfgstr']=nc_normcfgstr
720
+
721
+ _raw_gencfgdoc = _wrap('ncrystal_gencfgstr_doc',_charptr,(_int,),hide=True)
722
+ def nc_gencfgdoc(mode):
723
+ raw_str = _raw_gencfgdoc(mode)
724
+ if not raw_str:
725
+ return None
726
+ res=_cstr2str(ctypes.cast(raw_str,_cstr).value)
727
+ _raw_deallocstr(raw_str)
728
+ return res
729
+ functions['nc_gencfgdoc']=nc_gencfgdoc
730
+
731
+ _raw_gettextdata = _wrap('ncrystal_get_text_data',_cstrp,(_cstr,),hide=True)
732
+ _raw_deallocstr = _wrap('ncrystal_dealloc_string',None,(_charptr,),hide=True)
733
+ _raw_deallocstrlist = _wrap('ncrystal_dealloc_stringlist',None,(_uint,_cstrp),hide=True)
734
+
735
+ def nc_gettextdata(name):
736
+ ll = _raw_gettextdata(_str2cstr(str(name)))
737
+ assert ll is not None
738
+ n = 5
739
+ def _decode( s ):
740
+ s=s.decode('utf-8')
741
+ return ( s.replace('\r\n','\n').replace('\r','\n')
742
+ if '\r' in s else s )
743
+ res = [_decode(ll[i]) for i in range(n)]
744
+ assert isinstance(res[0],str)
745
+ _raw_deallocstrlist(n,ll)
746
+ return res
747
+ functions['nc_gettextdata'] = nc_gettextdata
748
+
749
+ _raw_getfilelist = _wrap('ncrystal_get_file_list',None,(_uintp,_cstrpp),hide=True)
750
+ def ncrystal_get_filelist():
751
+ n,ll = _uint(),_cstrp()
752
+ _raw_getfilelist(n,ctypes.byref(ll))
753
+ assert n.value%4==0
754
+ res=[]
755
+ for i in range(n.value//4):
756
+ res += [ (ll[i*4].decode(),ll[i*4+1].decode(),
757
+ ll[i*4+2].decode(),ll[i*4+3].decode()) ]
758
+ _raw_deallocstrlist(n,ll)
759
+ return res
760
+ functions['ncrystal_get_filelist'] = ncrystal_get_filelist
761
+
762
+ _raw_getpluginlist = _wrap('ncrystal_get_plugin_list',None,(_uintp,_cstrpp),hide=True)
763
+ def ncrystal_get_pluginlist():
764
+ n,ll = _uint(),_cstrp()
765
+ _raw_getpluginlist(n,ctypes.byref(ll))
766
+ assert n.value%3==0
767
+ res=[]
768
+ for i in range(n.value//3):
769
+ pluginname,filename,plugintype=ll[i*3].decode(),ll[i*3+1].decode(),ll[i*3+2].decode()
770
+ res+=[(pluginname,filename,plugintype)]
771
+ _raw_deallocstrlist(n,ll)
772
+ return res
773
+ functions['ncrystal_get_pluginlist'] = ncrystal_get_pluginlist
774
+
775
+ _wrap('ncrystal_add_custom_search_dir',None,(_cstr,))
776
+ _wrap('ncrystal_remove_custom_search_dirs',None,tuple())
777
+ _wrap('ncrystal_enable_abspaths',None,(_int,))
778
+ _wrap('ncrystal_enable_relpaths',None,(_int,))
779
+ _wrap('ncrystal_enable_stddatalib',None,(_int,_cstr))
780
+ _wrap('ncrystal_enable_stdsearchpath',None,(_int,))
781
+ _wrap('ncrystal_remove_all_data_sources',None,tuple())
782
+ _wrap('ncrystal_enable_factory_threadpool',None,(_uint,))
783
+
784
+ _raw_benchloadcfg = _wrap('ncrystal_benchloadcfg',_dbl,(_cstr,_int,_int),hide=True)
785
+ def ncrystal_benchloadcfg( cfgstr, do_scatter, nrepeat ):
786
+ arg_doscatter = _int( 1 if do_scatter else 0)
787
+ arg_nrepeat = _int( int(nrepeat) )
788
+ res=_raw_benchloadcfg(_str2cstr(cfgstr),arg_doscatter,arg_nrepeat)
789
+ return float(res)
790
+ functions['benchloadcfg'] = ncrystal_benchloadcfg
791
+
792
+ _MSGHANDLERFCTTYPE = ctypes.CFUNCTYPE( None, _cstr, _uint )
793
+ _raw_setmsghandler = _wrap('ncrystal_setmsghandler',None,(_MSGHANDLERFCTTYPE,),hide=True)
794
+ def ncrystal_setmsghandler(pyhandler):
795
+ #Set msg handler function, keeping references as needed (otherwise fct ptrs
796
+ #kept on C++ side will suddenly stop working!) and casting None to a null-ptr.
797
+ def handler( msg, msgtype ):
798
+ #NB: We could instead consider converting to bytes rather than str
799
+ #in case msgtype==2 (raw output):
800
+ pyhandler( _cstr2str(msg), int(msgtype) )
801
+ if not handler:
802
+ keepalive=(None,None,ctypes.cast(None, _MSGHANDLERFCTTYPE))
803
+ else:
804
+ keepalive=(pyhandler,handler,_MSGHANDLERFCTTYPE(handler))#keep refs!
805
+ _keepalive.append(keepalive)
806
+ _raw_setmsghandler(keepalive[-1])
807
+ functions['setmsghandler'] = ncrystal_setmsghandler
808
+
809
+ _raw_runmmcsim_stdengine = _wrap('ncrystal_runmmcsim_stdengine',None,
810
+ (_uint,_uint,
811
+ _cstr,_cstr,_cstr,
812
+ _charptrptr,_uintp,_dblpp,_dblpp),
813
+ hide=True)
814
+ def nc_runmmcsim_stdengine( nthreads,
815
+ tally_detail_lvl,
816
+ mat_cfgstr,
817
+ mmc_geomcfg,
818
+ mmc_srccfg ):
819
+ nthreads_ = _uint(int(nthreads))
820
+ assert 0<=tally_detail_lvl<=2
821
+ tally_detail_lvl_ = _uint(int(tally_detail_lvl))
822
+ mat_cfgstr_ = _str2cstr(mat_cfgstr)
823
+ mmc_geomcfg_ = _str2cstr(mmc_geomcfg)
824
+ mmc_srccfg_ = _str2cstr(mmc_srccfg)
825
+ t_json = _charptr()
826
+ t_exitangle_nbins = _uint()
827
+ t_exitangle_ct = _dblp()
828
+ t_exitangle_errsq = _dblp()
829
+ _raw_runmmcsim_stdengine( nthreads_,
830
+ tally_detail_lvl_,
831
+ mat_cfgstr_,
832
+ mmc_geomcfg_,
833
+ mmc_srccfg_,
834
+ t_json,
835
+ t_exitangle_nbins,
836
+ ctypes.byref(t_exitangle_ct),
837
+ ctypes.byref(t_exitangle_errsq) )
838
+ if t_json is not None:
839
+ t_json_cstr = ctypes.cast(t_json,_cstr).value
840
+ if t_json_cstr is not None:
841
+ _ = _cstr2str(t_json_cstr)
842
+ _raw_deallocstr(t_json)
843
+ t_json = _
844
+ else:
845
+ t_json = None
846
+
847
+ tally_exitangle_contents = _cptr_to_nparray( t_exitangle_ct, t_exitangle_nbins )
848
+ tally_exitangle_errsq = _cptr_to_nparray( t_exitangle_errsq, t_exitangle_nbins )
849
+ return tally_exitangle_contents,tally_exitangle_errsq,t_json
850
+
851
+ functions['runmmcsim_stdengine']=nc_runmmcsim_stdengine
852
+
853
+
854
+ return functions