forked from weft/warp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ace.pyx
1791 lines (1479 loc) · 61.9 KB
/
ace.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module is for reading ACE-format cross sections. ACE stands for "A
Compact ENDF" format and originated from work on MCNP_. It is used in a number
of other Monte Carlo particle transport codes.
ACE-format cross sections are typically generated from ENDF_ files through a
cross section processing program like NJOY_. The ENDF data consists of tabulated
thermal data, ENDF/B resonance parameters, distribution parameters in the
unresolved resonance region, and tabulated data in the fast region. After the
ENDF data has been reconstructed and Doppler-broadened, the ACER module
generates ACE-format cross sections.
.. _MCNP: https://laws.lanl.gov/vhosts/mcnp.lanl.gov/
.. _NJOY: http://t2.lanl.gov/codes.shtml
.. _ENDF: http://www.nndc.bnl.gov/endf
.. moduleauthor:: Paul Romano <[email protected]>, Anthony Scopatz <[email protected]>
"""
from __future__ import division, unicode_literals
import io
import struct
from warnings import warn
from collections import OrderedDict
cimport numpy as np
import numpy as np
from bisect import bisect_right
from libc.stdlib cimport malloc, free
from libc.stdlib cimport atof
from libc.string cimport strtok, strcpy, strncpy
from cython.operator cimport dereference as deref
cdef bint NP_LE_V15 = int(np.__version__.split('.')[1]) <= 5 and np.__version__.startswith('1')
def fromstring_split(s, sep=None, dtype=float):
"""A replacement for numpy.fromstring() using the Python str.split()
and np.array().
Parameters
----------
s : str
String of data.
sep : str or None
String of separator characters, has the same meaning as in
str.split().
dtype : np.dtype
Numpy dtype to cast elements enough.
Returns
-------
data : ndarray, 1d
Will always return a 1d array of dtype. You must reshape to the
appropriate shape.
See Also
--------
fromstring_token : May faster depending on the data.
"""
cdef list rawdata
rawdata = s.split(sep)
return np.array(rawdata, dtype=dtype)
def fromstring_token(s, sep=" ", bint inplace=False, int maxsize=-1):
"""A replacement for numpy.fromstring() using the C standard
library atof() and strtok() functions.
Parameters
----------
s : str
String of data.
sep : str
String of separator characters. Unlike numpy.fromstring(),
all characters are separated on independently.
inplace : bool
Whether s should tokenized in-place or whether a copy should
be made. If done in-place, the first instance of sep between
any tokens will replaced with the NULL character.
maxsize : int
Specifies the size of the array to pre-allocate. If negative,
this will be set to the maximum possible number of elements,
ie len(s)/2 + 1.
Returns
-------
data : ndarray, 1d, float64
Will always return a 1d float64 array. You must cast and reshape
to the appropriate type and shape.
See Also
--------
fromstring_split : May faster depending on the data.
"""
cdef char* cstring
cdef char* cs
cdef char* csep
cdef int i, I
cdef np.ndarray[np.float64_t, ndim=1] cdata
s_bytes = s.encode()
I = len(s_bytes)
sep_bytes = sep.encode()
csep = sep_bytes
if inplace:
cs = s_bytes
else:
cs = <char *> malloc(I * sizeof(char))
strcpy(cs, s_bytes)
if maxsize < 0:
maxsize = (I // 2) + 1
data = np.empty(maxsize, dtype=np.float64)
cdata = data
i = 0
cstring = strtok(cs, csep)
while cstring != NULL:
cdata[i] = atof(cstring)
cstring = strtok(NULL, csep)
i += 1
if not inplace:
free(cs)
data = data[:i].copy()
return data
def ascii_to_binary(ascii_file, binary_file):
"""Convert an ACE file in ASCII format (type 1) to binary format (type 2).
Parameters
----------
ascii_file : str
Filename of ASCII ACE file
binary_file : str
Filename of binary ACE file to be written
"""
# Open ASCII file
ascii = open(ascii_file, 'r')
# Set default record length
record_length = 4096
# Read data from ASCII file
lines = ascii.readlines()
ascii.close()
# Open binary file
binary = open(binary_file, 'wb')
idx = 0
while idx < len(lines):
#check if it's a > 2.0.0 version header
if lines[idx].split()[0][1] == '.':
if lines[idx + 1].split()[3] == '3':
idx = idx + 3
else:
raise NotImplementedError('Only backwards compatible ACE'
'headers currently supported')
# Read/write header block
hz = lines[idx][:10].encode('UTF-8')
aw0 = float(lines[idx][10:22])
tz = float(lines[idx][22:34])
hd = lines[idx][35:45].encode('UTF-8')
hk = lines[idx + 1][:70].encode('UTF-8')
hm = lines[idx + 1][70:80].encode('UTF-8')
binary.write(struct.pack(str('=10sdd10s70s10s'), hz, aw0, tz, hd, hk, hm))
# Read/write IZ/AW pairs
data = ' '.join(lines[idx + 2:idx + 6]).split()
iz = list(map(int, data[::2]))
aw = list(map(float, data[1::2]))
izaw = [item for sublist in zip(iz, aw) for item in sublist]
binary.write(struct.pack(str('=' + 16*'id'), *izaw))
# Read/write NXS and JXS arrays. Null bytes are added at the end so
# that XSS will start at the second record
nxs = list(map(int, ' '.join(lines[idx + 6:idx + 8]).split()))
jxs = list(map(int, ' '.join(lines[idx + 8:idx + 12]).split()))
binary.write(struct.pack(str('=16i32i{0}x'.format(record_length - 500)),
*(nxs + jxs)))
# Read/write XSS array. Null bytes are added to form a complete record
# at the end of the file
n_lines = (nxs[0] + 3)//4
xss = list(map(float, ' '.join(lines[
idx + 12:idx + 12 + n_lines]).split()))
extra_bytes = record_length - ((len(xss)*8 - 1) % record_length + 1)
binary.write(struct.pack(str('={0}d{1}x'.format(nxs[0], extra_bytes)),
*xss))
# Advance to next table in file
idx += 12 + n_lines
# Close binary file
binary.close()
class Library(object):
"""
A Library objects represents an ACE-formatted file which may contain
multiple tables with data.
Parameters
----------
filename : str
Path of the ACE library file to load.
Attributes
----------
binary : bool
Identifies Whether the library is in binary format or not
tables : dict
Dictionary whose keys are the names of the ACE tables and whose
values are the instances of subclasses of AceTable (e.g. NeutronTable)
verbose : bool
Determines whether output is printed to the stdout when reading a
Library
"""
def __init__(self, filename):
# Determine whether file is ASCII or binary
self.f = None
try:
self.f = io.open(filename, 'rb')
# Grab 10 lines of the library
sb = b''.join([self.f.readline() for i in range(10)])
# Try to decode it with ascii
sd = sb.decode('ascii')
# No exception so proceed with ASCII - reopen in non-binary
self.f.close()
self.f = io.open(filename, 'r')
self.f.seek(0)
self.binary = False
except UnicodeDecodeError:
self.f.close()
self.f = open(filename, 'rb')
self.binary = True
# Set verbosity
self.verbose = False
self.tables = {}
def read(self, table_names=None):
"""read(table_names=None)
Read through and parse the ACE-format library.
Parameters
----------
table_names : None, str, or iterable, optional
Tables from the file to read in. If None, reads in all of the
tables. If str, reads in only the single table of a matching name.
"""
if isinstance(table_names, basestring):
table_names = [table_names]
if table_names is not None:
table_names = set(table_names)
if self.binary:
self._read_binary(table_names)
else:
self._read_ascii(table_names)
def _read_binary(self, table_names, recl_length=4096, entries=512):
while True:
start_position = self.f.tell()
# Check for end-of-file
if len(self.f.read(1)) == 0:
return
self.f.seek(start_position)
# Read name, atomic mass ratio, temperature, date, comment, and
# material
name, awr, temp, date, comment, mat = \
struct.unpack(str('=10sdd10s70s10s'), self.f.read(116))
name = name.strip()
# Read ZAID/awr combinations
data = struct.unpack(str('=' + 16*'id'), self.f.read(192))
# Read NXS
nxs = list(struct.unpack(str('=16i'), self.f.read(64)))
# Determine length of XSS and number of records
length = nxs[0]
n_records = (length + entries - 1)//entries
# name is bytes, make it a string
name = name.decode()
# verify that we are supposed to read this table in
if (table_names is not None) and (name not in table_names):
self.f.seek(start_position + recl_length*(n_records + 1))
continue
# ensure we have a valid table type
if 0 == len(name) or name[-1] not in table_types:
# TODO: Make this a proper exception.
print("Unsupported table: " + name)
self.f.seek(start_position + recl_length*(n_records + 1))
continue
# get the table
table = table_types[name[-1]](name, awr, temp)
if self.verbose:
temp_in_K = round(temp * 1e6 / 8.617342e-5)
print("Loading nuclide {0} at {1} K".format(name, temp_in_K))
self.tables[name] = table
# Read JXS
table.jxs = list(struct.unpack(str('=32i'), self.f.read(128)))
# Read XSS
self.f.seek(start_position + recl_length)
table.xss = list(struct.unpack(str('={0}d'.format(length)),
self.f.read(length*8)))
# Insert empty object at beginning of NXS, JXS, and XSS
# arrays so that the indexing will be the same as
# Fortran. This makes it easier to follow the ACE format
# specification.
table.nxs = nxs
table.nxs.insert(0, 0)
table.nxs = np.array(table.nxs, dtype=int)
table.jxs.insert(0, 0)
table.jxs = np.array(table.jxs, dtype=int)
table.xss.insert(0, 0.0)
table.xss = np.array(table.xss, dtype=float)
# Read all data blocks
table._read_all()
# Advance to next record
self.f.seek(start_position + recl_length*(n_records + 1))
def _read_ascii(self, table_names):
cdef list lines, rawdata
f = self.f
tables_seen = set()
cdef int i
lines = [f.readline() for i in range(13)]
while (0 != len(lines)) and (lines[0] != ''):
# Read name of table, atomic mass ratio, and temperature. If first
# line is empty, we are at end of file
# check if it's a 2.0 style header
if lines[0].split()[0][1] == '.':
words = lines[0].split()
version = words[0]
name = words[1]
name_old = lines[3].split()[0] # old style name, same as in xsdir
if len(words) == 3:
source = words[2]
words = lines[1].split()
awr = float(words[0])
temp = float(words[1])
commentlines = int(words[3])
for i in range(commentlines):
lines.pop(0)
lines.append(f.readline())
else:
words = lines[0].split()
name = words[0]
awr = float(words[1])
temp = float(words[2])
datastr = '0 ' + ' '.join(lines[6:8])
nxs = fromstring_split(datastr, dtype=int)
n_lines = (nxs[1] + 3)//4
n_bytes = len(lines[-1]) * (n_lines - 2) + 1
# Ensure that we have more tables to read in
if (table_names is not None) and (table_names < tables_seen):
break
tables_seen.add(name)
# verify that we are suppossed to read this table in
if (table_names is not None) and (name not in table_names):
cur = f.tell()
f.seek(cur + n_bytes)
f.readline()
lines = [f.readline() for i in range(13)]
continue
# ensure we have a valid table type
if 0 == len(name) or name[-1] not in table_types:
warn("Unsupported table: " + name, RuntimeWarning)
cur = f.tell()
f.seek(cur + n_bytes)
f.readline()
lines = [f.readline() for i in range(13)]
continue
# read and and fix over-shoot
lines += f.readlines(n_bytes)
if 12+n_lines < len(lines):
goback = sum([len(line) for line in lines[12+n_lines:]])
lines = lines[:12+n_lines]
cur = f.tell()
f.seek(cur - goback)
# get the table
table = table_types[name[-1]](name, awr, temp)
if self.verbose:
temp_in_K = round(temp * 1e6 / 8.617342e-5)
print("Loading nuclide {0} at {1} K".format(name, temp_in_K))
self.tables[name] = table
# add the old style name if there
try:
name_old
except:
pass
else:
self.tables[name_old] = table
# Read comment
table.comment = lines[1].strip()
# Add NXS, JXS, and XSS arrays to table
# Insert empty object at beginning of NXS, JXS, and XSS
# arrays so that the indexing will be the same as
# Fortran. This makes it easier to follow the ACE format
# specification.
table.nxs = nxs
datastr = '0 ' + ' '.join(lines[8:12])
table.jxs = fromstring_split(datastr, dtype=int)
datastr = '0.0 ' + ''.join(lines[12:12+n_lines])
if NP_LE_V15:
#table.xss = np.fromstring(datastr, sep=" ")
table.xss = fromstring_split(datastr, dtype=float)
else:
table.xss = fromstring_token(datastr, inplace=True, maxsize=4*n_lines+1)
# Read all data blocks
table._read_all()
lines = [f.readline() for i in range(13)]
f.seek(0)
def find_table(self, name):
"""find_table(name)
Returns a cross-section table with a given name.
Parameters
----------
name : str
Name of the cross-section table, e.g. 92235.70c
"""
return self.tables.get(name, None)
def __del__(self):
if self.f is not None:
self.f.close()
class AceTable(object):
"""Abstract superclass of all other classes for cross section tables."""
def __init__(self, name, awr, temp):
self.name = name
self.awr = awr
self.temp = temp
def _read_all(self):
raise NotImplementedError
class NeutronTable(AceTable):
"""A NeutronTable object contains continuous-energy neutron interaction data
read from an ACE-formatted Type I table. These objects are not normally
instantiated by the user but rather created when reading data using a
Library object and stored within the ``tables`` attribute of a Library
object.
Parameters
----------
name : str
ZAID identifier of the table, e.g. '92235.70c'.
awr : float
Atomic mass ratio of the target nuclide.
temp : float
Temperature of the target nuclide in eV.
Attributes
----------
awr : float
Atomic mass ratio of the target nuclide.
energy : list of floats
The energy values (MeV) at which reaction cross-sections are tabulated.
name : str
ZAID identifier of the table, e.g. 92235.70c.
nu_p_energy : list of floats
Energies in MeV at which the number of prompt neutrons emitted per
fission is tabulated.
nu_p_type : str
Indicates how number of prompt neutrons emitted per fission is
stored. Can be either "polynomial" or "tabular".
nu_p_value : list of floats
The number of prompt neutrons emitted per fission, if data is stored in
"tabular" form, or the polynomial coefficients for the "polynomial"
form.
nu_t_energy : list of floats
Energies in MeV at which the total number of neutrons emitted per
fission is tabulated.
nu_t_type : str
Indicates how total number of neutrons emitted per fission is
stored. Can be either "polynomial" or "tabular".
nu_t_value : list of floats
The total number of neutrons emitted per fission, if data is stored in
"tabular" form, or the polynomial coefficients for the "polynomial"
form.
reactions : list of Reactions
A list of Reaction instances containing the cross sections, secondary
angle and energy distributions, and other associated data for each
reaction for this nuclide.
sigma_a : list of floats
The microscopic absorption cross section for each value on the energy
grid.
sigma_t : list of floats
The microscopic total cross section for each value on the energy grid.
temp : float
Temperature of the target nuclide in eV.
"""
def __init__(self, name, awr, temp):
super(NeutronTable, self).__init__(name, awr, temp)
self.reactions = OrderedDict()
self.photon_reactions = OrderedDict()
def __repr__(self):
if hasattr(self, 'name'):
return "<ACE Continuous-E Neutron Table: {0}>".format(self.name)
else:
return "<ACE Continuous-E Neutron Table>"
def _read_all(self):
self._read_cross_sections()
self._read_nu()
self._read_angular_distributions()
self._read_energy_distributions()
self._read_gpd()
self._read_mtrp()
self._read_lsigp()
self._read_sigp()
self._read_landp()
self._read_andp()
# Read LDLWP block
# Read DLWP block
# Read YP block
self._read_yp()
self._read_fis()
self._read_unr()
def _read_cross_sections(self):
"""Reads and parses the ESZ, MTR, LQR, TRY, LSIG, and SIG blocks. These
blocks contain the energy grid, all reaction cross sections, the total
cross section, average heating numbers, and a list of reactions with
their Q-values and multiplicites.
"""
cdef int n_energies, n_reactions, loc
# Determine number of energies on nuclide grid and number of reactions
# excluding elastic scattering
n_energies = self.nxs[3]
n_reactions = self.nxs[4]
# Read energy grid and total, absorption, elastic scattering, and
# heating cross sections -- note that this appear separate from the rest
# of the reaction cross sections
arr = self.xss[self.jxs[1]:self.jxs[1] + 5*n_energies]
arr.shape = (5, n_energies)
self.energy, self.sigma_t, self.sigma_a, sigma_el, self.heating = arr
# Create elastic scattering reaction
elastic_scatter = Reaction(2, self)
elastic_scatter.Q = 0.0
elastic_scatter.IE = 0
elastic_scatter.multiplicity = 1
elastic_scatter.sigma = sigma_el
self.reactions[2] = elastic_scatter
# Create all other reactions with MT values
mts = np.asarray(self.xss[self.jxs[3]:self.jxs[3] + n_reactions], dtype=int)
qvalues = np.asarray(self.xss[self.jxs[4]:self.jxs[4] +
n_reactions], dtype=float)
tys = np.asarray(self.xss[self.jxs[5]:self.jxs[5] + n_reactions], dtype=int)
# Create all reactions other than elastic scatter
reactions = [(mt, Reaction(mt, self)) for mt in mts]
self.reactions.update(reactions)
# Loop over all reactions other than elastic scattering
for i, reaction in enumerate(list(self.reactions.values())[1:]):
# Copy Q values and multiplicities and determine if scattering
# should be treated in the center-of-mass or lab system
reaction.Q = qvalues[i]
reaction.multiplicity = abs(tys[i])
reaction.center_of_mass = (tys[i] < 0)
# Get locator for cross-section data
loc = int(self.xss[self.jxs[6] + i])
# Determine starting index on energy grid
reaction.IE = int(self.xss[self.jxs[7] + loc - 1]) - 1
# Determine number of energies in reaction
n_energies = int(self.xss[self.jxs[7] + loc])
# Read reaction cross section
reaction.sigma = self.xss[self.jxs[7] + loc + 1:
self.jxs[7] + loc + 1 + n_energies]
def _read_nu(self):
"""Read the NU block -- this contains information on the prompt
and delayed neutron precursor yields, decay constants, etc
"""
cdef int ind, i, jxs2, KNU, LNU, NR, NE, NC
jxs2 = self.jxs[2]
# No NU block
if jxs2 == 0:
return
# Either prompt nu or total nu is given
if self.xss[jxs2] > 0:
KNU = jxs2
LNU = int(self.xss[KNU])
# Polynomial function form of nu
if LNU == 1:
self.nu_t_type = "polynomial"
NC = int(self.xss[KNU+1])
coeffs = self.xss[KNU+2 : KNU+2+NC]
# Tabular data form of nu
elif LNU == 2:
self.nu_t_type = "tabular"
NR = int(self.xss[KNU+1])
if NR > 0:
self.nu_t_interp_NBT = self.xss[KNU+2 : KNU+2+NR ]
self.nu_t_interp_INT = self.xss[KNU+2+NR : KNU+2+2*NR]
else:
self.nu_t_interp_INT = 2
NE = int(self.xss[KNU+2+2*NR])
self.nu_t_energy = self.xss[KNU+3+2*NR : KNU+3+2*NR+NE ]
self.nu_t_value = self.xss[KNU+3+2*NR+NE : KNU+3+2*NR+2*NE]
# Both prompt nu and total nu
elif self.xss[jxs2] < 0:
KNU = jxs2 + 1
LNU = int(self.xss[KNU])
# Polynomial function form of nu
if LNU == 1:
self.nu_p_type = "polynomial"
NC = int(self.xss[KNU+1])
coeffs = self.xss[KNU+2 : KNU+2+NC]
# Tabular data form of nu
elif LNU == 2:
self.nu_p_type = "tabular"
NR = int(self.xss[KNU+1])
if NR > 0:
self.nu_p_interp_NBT = self.xss[KNU+2 : KNU+2+NR ]
self.nu_p_interp_INT = self.xss[KNU+2+NR : KNU+2+2*NR]
else:
self.nu_p_interp_INT = 2
NE = int(self.xss[KNU+2+2*NR])
self.nu_p_energy = self.xss[KNU+3+2*NR : KNU+3+2*NR+NE ]
self.nu_p_value = self.xss[KNU+3+2*NR+NE : KNU+3+2*NR+2*NE]
KNU = jxs2 + int(abs(self.xss[jxs2])) + 1
LNU = int(self.xss[KNU])
# Polynomial function form of nu
if LNU == 1:
self.nu_t_type = "polynomial"
NC = int(self.xss[KNU+1])
coeffs = self.xss[KNU+2 : KNU+2+NC]
# Tabular data form of nu
elif LNU == 2:
self.nu_t_type = "tabular"
NR = int(self.xss[KNU+1])
if NR > 0:
self.nu_t_interp_NBT = self.xss[KNU+2 : KNU+2+NR ]
self.nu_t_interp_INT = self.xss[KNU+2+NR : KNU+2+2*NR]
else:
self.nu_t_interp_INT = 2
NE = int(self.xss[KNU+2+2*NR])
self.nu_t_energy = self.xss[KNU+3+2*NR : KNU+3+2*NR+NE ]
self.nu_t_value = self.xss[KNU+3+2*NR+NE : KNU+3+2*NR+2*NE]
# Check for delayed nu data
if self.jxs[24] > 0:
KNU = self.jxs[24]
NR = int(self.xss[KNU+1])
if NR > 0:
self.nu_d_interp_NBT = self.xss[KNU+2 : KNU+2+NR ]
self.nu_d_interp_INT = self.xss[KNU+2+NR : KNU+2+2*NR]
NE = int(self.xss[KNU+2+2*NR])
self.nu_d_energy = self.xss[KNU+3+2*NR : KNU+3+2*NR+NE ]
self.nu_d_value = self.xss[KNU+3+2*NR+NE : KNU+3+2*NR+2*NE]
# Delayed neutron precursor distribution
self.nu_d_precursor_const = {}
self.nu_d_precursor_energy = {}
self.nu_d_precursor_prob = {}
i = self.jxs[25]
n_group = self.nxs[8]
for group in range(n_group):
self.nu_d_precursor_const[group] = self.xss[i]
NR = int(self.xss[i+1])
if NR > 0:
self.nu_d_precursor_interp_NBT = self.xss[i+2 : i+2+NR]
self.nu_d_precursor_interp_INT = self.xss[i+2+NR : i+2+2*NR]
else:
self.nu_d_precursor_interp_INT = 2
NE = int(self.xss[i+2+2*NR])
self.nu_d_precursor_energy[group] = self.xss[i+3+2*NR : i+3+2*NR+NE ]
self.nu_d_precursor_prob[group] = self.xss[i+3+2*NR+NE : i+3+2*NR+2*NE]
i = i+3+2*NR+2*NE
# Energy distribution for delayed fission neutrons
LED = self.jxs[26]
self.nu_d_energy_dist = []
for group in range(n_group):
location_start = self.xss[LED + group]
energy_dist = self._get_energy_distribution(
location_start, delayed_n=True)
self.nu_d_energy_dist.append(energy_dist)
def _read_angular_distributions(self):
"""Find the angular distribution for each reaction MT
"""
cdef int ind, i, j, n_reactions, n_energies, n_bins
cdef dict ang_cos, ang_pdf, ang_cdf
# Number of reactions with secondary neutrons (including elastic
# scattering)
n_reactions = self.nxs[5] + 1
# Angular distribution for all reactions with secondary neutrons
for i, reaction in enumerate(list(self.reactions.values())[:n_reactions]):
loc = int(self.xss[self.jxs[8] + i])
# Check if angular distribution data exist
if loc == -1:
# Angular distribution data are specified through LAWi
# = 44 in the DLW block
continue
elif loc == 0:
# No angular distribution data are given for this
# reaction, isotropic scattering is asssumed (in CM if
# TY < 0 and in LAB if TY > 0)
continue
ind = self.jxs[9] + loc
# Number of energies at which angular distributions are tabulated
n_energies = int(self.xss[ind - 1])
# Incoming energy grid
reaction.ang_energy_in = self.xss[ind:ind + n_energies]
ind += n_energies
# Read locations for angular distributions
locations = np.asarray(self.xss[ind:ind + n_energies], dtype=int)
ind += n_energies
ang_cos = {}
ang_pdf = {}
ang_cdf = {}
ang_intt= {}
for j, location in enumerate(locations):
if location > 0:
# Equiprobable 32 bin distribution
# print([reaction,'equiprobable'])
ang_cos[j] = self.xss[ind:ind + 33]
ind += 33
elif location < 0:
# Tabular angular distribution
JJ = int(self.xss[ind])
n_bins = int(self.xss[ind + 1])
ind += 2
ang_dat = self.xss[ind:ind + 3*n_bins]
ang_dat.shape = (3, n_bins)
ang_cos[j], ang_pdf[j], ang_cdf[j] = ang_dat
ang_intt[j] = JJ
ind += 3 * n_bins
else:
# Isotropic angular distribution
ang_cos = np.array([-1., 0., 1.])
ang_pdf = np.array([0.5, 0.5, 0.5])
ang_cdf = np.array([0., 0.5, 1.])
ang_intt= np.array([0])
reaction.ang_cos = ang_cos
reaction.ang_pdf = ang_pdf
reaction.ang_cdf = ang_cdf
reaction.ang_intt= ang_intt
def _read_energy_distributions(self):
"""Determine the energy distribution for secondary neutrons for
each reaction MT
"""
cdef int i
# Number of reactions with secondary neutrons other than elastic
# scattering. For elastic scattering, the outgoing energy can be
# determined from kinematics.
n_reactions = self.nxs[5]
for i, reaction in enumerate(list(self.reactions.values())[1:n_reactions + 1]):
# Determine locator for ith energy distribution
location_start = int(self.xss[self.jxs[10] + i])
# Read energy distribution data
reaction.energy_dist = self._get_energy_distribution(location_start)
def _get_energy_distribution(self, location_start, delayed_n=False):
"""Returns an EnergyDistribution object from data read in starting at
location_start.
"""
cdef int ind, i, n_reactions, NE, n_regions, location_next_law, law, location_data, NPE, NPA
# Create EnergyDistribution object
edist = EnergyDistribution()
# Determine location of energy distribution
if delayed_n:
location_dist = self.jxs[27]
else:
location_dist = self.jxs[11]
# Set starting index for energy distribution
ind = location_dist + location_start - 1
location_next_law = int(self.xss[ind])
law = int(self.xss[ind+1])
location_data = int(self.xss[ind+2])
# Number of interpolation regions for law applicability regime
n_regions = int(self.xss[ind+3])
ind += 4
if n_regions > 0:
dat = np.asarray(self.xss[ind:ind + 2*n_regions], dtype=int)
dat.shape = (2, n_regions)
interp_NBT, interp_INT = dat
ind += 2 * n_regions
# Determine tabular energy points and probability of law
# validity
NE = int(self.xss[ind])
dat = self.xss[ind+1:ind+1+2*NE]
dat.shape = (2, NE)
edist.energy, edist.pvalid = dat
edist.law = law
ind = location_dist + location_data - 1
if law == 1:
# Tabular equiprobable energy bins (ENDF Law 1)
n_regions = int(self.xss[ind])
ind += 1
if n_regions > 0:
dat = np.asarray(self.xss[ind:ind+2*n_regions], dtype=int)
dat.shape = (2, n_regions)
edist.NBT, edist.INT = dat
ind += 2 * n_regions
# Number of outgoing energies in each E_out table
NE = int(self.xss[ind])
edist.energy_in = self.xss[ind+1:ind+1+NE]
ind += 1 + NE
# Read E_out tables
NET = int(self.xss[ind])
dat = self.xss[ind+1:ind+1+3*NET]
dat.shape = (3, NET)
self.e_dist_energy_out1, self.e_dist_energy_out2, \
self.e_dist_energy_outNE = dat
ind += 1 + 3 * NET
elif law == 2:
# Discrete photon energy
self.e_dist_LP = int(self.xss[ind])
self.e_dist_EG = self.xss[ind+1]
ind += 2
elif law == 3:
# Level scattering (ENDF Law 3)
edist.data = self.xss[ind:ind+2]
ind += 2
elif law == 4:
# Continuous tabular distribution (ENDF Law 1)
n_regions = int(self.xss[ind])
ind += 1
if n_regions > 0:
dat = np.asarray(self.xss[ind:ind+2*n_regions], dtype=int)
dat.shape = (2, n_regions)
edist.NBT, edist.INT = dat
ind += 2 * n_regions
# Number of outgoing energies in each E_out table
NE = int(self.xss[ind])
edist.energy_in = self.xss[ind+1:ind+1+NE]
L = self.xss[ind+1+NE:ind+1+2*NE]
ind += 1 + 2*NE
nps = []
edist.intt = [] # Interpolation scheme (1=hist, 2=lin-lin)
edist.energy_out = [] # Outgoing E grid for each incoming E
edist.pdf = [] # Probability dist for " " "
edist.cdf = [] # Cumulative dist for " " "
for i in range(NE):
INTTp = int(self.xss[ind])
if INTTp > 10:
INTT = INTTp % 10
ND = (INTTp - INTT)/10
else:
INTT = INTTp
ND = 0
edist.intt.append(INTT)
#if ND > 0:
# print [reaction, ND, INTT]
NP = int(self.xss[ind+1])
nps.append(NP)
dat = self.xss[ind+2:ind+2+3*NP]
dat.shape = (3, NP)
edist.energy_out.append(dat[0])
edist.pdf.append(dat[1])
edist.cdf.append(dat[2])
ind += 2 + 3*NP
# convert to arrays if possible
edist.intt = np.array(edist.intt)
nps = np.array(nps)
if all((nps[1:] - nps[:-1]) == 0):
edist.energy_out = np.array(edist.energy_out)
edist.pdf = np.array(edist.pdf)
edist.cdf = np.array(edist.cdf)
elif law == 5:
# General evaporation spectrum (ENDF-5 File 5 LF=5)
n_regions = int(self.xss[ind])
ind += 1
if n_regions > 0:
dat = np.asarray(self.xss[ind:ind+2*n_regions], dtype=int)
dat.shape = (2, n_regions)
edist.NBT, edist.INT = dat
ind += 2 * n_regions
NE = int(self.xss[ind])
edist.energy_in = self.xss[ind+1:ind+1+NE]
edist.T = self.xss[ind+1+NE:ind+1+2*NE]
ind += 1+ 2*NE
NET = int(self.xss[ind])
edist.X = self.xss[ind+1:ind+1+NET]