forked from sbradnam/JADE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatreader.py
1234 lines (1004 loc) · 37.3 KB
/
matreader.py
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
# -*- coding: utf-8 -*-
# Created on 24/10/2019
# @author: Davide laghi
# Support classes for MCNP material card reader/writer
# Copyright 2021, the JADE Development Team. All rights reserved.
# This file is part of JADE.
# JADE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# JADE is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with JADE. If not, see <http://www.gnu.org/licenses/>.
# -------------------------------------
# == IMPORTS ==
# -------------------------------------
import re
import pandas as pd
from numjuggler import parser as par
from collections.abc import Sequence
from decimal import Decimal
import copy
import sys
import os
from contextlib import contextmanager
import warnings
# -------------------------------------
# == COMMON PATTERNS ==
# -------------------------------------
PAT_COMMENT = re.compile(r'[cC][\s\t]+')
PAT_MAT = re.compile(r'[\s\t]*[mM]\d+')
PAT_MX = re.compile(r'[\s\t]*mx\d+', re.IGNORECASE)
# -------------------------------------
# == CLASSES FOR MATERIAL READING ==
# -------------------------------------
class Zaid:
def __init__(self, fraction, element, isotope,
library, ab='', fullname=''):
"""
Object representing a Zaid
Parameters
----------
fraction : str/float
fraction of the zaid.
element : str
element part of the zaid (AA).
isotope : str
isotope part of the zaid (ZZZ).
library : str
library suffix (e.g. 99c).
ab : str, optional
abundance of the zaid in the material. The default is ''.
fullname : str, optional
formula name (e.g. H1). The default is ''.
Returns
-------
None.
"""
self.fraction = float(fraction)
self.element = element
self.isotope = isotope
self.library = library
self.ab = ab
self.fullname = fullname
if self.library is None:
self.name = self.element+self.isotope
else:
self.name = self.element+self.isotope+'.'+self.library
@classmethod
def from_string(cls, string):
"""
Generate a zaid object from an MCNP string
Parameters
----------
cls : matreader.Zaid
zaid to be created.
string : str
original MCNP string.
Returns
-------
Zaid
created zaid.
"""
# Divide fraction from zaid
patSpacing = re.compile(r'[\s\t]+')
items = patSpacing.split(string)
# ZAID
pieces = items[0].split('.')
# Try to identify library if present
try:
library = pieces[1]
except IndexError:
library = None
# Identify element and isotope
element = pieces[0][:-3]
isotope = pieces[0][-3:]
# identify fraction
fraction = items[1]
return cls(fraction, element, isotope, library)
def to_text(self):
"""
Get the zaid string ready for MCNP material card
Returns
-------
str
zaid string.
"""
fraction = "{:.6E}".format(Decimal(self.fraction))
if self.library is None:
zaidname = self.element+self.isotope
else:
zaidname = self.element+self.isotope+'.'+self.library
# Add INFO
try:
abundance = '%s' % float('%.5g' % float(self.ab))
except ValueError:
abundance = ''
abundance = 'AB(%) '+abundance
inline_comm = ' $ '+self.fullname
args = (zaidname, fraction, inline_comm, abundance)
return '{0:>15} {1:>18} {2:<12} {3:<10}'.format(*args)
def get_fullname(self, libmanager):
"""
Get the formula name of the zaid (e.g. H1)
Parameters
----------
libmanager : libmanager.LibManager
libmanager handling the libraries operations.
Returns
-------
formula : str
zaid formula name.
"""
name, formula = libmanager.get_zaidname(self)
return formula
# def update_info(self,ab,fullname):
# """
# Update zaid info
# """
# self.additional_info['ab'] = ab
# self.additional_info['fullname'] = fullname
class Element:
def __init__(self, zaidList):
"""
Generate an Element object starting from a list of zaids.
It will collapse multiple instance of a zaid into a single one
Parameters
----------
zaidList : list
list of zaids constituing the element.
Returns
-------
None.
"""
zaids = {}
for zaid in zaidList:
# If already in dic sum the fractions
if zaid.name in zaids.keys():
zaids[zaid.name] = zaids[zaid.name]+zaid.fraction
else:
zaids[zaid.name] = zaid.fraction
zaidList = []
for name, fraction in zaids.items():
zaidList.append(Zaid.from_string(name+' '+str(fraction)))
self.Z = zaid.element
self.zaids = zaidList
def update_zaidinfo(self, libmanager):
"""
Update zaids infos through a libmanager. Info are the formula name and
the abundance in the material.
Parameters
----------
libmanager : libmanager.LibManager
libmanager handling the libraries operations.
Returns
-------
None.
"""
tot_fraction = 0
for zaid in self.zaids:
tot_fraction = tot_fraction + zaid.fraction
for zaid in self.zaids:
fullname = zaid.get_fullname(libmanager)
ab = zaid.fraction/tot_fraction*100
# zaid.update_info(ab,fullname)
zaid.ab = ab
zaid.fullname = fullname
def get_fraction(self):
"""
Get the sum of the fraction of the zaids composing the element
Returns
-------
fraction : float
element fraction.
"""
fraction = 0
for zaid in self.zaids:
fraction = fraction+zaid.fraction
return fraction
class SubMaterial:
# init method for zaid
def __init__(self, name, zaidList, elemList=None, header=None,
additional_keys=[]):
"""
Generate a SubMaterial Object starting from a list of Zaid and
eventually Elements list
Parameters
----------
name : str
if the first submaterial, the name is the name of the material
(e.g. m1).
zaidList : list[Zaid]
list of zaids composing the submaterial.
elemList : list[Element], optional
list of elements composing the submaterial. The default is None.
header : str, optional
Header of the submaterial. The default is None.
additional_keys : list[str], optional
list of additional keywords in the submaterial. The default is [].
Returns
-------
None.
"""
# List of zaids object of the submaterial
self.zaidList = zaidList
# Name of the material
if name is not None:
self.name = name.strip() # Be sure to strip spaces
else:
self.name = None
# List of elements in material
if elemList is None:
self.collapse_zaids()
else:
self.elements = elemList
# Header of the submaterial
self.header = header
# Additional keys as plib,hlib etc.
self.additional_keys = additional_keys
@classmethod
def from_text(cls, text):
"""
Generate a submaterial from MCNP input text
Parameters
----------
cls : SubMaterial
submaterial to be generated.
text : list[str]
Original text of the MCNP input.
Returns
-------
SubMaterial
generated submaterial.
"""
# Useful patterns
patSpacing = re.compile(r'[\s\t]+')
patComment = PAT_COMMENT
patName = PAT_MAT
searchHeader = True
header = ''
zaidList = []
additional_keys_list = []
for line in text:
zaids = None
additional_keys = None
# Header MUST be at the top of the text block
if searchHeader:
# Get header
if patComment.match(line) is None:
searchHeader = False
# Special treatment for first line
try:
name = patName.match(line).group()
except AttributeError:
# There is no material name
name = None
pieces = patSpacing.split(line)
if len(pieces) > 1:
# CASE1: only material name+additional spacing
if pieces[1] == '':
pass # no more actions for this line
# CASE2: material name + zaids or only zaids
else:
if name is None:
start = 0
else:
start = patName.match(line).end()
zaids, additional_keys = readLine(line[start:])
# CASE3: only material name and no spacing
else:
pass # no more actions for this line
else:
header = header+line
continue
else:
zaids, additional_keys = readLine(line)
if zaids is not None:
zaidList.extend(zaids)
if additional_keys is not None:
additional_keys_list.extend(additional_keys)
return cls(name, zaidList, elemList=None, header=header[:-1],
additional_keys=additional_keys_list)
def collapse_zaids(self):
"""
Organize zaids into their elements and collapse mutiple istances
Returns
-------
None.
"""
elements = {}
for zaid in self.zaidList:
if zaid.element not in elements.keys():
elements[zaid.element] = [zaid]
else:
elements[zaid.element].append(zaid)
elemList = []
for element_tag, zaids in elements.items():
elemList.append(Element(zaids))
self.elements = elemList
def to_text(self):
"""
Write to text in MNCP format the submaterial
Returns
-------
str
formatted submaterial text.
"""
if self.header is not None:
text = self.header+'\n'
else:
text = ''
# if self.name is not None:
# text = text+'\n'+self.name
if self.elements is not None:
for elem in self.elements:
for zaid in elem.zaids:
text = text+zaid.to_text()+'\n'
else:
for zaid in self.zaidList:
text = text+zaid.to_text()+'\n'
# Add additional keys
if len(self.additional_keys) > 0:
text = text+'\t'
for key in self.additional_keys:
text = text+' '+key
return text.strip('\n')
def translate(self, newlib, lib_manager):
"""
This method implements the translation logic of JADE. All zaids are
translated accordingly to the newlib specified.
Parameters
----------
newlib : dict or str
There are a few ways that newlib can be provided:
1) str (e.g. 31c), the new library to translate to will be the
one indicated;
2) dic (e.g. {'98c' : '99c', '31c: 32c'}), the new library is
determined based on the old library of the zaid
3) dic (e.g. {'98c': [list of zaids], '31c': [list of zaids]}),
the new library to be used is explicitly stated depending
on the zaidnum.
lib_manager : LibManager
Object handling libraries operation.
Returns
-------
None.
"""
newzaids = []
for zaid in self.zaidList:
# Implement the capability to translate to different libraries
# depending on the starting one
if type(newlib) == dict:
# Check for which kind of dic it is
if type(list(newlib.values())[0]) == str:
# The assignment is based on old lib
try:
newtag = newlib[zaid.library]
except KeyError:
# the zaid should have been assigned to a library
raise ValueError('''
Zaid {} was not assigned to any library'''.format(zaid.name))
else:
# The assignment is explicit, all libs need to be searched
newtag = None
zaidnum = zaid.element+zaid.isotope
for lib, zaids in newlib.items():
if zaidnum in zaids:
newtag = lib
break
# Check that a library has been actually found
if newtag is None:
# the zaid should have been assigned to a library
raise ValueError('''
Zaid {} was not assigned to any library'''.format(zaid.name))
else:
newtag = newlib
try:
translation = lib_manager.convertZaid(zaid.element +
zaid.isotope, newtag)
except ValueError:
# No Available translation was found, ignore zaid
# Only video warning, to propagate to the log would be too much
print(' WARNING: no available translation was found for ' +
zaid.name+'.\n The zaid has been ignored. ')
continue
# Check if it is atomic or mass fraction
if float(zaid.fraction) < 0:
ref_mass = 0
for key, item in translation.items():
ref_mass = ref_mass + item[1]*item[2]
for key, item in translation.items():
fraction = str(item[1]*item[2]/ref_mass*zaid.fraction)
element = str(key)[:-3]
isotope = str(key)[-3:]
library = item[0]
newzaids.append(Zaid(fraction, element, isotope, library))
else:
for key, item in translation.items():
fraction = str(item[1]*zaid.fraction)
element = str(key)[:-3]
isotope = str(key)[-3:]
library = item[0]
newzaids.append(Zaid(fraction, element, isotope, library))
self.zaidList = newzaids
self.collapse_zaids()
def update_info(self, lib_manager):
"""
This methods allows to update the in-line comments for every zaids
containing additional information
Parameters
----------
lib_manager : libmanager.LibManager
Library manager for the conversion.
Returns
-------
None.
"""
self.collapse_zaids() # To be sure to have adjourned elements
for elem in self.elements:
elem.update_zaidinfo(lib_manager)
# TODO
# Here the zaidlist of the submaterial should be adjourned or the next
# collapse zaid will cancel the informations. If update info is used
# as last operations there are no problems.
def get_info(self, lib_manager):
"""
Returns DataFrame containing the different fractions of the elements
and zaids
Parameters
----------
lib_manager : libmanager.LibManager
Library manager for the conversion.
Returns
-------
df_el : pd.DataFrame
table of information of the submaterial on an elemental level.
df_zaids : pd.DataFrame
table of information of the submaterial on a zaid level.
"""
# dic_element = {'Element': [], 'Fraction': []}
# dic_zaids = {'Element': [], 'Zaid': [], 'Fraction': []}
dic_element = {'Element': [], 'Fraction': []}
dic_zaids = {'Element': [], 'Isotope': [], 'Fraction': []}
for elem in self.elements:
fraction = elem.get_fraction()
# dic_element['Element'].append(elem.Z)
dic_element['Fraction'].append(fraction)
for zaid in elem.zaids:
fullname = zaid.get_fullname(lib_manager)
elementname = fullname.split('-')[0]
# dic_zaids['Element'].append(elem.Z)
# dic_zaids['Zaid'].append(zaid.isotope)
dic_zaids['Element'].append(elementname)
dic_zaids['Isotope'].append(fullname + ' [' + str(zaid.element)
+ str(zaid.isotope)+']')
dic_zaids['Fraction'].append(zaid.fraction)
dic_element['Element'].append(elementname)
df_el = pd.DataFrame(dic_element)
df_zaids = pd.DataFrame(dic_zaids)
return df_el, df_zaids
def scale_fractions(self, norm_factor):
"""
Scale the zaids fractions using a normalizing factor
Parameters
----------
norm_factor : float
scaling factor.
Returns
-------
None.
"""
for zaid in self.zaidList:
zaid.fraction = zaid.fraction*norm_factor
self.collapse_zaids()
# Support function for Submaterial
def readLine(string):
patSpacing = re.compile(r'[\s\t]+')
patComment = re.compile(r'\$')
patnumber = re.compile(r'\d+')
pieces = patSpacing.split(string)
# kill first piece if it is void
if pieces[0] == '':
del pieces[0]
# kill last piece if it is void
if pieces[-1] == '':
del pieces[-1]
# kill comment section
i = 0
for i, piece in enumerate(pieces):
if patComment.match(pieces[i]) is not None:
del pieces[i:]
break
i = 0
zaids = []
additional_keys = None
while True:
try:
# Check if it is zaid or keyword
if patnumber.match(pieces[i]) is None or pieces[i] == '':
additional_keys = pieces[i:]
break
else:
zaidstring = pieces[i]+' '+pieces[i+1]
zaid = Zaid.from_string(zaidstring)
zaids.append(zaid)
i = i+2
except IndexError:
break
return zaids, additional_keys
class Material:
def __init__(self, zaids, elem, name, submaterials=None, mx_cards=[],
header=None):
"""
Object representing an MCNP material
Parameters
----------
zaids : list[zaids]
zaids composing the material.
elem : list[elem]
elements composing the material.
name : str
name of the material (e.g. m1).
submaterials : list[Submaterials], optional
list of submaterials composing the material. The default is None.
mx_cards : list, optional
list of mx_cards in the material if present. The default is [].
header : str, optional
material header. The default is None.
Returns
-------
None.
"""
self.zaids = zaids
self.elem = elem
self.submaterials = submaterials
self.name = name.strip()
self.mx_cards = mx_cards
self.header = header
# Adjust the submaterial and headers reading
try:
# The first submaterial header is actually the material header.
# If submat is void it has to be deleted (only header), otherwise
# it means it has no header
submat = submaterials[0]
if len(submat.zaidList) == 0: # Happens in reading from text
# self.header = submat.header
del self.submaterials[0]
# else:
# self.submaterials[0].header = None
except IndexError:
self.header = None
@classmethod
def from_text(cls, text):
"""
Create a material from MCNP formatted text
Parameters
----------
cls : TYPE
DESCRIPTION.
text : list[str]
MCNP formatted text.
Returns
-------
matreader.Material
material object created.
"""
# split the different submaterials
patC = PAT_COMMENT
pat_matHeader = PAT_MAT
inHeader = True
subtext = []
submaterials = []
for line in text:
checkComment = patC.match(line)
checkHeaderMat = pat_matHeader.match(line)
if checkHeaderMat is not None:
header = ''.join(subtext)
subtext = []
if inHeader:
subtext.append(line)
if checkComment is None: # The end of the header is found
inHeader = False
else:
if checkComment is None: # Still in the material
subtext.append(line)
else: # a new header starts
submaterials.append(SubMaterial.from_text(subtext))
inHeader = True
subtext = [line]
submaterials.append(SubMaterial.from_text(subtext))
return cls(None, None, submaterials[0].name, submaterials=submaterials,
header=header)
def to_text(self):
"""
Write the material to MCNP formatted text
Returns
-------
str
MCNP formatte text representing the material.
"""
if self.header is not None:
text = self.header.strip('\n')+'\n'+self.name.upper().strip('\n')
else:
text = self.name.upper()
if self.submaterials is not None:
for submaterial in self.submaterials:
text = text+'\n'+submaterial.to_text()
# Add mx cards
for mx in self.mx_cards:
for line in mx:
line = line.strip('\n')
text = text+'\n'+line.upper()
else:
text = ' Not supported yet, generate submaterials first'
pass # TODO
return text.strip('\n')
def translate(self, newlib, lib_manager, update=True):
"""
This method allows to translate all submaterials to another library
Parameters
----------
newlib : dict or str
There are a few ways that newlib can be provided:
1) str (e.g. 31c), the new library to translate to will be the
one indicated;
2) dic (e.g. {'98c' : '99c', '31c: 32c'}), the new library is
determined based on the old library of the zaid
3) dic (e.g. {'98c': [list of zaids], '31c': [list of zaids]}),
the new library to be used is explicitly stated depending
on the zaidnum.
lib_manager : libmanager.LibManager
object handling all libraries operations.
update : bool, optional
if True, material infos are updated. The default is True.
Returns
-------
None.
"""
for submat in self.submaterials:
submat.translate(newlib, lib_manager)
self.update_info(lib_manager)
def get_tot_fraction(self):
"""
Returns the total material fraction
"""
fraction = 0
for submat in self.submaterials:
for zaid in submat.zaidList:
fraction = fraction+zaid.fraction
return fraction
def add_mx(self, mx_cards):
"""
Add a list of mx_cards to the material
"""
self.mx_cards = mx_cards
def update_info(self, lib_manager):
"""
This methods allows to update the in-line comments for every zaids
containing additional information
lib_manager: (LibManager) Library manager for the conversion
"""
for submaterial in self.submaterials:
submaterial.update_info(lib_manager)
def switch_fraction(self, ftype, lib_manager, inplace=True):
"""
Switch between atom or mass fraction for the material card.
If the material is already switched the command is ignored.
Parameters
----------
ftype : str
Either 'mass' or 'atom' to chose the type of switch.
lib_manager : libmanager.LibManager
Handles zaid data.
inplace : bool
if True the densities of the isotopes are changed inplace,
otherwise a copy of the material is provided. DEFAULT is True
Raises
------
KeyError
if ftype is not either 'atom' or 'mass'.
Returns
-------
submaterials : list
list of the submaterials where fraction have been switched
"""
# Get total fraction
totf = self.get_tot_fraction()
new_submats = []
if ftype == 'atom': # mass2atom switch
if totf < 0: # Check if the switch must be effectuated
# x_n = (x_m/m)/sum(x_m/m)
# get sum(x_m/m)
norm = 0
for submat in self.submaterials:
for zaid in submat.zaidList:
atom_mass = lib_manager.get_zaid_mass(zaid)
norm = norm + (-1*zaid.fraction/atom_mass)
for submat in self.submaterials:
new_zaids = []
new_submat = copy.deepcopy(submat)
for zaid in submat.zaidList:
atom_mass = lib_manager.get_zaid_mass(zaid)
if inplace:
zaid.fraction = (-1*zaid.fraction/atom_mass)/norm
else:
newz = copy.deepcopy(zaid)
newz.fraction = (-1*zaid.fraction/atom_mass)/norm
new_zaids.append(newz)
new_submat.zaidList = new_zaids
new_submat.update_info(lib_manager)
new_submats.append(new_submat)
else:
new_submats = self.submaterials
elif ftype == 'mass': # atom2mass switch
if totf > 0: # Check if the switch must be effectuated
# x_n = (x_m*m)/sum(x_m*m)
# get sum(x_m*m)
norm = 0
for submat in self.submaterials:
for zaid in submat.zaidList:
atom_mass = lib_manager.get_zaid_mass(zaid)
norm = norm + (zaid.fraction*atom_mass)
for submat in self.submaterials:
new_zaids = []
new_submat = copy.deepcopy(submat)
for zaid in submat.zaidList:
atom_mass = lib_manager.get_zaid_mass(zaid)
if inplace:
zaid.fraction = (-1*zaid.fraction*atom_mass)/norm
else:
newz = copy.deepcopy(zaid)
newz.fraction = (-1*zaid.fraction*atom_mass)/norm
new_zaids.append(newz)
new_submat.zaidList = new_zaids
new_submat.update_info(lib_manager)
new_submats.append(new_submat)
else:
new_submats = self.submaterials
else:
raise KeyError(ftype+' is not a valid key error [atom, mass]')
self.update_info(lib_manager)
return new_submats
class MatCardsList(Sequence):
def __init__(self, materials):
"""
Object representing the list of materials included in an MCNP input.
This class is a child of the Sequence base class.
Parameters
----------
materials : list[Material]
list of materials.
Returns
-------
None.
"""
self.materials = materials
# Build also the dictionary
self.matdic = self._compute_dic()
def __len__(self):
return len(self.materials)
def __repr__(self):
return str(self.matdic)
def __getitem__(self, key):
if type(key) is int:
return self.materials[key]
else:
return self.matdic[key.upper()]
def append(self, material):
self.materials.append(material)
self.matdic = self._compute_dic()
def remove(self, item):
self.materials.remove(item) # TODO this should get the key instead
self.matdic = self._compute_dic()
def _compute_dic(self):
matdic = {}
for material in self.materials:
matdic[material.name.upper()] = material
return matdic
@classmethod
def from_input(cls, inputfile):
"""
This method use the numjuggler parser to help identify the mcards in
the input. Then the mcards are parsed using the classes defined in this
module
Parameters
----------
cls : TYPE
DESCRIPTION.
inputfile : os.PathLike
MCNP input file containing the material section.
Returns
-------