forked from acroucher/PyTOUGH
-
Notifications
You must be signed in to change notification settings - Fork 0
/
t2data.py
executable file
·1580 lines (1462 loc) · 81 KB
/
t2data.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
"""Class for TOUGH2 data"""
"""
Copyright 2011 University of Auckland.
This file is part of PyTOUGH.
PyTOUGH is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
PyTOUGH 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with PyTOUGH. If not, see <http://www.gnu.org/licenses/>."""
from fixed_format_file import *
from t2grids import *
from t2incons import *
from math import ceil
t2data_format_specification = {
'title':[['title'],['80s']],
'simulator':[['simulator'],['80s']],
'rocks1':[['name','nad','density','porosity','k1','k2','k3','conductivity','specific_heat'],
['5s','5d']+['10.4e']*7],
'rocks1.1':[['compressibility','expansivity','dry_conductivity','tortuosity','klinkenberg','xkd3','xkd4'], ['10.4e']*7],
'rocks1.2':[['type','']+['parameter']*7,['5d','5x']+['10.3e']*7],
'rocks1.3':[['type','']+['parameter']*7,['5d','5x']+['10.3e']*7],
'param1_autough2':[['max_iterations','print_level','max_timesteps','max_duration','print_interval',
'_option_str','diff0','texp','be'],
['2d']*2+['4d']*3+['24s']+['10.3e']*3],
'param1':[['max_iterations','print_level','max_timesteps','max_duration','print_interval','_option_str','texp','be'],
['2d']*2+['4d']*3+['24s']+['10.3e']*2],
'param2':[['tstart','tstop','const_timestep','max_timestep','print_block','','gravity','timestep_reduction','scale'],
['10.3e']*4+['5s','5x']+['10.4e']*3],
'param3':[['relative_error','absolute_error','pivot','upstream_weight','newton_weight','derivative_increment'],
['10.4e']*6],
'timestep': [['timestep']*8,['10.4e']*8],
'multi': [['num_components','num_equations','num_phases','num_secondary_parameters','num_inc'], ['5d']*5],
'multi_autough2': [['num_components','num_equations','num_phases','num_secondary_parameters','eos'], ['5d']*4+['4s']],
'lineq':[['type','epsilon','max_iterations','gauss','num_orthog'],['2d','10.4e','4d','1d','4d']],
'default_incons':[['incon']*4,['20.14e']*4],
'output_times1':[['num_times_specified','num_times','max_timestep','time_increment'],['5d']*2+['10.4e']*2],
'output_times2':[['time']*8,['10.4e']*8],
'relative_permeability':[['type','']+['parameter']*7,['5d','5x']+['10.3e']*7],
'capillarity':[['type','']+['parameter']*7,['5d','5x']+['10.3e']*7],
'blocks':[['name','nseq','nadd','rocktype','volume','ahtx','pmx','x','y','z'],['5s','5d','5d','5s']+['10.4e']*3+
['10.3e']*3],
'connections':[['block1','block2','nseq','nad1','nad2','direction','distance1','distance2','area','dircos','sigma'],
['5s']*2+['5d']*4+['10.4e']*3+['10.7f','10.4e']],
'generator':[['block','name','nseq','nadd','nads','ltab','','type','itab','gx','ex','hg','fg'],
['5s']*2+['5d']*3+['5d','5x','4s','1s']+['10.3e']*4],
'generation_times':[['time']*4,['14.7e']*4],
'generation_rates':[['rate']*4,['14.7e']*4],
'generation_enthalpy':[['enthalpy']*4,['14.7e']*4],
'short':[['','frequency'],['5x','2d']],
'incon1':[['block','nseq','nadd','porosity'],['5s']+['5d']*2+['15.9e']],
'incon2':[['incon']*4,['20.14e']*4],
'solver':[['type','','z_precond','','o_precond','relative_max_iterations','closure'],
['1d','2x','2s','3x','2s']+['10.4e']*2],
'indom2':[['indom']*4,['20.13e']*4],
'diffusion': [['diff']*8,['10.4e']*8],
'selec1': [['int_selec']*16,['5d']*16],
'selec2': [['float_selec']*8,['10.3e']*8],
'radii1': [['nrad'],['5d']],
'radii2': [['radius']*8,['10.4e']*8],
'equid' : [['nequ','','dr'],['5d','5x','10.4e']],
'logar' : [['nlog','','rlog','dr'],['5d','5x']+['10.4e']*2],
'layer1': [['nlay'],['5d']],
'layer2': [['layer']*8,['10.4e']*8],
'xyz1' : [['deg'],['10.4e']],
'xyz2' : [['ntype','','no','del'],['2s','3x','5d','10.4e']],
'xyz3' : [['deli']*8,['10.4e']*8],
'minc' : [['part','type','','dual'],['5s']*2+['5x','5s']],
'part1' : [['num_continua','nvol','where']+['spacing']*7,['3d']*2+['4s']+['10.4e']*7],
'part2' : [['vol']*8,['10.4e']*8]
}
t2data_extra_precision_format_specification = {
'rocks1':[['name','nad','density','porosity','k1','k2','k3','conductivity','specific_heat'],
['5s','5d']+['15.8e']*7],
'rocks1.1':[['compressibility','expansivity','dry_conductivity','tortuosity','klinkenberg','xkd3','xkd4'], ['15.8e']*7],
'rocks1.2':[['type','']+['parameter']*7,['5d','5x']+['15.8e']*7],
'rocks1.3':[['type','']+['parameter']*7,['5d','5x']+['15.8e']*7],
'blocks':[['name','nseq','nadd','rocktype','volume','ahtx','pmx','x','y','z'],['5s','5d','5d','5s']+['15.8e']*3+
['15.8e']*3],
'connections':[['block1','block2','nseq','nad1','nad2','direction','distance1','distance2','area','dircos','sigma'],
['5s']*2+['5d']*4+['15.8e']*3+['15.8f','15.8e']],
'relative_permeability':[['type','']+['parameter']*7,['5d','5x']+['15.8e']*7],
'capillarity':[['type','']+['parameter']*7,['5d','5x']+['15.8e']*7],
'generator':[['block','name','nseq','nadd','nads','ltab','','type','itab','gx','ex','hg','fg'],
['5s']*2+['5d']*3+['5d','5x','4s','1s']+['15.8e']*4],
'generation_times':[['time']*4,['15.8e']*4],
'generation_rates':[['rate']*4,['15.8e']*4],
'generation_enthalpy':[['enthalpy']*4,['15.8e']*4]}
class t2data_parser(fixed_format_file):
"""Class for parsing TOUGH2 data file."""
def __init__(self, filename, mode, read_function = default_read_function):
super(t2data_parser,self).__init__(filename, mode, t2data_format_specification, read_function)
class t2_extra_precision_data_parser(fixed_format_file):
"""Class for parsing AUTOUGH2 extra-precision auxiliary data file."""
def __init__(self, filename, mode, read_function = default_read_function):
super(t2_extra_precision_data_parser,self).__init__(filename, mode, t2data_extra_precision_format_specification, read_function)
import struct
class fortran_unformatted_file(file):
"""Class for 'unformatted' binary file written by Fortran. These are different from plain binary files
in that the byte length of each 'record' is written at its start and end."""
def readrec(self,fmt):
nb,=struct.unpack('i',self.read(4))
packed=self.read(nb)
self.read(4)
return struct.unpack(fmt,packed)
def writerec(self,fmt,val):
nb=struct.calcsize(fmt)
if isinstance(val,(tuple,list,np.ndarray)):
packed=struct.pack(fmt,*val)
else: packed=struct.pack(fmt,val)
head=struct.pack('i',nb)
self.write(''.join((head,packed,head)))
class t2generator(object):
"""TOUGH2 generator (source or sink)"""
def __init__(self,name=' ',block=' ',nseq=None,nadd=None,nads=None,type='MASS',
ltab=0,itab='',gx=0.0,ex=0.0,hg=0.0,fg=0.0,time=[],rate=[],enthalpy=[]):
self.name=name
self.block=block
self.nseq,self.nadd,self.nads=nseq,nadd,nads
self.type=type
self.ltab=ltab
self.itab=itab
self.gx=gx
self.ex=ex
self.hg=hg
self.fg=fg
self.time=time
self.rate=rate
self.enthalpy=enthalpy
def __repr__(self): return self.block+':'+self.name
default_parameters = {'max_iterations':None, 'print_level':None, 'max_timesteps':None, 'max_duration':None, 'print_interval':None,
'_option_str':'0'*24,'option':np.zeros(25,int8), 'diff0':None, 'texp':None, 'tstart':0.0, 'tstop':None,
'const_timestep':0.0,'timestep':[], 'max_timestep':None, 'print_block':None, 'gravity':0.0,
'timestep_reduction':None, 'scale':None, 'relative_error':None, 'absolute_error':None, 'pivot':None,
'upstream_weight':None, 'newton_weight':None, 'derivative_increment':None, 'default_incons':[]}
t2data_sections = ['SIMUL','ROCKS','MESHM','PARAM','START','NOVER','RPCAP','LINEQ','SOLVR','MULTI','TIMES',
'SELEC','DIFFU','ELEME','CONNE','GENER','SHORT','FOFT','COFT','GOFT','INCON','INDOM']
t2_extra_precision_sections = ['ROCKS', 'ELEME', 'CONNE', 'RPCAP', 'GENER']
class t2data(object):
"""Class for TOUGH2 data"""
def __init__(self, filename = '', meshfilename = '', read_function = default_read_function):
from copy import deepcopy
self.filename = filename
self.meshfilename = meshfilename
self.title = ''
self.simulator = ''
self.parameter = deepcopy(default_parameters)
self.multi = {}
self.start = False
self.relative_permeability = {}
self.capillarity = {}
self.lineq = {}
self.output_times = {}
self.grid = t2grid()
self.generatorlist = []
self.generator = {}
self.short_output = {}
self.incon = {}
self.solver = {}
self.history_block = []
self.history_connection = []
self.history_generator = []
self.indom = {}
self.noversion = False
self.diffusion = []
self.selection = {}
self.meshmaker = []
self._sections = []
self.end_keyword = 'ENDCY'
self._extra_precision, self._echo_extra_precision = [], True
self.update_read_write_functions()
self.read_function = read_function
if self.filename: self.read(filename, meshfilename)
def get_extra_precision(self): return self._extra_precision
def set_extra_precision(self, value):
if value is False: value = []
elif value is True: value = t2_extra_precision_sections
elif isinstance(value, str): value = [value]
# check if removing any extra precision sections:
for section in set(self._extra_precision) - set(value): self.insert_section(section)
self._extra_precision = value
self.update_read_write_functions()
extra_precision = property(get_extra_precision, set_extra_precision)
def get_echo_extra_precision(self): return self._echo_extra_precision
def set_echo_extra_precision(self, value):
if value <> self._echo_extra_precision:
if value is False: # remove previously echoed sections from section list
for section in self._extra_precision: self.delete_section(section)
else: # add sections previously not echoed to section list
for section in self._extra_precision: self.insert_section(section)
self._echo_extra_precision = value
self.update_read_write_functions()
echo_extra_precision = property(get_echo_extra_precision, set_echo_extra_precision)
def update_read_write_functions(self):
"""Updates functions for reading and writing sections of data file."""
self.read_fn = dict(zip(
t2data_sections,
[self.read_simulator, self.read_rocktypes, self.read_meshmaker, self.read_parameters, self.read_start,
self.read_noversion, self.read_rpcap, self.read_lineq, self.read_solver, self.read_multi, self.read_times,
self.read_selection, self.read_diffusion, self.read_blocks, self.read_connections,
self.read_generators, self.read_short_output, self.read_history_blocks,
self.read_history_connections, self.read_history_generators, self.read_incons, self.read_indom]))
self.write_fn = dict(zip(
t2data_sections,
[self.write_simulator, self.write_rocktypes, self.write_meshmaker, self.write_parameters,
self.write_start, self.write_noversion, self.write_rpcap, self.write_lineq, self.write_solver,
self.write_multi, self.write_times, self.write_selection, self.write_diffusion, self.write_blocks,
self.write_connections, self.write_generators, self.write_short_output, self.write_history_blocks,
self.write_history_connections, self.write_history_generators, self.write_incons, self.write_indom]))
skip_fn = dict(zip(t2_extra_precision_sections,
[self.skip_rocktypes, self.skip_blocks, self.skip_connections,
self.skip_rpcap, self.skip_generators]))
if not self.echo_extra_precision:
for section in self.extra_precision: self.read_fn[section] = skip_fn[section]
def get_present_sections(self):
"""Returns a list of TOUGH2 section keywords for which there are corresponding data in the t2data object."""
data_present = dict(zip(t2data_sections,
[self.simulator, self.grid and self.grid.rocktypelist, self.meshmaker, self.parameter, self.start,
self.noversion, self.relative_permeability or self.capillarity, self.lineq, self.solver, self.multi,
self.output_times, self.selection, self.diffusion, self.grid and self.grid.blocklist,
self.grid and self.grid.connectionlist, self.generatorlist, self.short_output, self.history_block,
self.history_connection, self.history_generator, self.incon, self.indom]))
return [keyword for keyword in t2data_sections if data_present[keyword]]
present_sections = property(get_present_sections)
def insert_section(self, section):
"""Inserts a new section into the internal list of data file sections."""
if section not in self._sections:
i = self.section_insertion_index(section)
self._sections.insert(i, section)
def delete_section(self, section):
"""Deletes a section from the internal list of data file sections."""
try: self._sections.remove(section)
except ValueError: pass
def section_insertion_index(self, section):
"""Determines an appropriate position to insert the specified section in the internal list of
data file sections."""
try:
listindex = t2data_sections.index(section)
if listindex == 0: return 0 # SIMUL section
else:
# first look for sections above the one specified,
# and put new one just after the last found:
for i in reversed(range(listindex)):
try:
section_index = self._sections.index(t2data_sections[i])
return section_index + 1
except ValueError: pass
# look for sections below the one specified,
# and put new one just before the first found:
for i in xrange(listindex, len(t2data_sections)):
try:
section_index = self._sections.index(t2data_sections[i])
return section_index
except ValueError: pass
return len(self._sections)
except ValueError: return len(self._sections)
def update_sections(self):
"""Updates internal section list, based on which properties are present."""
present = self.present_sections
missing = [keyword for keyword in present if keyword not in self._sections]
for keyword in missing: self.insert_section(keyword)
extra = [keyword for keyword in self._sections if keyword not in present]
for keyword in extra: self.delete_section(keyword)
def __repr__(self): return self.title
def run(self,save_filename='',incon_filename='',simulator='AUTOUGH2_2',silent=False):
"""Runs simulation using TOUGH2 or AUTOUGH2. It's assumed that the data object has been written to file
using write(). For AUTOUGH2, if the filenames for the save file or initial conditions file are not specified,
they are constructed by changing the extensions of the data filename. Set silent to True to suppress screen
output."""
if self.filename:
from os.path import splitext, basename
from os import devnull,system,remove
datbase,ext=splitext(self.filename)
if (self.type=='AUTOUGH2'):
if save_filename=='': save_filename=datbase+'.save'
if incon_filename=='': incon_filename=datbase+'.incon'
savebase,ext=splitext(save_filename)
inconbase,ext=splitext(incon_filename)
# write a file containing the filenames, to pipe into AUTOUGH2:
runfilename = datbase + '_' + basename(simulator) + '.in'
f=open(runfilename,'w')
f.write(savebase+'\n')
f.write(inconbase+'\n')
f.write(datbase+'\n')
f.close()
if silent: out=' > '+devnull
else: out=''
# run AUTOUGH2:
system(simulator+' < '+runfilename+out)
remove(runfilename)
else: # run TOUGH2 (need to specify simulator executable name)
if silent: out=devnull
else: out=datbase+'.listing'
system(simulator+' < '+self.filename+' > '+out)
def get_type(self):
"""Returns type (TOUGH2 or AUTOUGH2) based on whether the simulator has been set."""
if self.simulator: return 'AUTOUGH2'
else: return 'TOUGH2'
def set_type(self, value):
"""Sets type (TOUGH2 or AUTOUGH2), and runs conversion if needed (with default options)."""
if value in ['AUTOUGH2','TOUGH2']:
oldtype = self.type
if oldtype <> value:
if oldtype == 'AUTOUGH2': self.convert_to_TOUGH2()
elif oldtype == 'TOUGH2': self.convert_to_AUTOUGH2()
else: raise Exception('Data file type '+value+' is not supported.')
type = property(get_type, set_type)
def get_extra_precision_filename(self):
"""Returns name of extra precision data file name, based on the name of the data file."""
from os.path import splitext
base, ext = splitext(self.filename)
if base[0].isupper(): pext = 'PDAT'
else: pext = 'pdat'
return '.'.join((base, pext))
extra_precision_filename = property(get_extra_precision_filename)
def get_num_generators(self):
return len(self.generatorlist)
num_generators=property(get_num_generators)
def generator_index(self,blocksourcenames):
"""Returns index of generator with specified tuple of block and source names."""
if blocksourcenames in self.generator:
return self.generatorlist.index(self.generator[blocksourcenames])
else: return None
def total_generation(self,type='MASS',name=''):
"""Returns array containing total generation in each block of the specified generator type and name. The
name parameter specifies a regular expression to be matched."""
import re
tg=np.zeros(self.grid.num_blocks,float64)
gens=[g for g in self.generatorlist if ((type==g.type) and re.search(name,g.name))]
for g in gens: tg[self.grid.block_index(g.block)]+=g.gx
return tg
def specific_generation(self,type='MASS',name=''):
"""Returns array containing total specific generation (i.e. generation per unit volume) in each block of the
specified generator type and name. The name parameter specifies a regular expression to be matched."""
import re
tg=np.zeros(self.grid.num_blocks,float64)
gens=[g for g in self.generatorlist if ((g.type==type) and (re.search(name,g.name)))]
for g in gens:
blkindex=self.grid.block_index(g.block)
tg[blkindex]+=g.gx/self.grid.blocklist[blkindex].volume
return tg
def read_title(self,infile):
"""Reads simulation title"""
infile.read_value_line(self.__dict__,'title')
def write_title(self,outfile):
outfile.write(self.title.strip()+'\n')
def read_simulator(self,infile):
"""Reads simulator and EOS type. If the SIMUL section is present, check for extra precision
data in auxiliary file, and modify functions accordingly for reading the main data file."""
infile.read_value_line(self.__dict__,'simulator')
if self.type == 'AUTOUGH2': self.read_extra_precision()
def write_simulator(self,outfile):
if self.simulator:
outfile.write('SIMUL\n')
outfile.write(self.simulator.strip()+'\n')
def read_rocktypes(self,infile):
"""Reads grid rock types"""
self.grid.rocktypelist=[]
self.grid.rocktype={}
line=padstring(infile.readline())
while line.strip():
[name,nad,density,porosity,k1,k2,k3,conductivity,specific_heat]=infile.parse_string(line,'rocks1')
self.grid.add_rocktype(rocktype(name,nad,density,porosity,[k1,k2,k3],conductivity,specific_heat))
if nad>=1: # additional lines:
infile.read_value_line(self.grid.rocktype[name].__dict__,'rocks1.1')
if nad>=2:
vals=infile.read_values('rocks1.2')
self.grid.rocktype[name].relative_permeability['type']=vals[0]
self.grid.rocktype[name].relative_permeability['parameters']=vals[2:-1]
vals=infile.read_values('rocks1.3')
self.grid.rocktype[name].capillarity['type']=vals[0]
self.grid.rocktype[name].capillarity['parameters']=vals[2:-1]
line=padstring(infile.readline())
def skip_rocktypes(self,infile):
"""Skips rock type section"""
while infile.readline().strip(): pass
def write_rocktypes(self,outfile):
outfile.write('ROCKS\n')
for rt in self.grid.rocktypelist:
vals=[rt.name,rt.nad,rt.density,rt.porosity]+list(rt.permeability)+[rt.conductivity,rt.specific_heat]
outfile.write_values(vals,'rocks1')
if rt.nad>=1:
outfile.write_value_line(rt.__dict__,'rocks1.1')
if rt.nad>=2:
vals=[rt.relative_permeability['type'],None]+rt.relative_permeability['parameters']
outfile.write_values(vals,'rocks1.2')
vals=[rt.capillarity['type'],None]+rt.capillarity['parameters']
outfile.write_values(vals,'rocks1.2')
outfile.write('\n')
def read_parameters(self,infile):
"""Reads simulation parameters"""
spec=['param1','param1_autough2'][self.type=='AUTOUGH2']
infile.read_value_line(self.parameter,spec)
mops=ljust(self.parameter['_option_str'].rstrip(),24).replace(' ','0')
self.parameter['option']=np.array([0]+[int(mop) for mop in mops],int8)
infile.read_value_line(self.parameter,'param2')
if (self.parameter['print_block'] is not None) and (self.parameter['print_block'].strip()==''):
self.parameter['print_block']=None
self.read_timesteps(infile)
infile.read_value_line(self.parameter,'param3')
for val in infile.read_values('default_incons'): self.parameter['default_incons'].append(val)
# read any additional lines of default incons:
more = True
while more:
line = padstring(infile.readline())
if line.strip():
section = any([line.startswith(keyword) for keyword in t2data_sections])
if section: more = False
else:
more_incons = infile.parse_string(line, 'default_incons')
if more_incons:
while more_incons[-1] is None: more_incons.pop()
self.parameter['default_incons'] += more_incons
else: more, line = False, None
return line
def write_parameters(self,outfile):
outfile.write('PARAM\n')
from copy import copy
paramw=copy(self.parameter)
if paramw['print_block'] is not None: paramw['print_block']=unfix_blockname(paramw['print_block'])
self.parameter['_option_str']=''.join([str(m) for m in self.parameter['option'][1:]])
spec=['param1','param1_autough2'][self.type=='AUTOUGH2']
outfile.write_value_line(self.parameter,spec)
outfile.write_value_line(paramw,'param2')
self.write_timesteps(outfile)
outfile.write_value_line(self.parameter,'param3')
num_vars = len(self.parameter['default_incons'])
nlines = int(ceil(num_vars / 4.))
for i in xrange(nlines):
i1, i2 = i * 4, min((i + 1) * 4, num_vars)
vals = list(self.parameter['default_incons'][i1:i2])
if len(vals) < 4: vals += [None] * (4 - len(vals))
outfile.write_values(vals,'default_incons')
def read_timesteps(self,infile):
"""Reads time step sizes from file"""
if self.parameter['const_timestep']>=0.0:
self.parameter['timestep']=[self.parameter['const_timestep']]
else:
nlines=-int(self.parameter['const_timestep'])
self.parameter['timestep']=[]
for i in xrange(nlines):
for val in infile.read_values('timestep'):
if val is not None: self.parameter['timestep'].append(val)
def write_timesteps(self,outfile):
if self.parameter['const_timestep']<0.0:
nlines=-int(self.parameter['const_timestep'])
for i in xrange(nlines):
i1,i2=i*8,min((i+1)*8,len(self.parameter['timestep']))
vals=self.parameter['timestep'][i1:i2]
if len(vals)<8: vals+=[None]*(8-len(vals))
outfile.write_values(vals,'timestep')
def read_multi(self,infile):
"""Reads EOS parameters"""
spec=['multi','multi_autough2'][self.type=='AUTOUGH2']
infile.read_value_line(self.multi,spec)
if 'eos' in self.multi: self.multi['eos']=self.multi['eos'].strip()
def write_multi(self,outfile):
if self.multi<>{}:
outfile.write('MULTI\n')
spec=['multi','multi_autough2'][self.type=='AUTOUGH2']
outfile.write_value_line(self.multi,spec)
def read_start(self,infile):
"""Sets start parameter"""
self.start=True
def write_start(self,outfile):
if self.start: outfile.write('START\n')
def read_rpcap(self,infile):
"""Reads relative permeability and capillarity parameters"""
vals=infile.read_values('relative_permeability')
self.relative_permeability['type'],self.relative_permeability['parameters']=vals[0],vals[2:]
vals=infile.read_values('capillarity')
self.capillarity['type'],self.capillarity['parameters']=vals[0],vals[2:]
def skip_rpcap(self,infile):
"""Skips relative permeability and capillarity parameter section."""
for i in xrange(2): infile.readline()
def write_rpcap(self,outfile):
if self.relative_permeability:
outfile.write('RPCAP\n')
vals=[self.relative_permeability['type'],None]+self.relative_permeability['parameters']
outfile.write_values(vals,'relative_permeability')
vals=[self.capillarity['type'],None]+self.capillarity['parameters']
outfile.write_values(vals,'capillarity')
def read_lineq(self,infile):
"""Reads linear equation parameters (AUTOUGH2)"""
infile.read_value_line(self.lineq,'lineq')
def write_lineq(self,outfile):
if self.lineq:
outfile.write('LINEQ\n')
outfile.write_value_line(self.lineq,'lineq')
def read_solver(self,infile):
"""Reads linear equation parameters (TOUGH2)"""
infile.read_value_line(self.solver,'solver')
def write_solver(self,outfile):
if self.solver:
outfile.write('SOLVR\n')
outfile.write_value_line(self.solver,'solver')
def read_blocks(self,infile):
"""Reads grid blocks"""
self.grid.block,self.grid.blocklist={},[]
line=padstring(infile.readline())
while line.strip():
[name,nseq,nadd,rockname,volume,ahtx,pmx,x,y,z]=infile.parse_string(line,'blocks')
name=fix_blockname(name)
if rockname in self.grid.rocktype: rocktype=self.grid.rocktype[rockname]
elif rockname.strip()=='' and self.grid.num_rocktypes>0: rocktype=self.grid.rocktypelist[0] # default
else:
try: # check if rocktype index specified:
rockindex=int(rockname)-1
rocktype=self.grid.rocktypelist[rockindex]
except: raise RuntimeError("Unknown rocktype "+rockname+" in block "+name)
if (x is not None) and (y is not None) and (z is not None): centre=np.array([x,y,z])
else: centre=None
if nseq==0: nseq=None
if nadd==0: nadd=None
self.grid.add_block(t2block(name,volume,rocktype,centre=centre,ahtx=ahtx,pmx=pmx,nseq=nseq,nadd=nadd))
line=padstring(infile.readline())
def skip_blocks(self, infile):
"""Skips blocks section in file"""
while infile.readline().strip(): pass
def write_blocks(self,outfile):
if self.grid.num_blocks>0:
outfile.write('ELEME\n')
from copy import copy
for blk in self.grid.blocklist:
blkw=copy(blk.__dict__)
blkw['name']=unfix_blockname(blkw['name'])
if blk.centre is None: outfile.write_value_line(blkw,'blocks')
else:
vals=[blkw['name'],blk.nseq,blk.nadd,blk.rocktype.name,blk.volume,
blk.ahtx,blk.pmx]+list(blk.centre)
outfile.write_values(vals,'blocks')
outfile.write('\n')
def read_connections(self,infile):
"""Reads grid connections"""
self.grid.connectionlist,self.grid.connection=[],{}
line=padstring(infile.readline())
while line.strip() and not line.startswith('+++'):
[name1,name2,nseq,nad1,nad2,isot,d1,d2,areax,betax,sigx]=infile.parse_string(line,'connections')
name1,name2=fix_blockname(name1),fix_blockname(name2)
if nseq==0: nseq=None
if nad1==0: nad1=None
if nad2==0: nad2=None
self.grid.add_connection(t2connection([self.grid.block[name1],self.grid.block[name2]],isot,[d1,d2],areax,betax,sigx,nseq,nad1,nad2))
line=padstring(infile.readline())
def skip_connections(self, infile):
"""Skips connections section in file"""
while infile.readline().strip(): pass
def write_connections(self,outfile):
if self.grid.num_connections>0:
outfile.write('CONNE\n')
for con in self.grid.connectionlist:
vals=[unfix_blockname(con.block[0].name),unfix_blockname(con.block[1].name),
con.nseq,con.nad1,con.nad2,con.direction]+con.distance+[con.area,con.dircos]
outfile.write_values(vals,'connections')
outfile.write('\n')
def add_generator(self,generator=t2generator()):
"""Adds a generator."""
self.generatorlist.append(generator)
self.generator[(generator.block,generator.name)]=self.generatorlist[-1]
def delete_generator(self,blocksourcenames):
i=self.generator_index(blocksourcenames)
del self.generator[blocksourcenames]
del self.generatorlist[i]
def clear_generators(self):
self.generator.clear()
del self.generatorlist[:]
def delete_orphan_generators(self):
"""Deletes any generators specified in blocks which do not exist in the grid."""
delgenindices, delgens = [], set([])
# Delete items from the generator list and dictionary separately (rather than using
# self.delete_generator() in case there are multiple generators in the list with the
# same dictionary key.
for i,gen in enumerate(self.generatorlist):
if not (gen.block in self.grid.block):
delgenindices.append(i)
delgens.add((gen.block,gen.name))
for bg in delgens: del self.generator[bg]
for i in reversed(delgenindices): del self.generatorlist[i]
def read_generator(self,line,infile):
"""Returns generator read from line in file"""
[block,name,nseq,nadd,nads,ltab,empty,gentype,itab,gx,ex,hg,fg]=infile.parse_string(line,'generator')
block,name=fix_blockname(block),fix_blockname(name)
time,rate,enthalpy=[],[],[]
if ltab and gentype<>'DELV':
ntimes=abs(ltab)
if ntimes>1:
nlines=int(ceil(ntimes/4.))
for i in xrange(nlines):
for val in infile.read_values('generation_times'):
if val is not None: time.append(val)
for i in xrange(nlines):
for val in infile.read_values('generation_rates'):
if val is not None: rate.append(val)
if itab.strip():
for i in xrange(nlines):
for val in infile.read_values('generation_enthalpy'):
if val is not None: enthalpy.append(val)
return t2generator(name=name,block=block,nseq=nseq,nadd=nadd,nads=nads,type=gentype,ltab=ltab,itab=itab,
gx=gx,ex=ex,hg=hg,fg=fg,time=time,rate=rate,enthalpy=enthalpy)
def write_generator(self,gen,outfile):
from copy import copy
genw=copy(gen.__dict__)
genw['name'],genw['block']=unfix_blockname(genw['name']),unfix_blockname(genw['block'])
outfile.write_value_line(genw,'generator')
if gen.ltab and gen.type<>'DELV': ntimes=abs(gen.ltab)
else: ntimes=1
if ntimes>1:
nlines=int(ceil(ntimes/4.))
for i in xrange(nlines):
i1,i2=i*4,min((i+1)*4,ntimes)
vals = list(gen.time[i1:i2])
if len(vals)<4: vals+=[None]*(4-len(vals))
outfile.write_values(vals,'generation_times')
for i in xrange(nlines):
i1,i2=i*4,min((i+1)*4,ntimes)
vals = list(gen.rate[i1:i2])
if len(vals)<4: vals+=[None]*(4-len(vals))
outfile.write_values(vals,'generation_rates')
if gen.enthalpy:
for i in xrange(nlines):
i1,i2=i*4,min((i+1)*4,ntimes)
vals = list(gen.enthalpy[i1:i2])
if len(vals)<4: vals+=[None]*(4-len(vals))
outfile.write_values(vals,'generation_enthalpy')
def read_generators(self,infile):
"""Reads generators from file"""
self.generatorlist=[]
line=infile.readline()
while line.strip():
self.add_generator(self.read_generator(line,infile))
line=infile.readline()
def skip_generators(self,infile):
"""Skips generator section in file"""
while infile.readline().strip(): pass
def write_generators(self,outfile):
if self.generatorlist:
outfile.write('GENER\n')
for generator in self.generatorlist:
self.write_generator(generator,outfile)
outfile.write('\n')
def read_times(self,infile):
"""Reads output times from file"""
infile.read_value_line(self.output_times,'output_times1')
self.output_times['time']=[]
nlines=int(ceil(self.output_times['num_times_specified']/8.))
for i in xrange(nlines):
for val in infile.read_values('output_times2'):
if val is not None: self.output_times['time'].append(val)
def write_times(self,outfile):
if self.output_times:
outfile.write('TIMES\n')
outfile.write_value_line(self.output_times,'output_times1')
nlines=int(ceil(self.output_times['num_times_specified']/8.))
for i in xrange(nlines):
i1,i2=i*8,min((i+1)*8,len(self.output_times['time']))
vals=self.output_times['time'][i1:i2]
if len(vals)<8: vals+=[None]*(8-len(vals))
outfile.write_values(vals,'output_times2')
def read_incons(self,infile):
"""Reads initial conditions from file"""
line=infile.readline()
while line.strip():
[blockname, nseq, nadd, porosity] = infile.parse_string(line, 'incon1')
blockname=fix_blockname(blockname)
variables=infile.read_values('incon2')
while variables and variables[-1] is None: variables.pop()
if nseq == 0: nseq = None
if nadd == 0: nadd = None
if nseq is None: self.incon[blockname] = [porosity, variables]
else: self.incon[blockname] = [porosity, variables, nseq, nadd]
line=infile.readline()
def write_incons(self,outfile):
if self.incon:
outfile.write('INCON\n')
for blkname,inc in self.incon.iteritems():
if len(inc) >= 4: nseq, nadd = inc[2], inc[3]
else: nseq, nadd = None, None
vals = [unfix_blockname(blkname), nseq, nadd, inc[0]]
outfile.write_values(vals,'incon1')
outfile.write_values(inc[1],'incon2')
outfile.write('\n')
def read_short_blocks(self,infile):
"""Reads short output blocks"""
self.short_output['block']=[]
badblocks=[]
more=True
while more:
line=infile.readline()
if line.strip():
if line[0:5] in ['ELEME','CONNE','GENER']: more=False
else:
blockname=fix_blockname(line[0:5])
if blockname in self.grid.block: self.short_output['block'].append(self.grid.block[blockname])
else: badblocks.append(blockname)
else: more=False
if len(badblocks)>0: print 'Short output blocks',badblocks,'do not exist and will be ignored.'
return line
def read_short_connections(self,infile):
"""Reads short output connections"""
self.short_output['connection']=[]
badcons=[]
more=True
while more:
line=infile.readline()
if line.strip():
if line[0:5] in ['ELEME','CONNE','GENER']: more=False
else:
blknames=(fix_blockname(line[0:5]),fix_blockname(line[5:10]))
if blknames in self.grid.connection: self.short_output['connection'].append(self.grid.connection[blknames])
else: badcons.append(blknames)
else: more=False
if len(badcons)>0: print 'Short output connections',badcons,'do not exist and will be ignored.'
return line
def read_short_generators(self,infile):
"""Reads short output generators"""
self.short_output['generator']=[]
badgens=[]
more=True
while more:
line=infile.readline()
if line.strip():
if line[0:5] in ['ELEME','CONNE','GENER']: more=False
else:
blksourcenames=(fix_blockname(line[0:5]),fix_blockname(line[5:10]))
if blksourcenames in self.generator: self.short_output['generator'].append(self.generator[blksourcenames])
else: badgens.append(blksourcenames)
else: more=False
if len(badgens)>0: print 'Short output generators',badgens,'do not exist and will be ignored.'
return line
def read_short_output(self,infile,headerline):
"""Reads short output specifications from file. 'headerline' is passed in to read the frequency parameter."""
vals=infile.parse_string(headerline,'short')
if len(vals)>1: self.short_output['frequency']=vals[1]
read_fn={'ELEME':self.read_short_blocks,'CONNE':self.read_short_connections,'GENER':self.read_short_generators}
more=True
line=infile.readline()
while more:
if line.strip():
keyword=line[0:5]
line=read_fn[keyword](infile)
else: more=False
def write_short_output(self,outfile):
if self.short_output:
outfile.write('SHORT')
if 'frequency' in self.short_output:
if self.short_output['frequency']: outfile.write('%2d' % self.short_output['frequency'])
outfile.write('\n')
if 'block' in self.short_output:
outfile.write('ELEME\n')
for block in self.short_output['block']:outfile.write(unfix_blockname(block.name)+'\n')
if 'connection' in self.short_output:
outfile.write('CONNE\n')
for con in self.short_output['connection']:outfile.write(unfix_blockname(con.block[0].name)+
unfix_blockname(con.block[1].name)+'\n')
if 'generator' in self.short_output:
outfile.write('GENER\n')
for gen in self.short_output['generator']:outfile.write(unfix_blockname(gen.block)+
unfix_blockname(gen.name)+'\n')
outfile.write('\n')
def read_history_blocks(self,infile):
"""Reads history blocks (TOUGH2)"""
self.history_block=[]
badblocks=[]
line=infile.readline()
if self.grid.num_blocks>0:
while line.strip():
blockname=fix_blockname(line[0:5])
if blockname in self.grid.block: self.history_block.append(self.grid.block[blockname])
else: badblocks.append(blockname)
line=infile.readline()
if len(badblocks)>0: print 'History blocks',badblocks,'do not exist and will be ignored.'
else: # no grid- don't check blocks; and store names rather than t2blocks
while line.strip():
blockname=fix_blockname(line[0:5])
self.history_block.append(blockname)
line=infile.readline()
def read_history_connections(self,infile):
"""Reads history connections (TOUGH2)"""
self.history_connection=[]
badcons=[]
line=infile.readline()
if self.grid.num_blocks>0:
while line.strip():
blknames=(fix_blockname(line[0:5]),fix_blockname(line[5:10]))
if blknames in self.grid.connection: self.history_connection.append(self.grid.connection[blknames])
else: badcons.append(blknames)
line=infile.readline()
if len(badcons)>0: print 'History connections',badcons,'do not exist and will be ignored.'
else: # no grid
while line.strip():
blknames=(fix_blockname(line[0:5]),fix_blockname(line[5:10]))
self.history_connection.append(blknames)
line=infile.readline()
def read_history_generators(self,infile):
"""Reads history generators (TOUGH2)"""
self.history_generator=[]
badgens=[]
line=infile.readline()
if self.grid.num_blocks>0:
while line.strip():
blockname=fix_blockname(line[0:5])
if blockname in self.grid.block: self.history_generator.append(self.grid.block[blockname])
else: badgens.append(blockname)
line=infile.readline()
if len(badgens)>0: print 'History generator blocks',badgens,'do not exist and will be ignored.'
else: # no grid
while line.strip():
blockname=fix_blockname(line[0:5])
self.history_generator.append(blockname)
line=infile.readline()
def write_history_blocks(self,outfile):
if self.history_block:
outfile.write('FOFT\n')
for blk in self.history_block:
if isinstance(blk,str): blkname=blk
else: blkname=blk.name
outfile.write(unfix_blockname(blkname)+'\n')
outfile.write('\n')
def write_history_connections(self,outfile):
if self.history_connection:
outfile.write('COFT\n')
for con in self.history_connection:
if isinstance(con,tuple): cname=con
else: cname=tuple([blk.name for blk in con.block])
outfile.write(unfix_blockname(cname[0])+unfix_blockname(cname[1])+'\n')
outfile.write('\n')
def write_history_generators(self,outfile):
if self.history_generator:
outfile.write('GOFT\n')
for blk in self.history_generator:
if isinstance(blk,str): blkname=blk
else: blkname=blk.name
outfile.write(unfix_blockname(blkname)+'\n')
outfile.write('\n')
def read_indom(self,infile):
"""Reads rock-specific initial conditions from file"""
line=infile.readline()
while line.strip():
rockname=line[0:5]
variables=infile.read_values('incon2')
self.indom[rockname]=variables
line=infile.readline()
def write_indom(self,outfile):
if self.indom:
outfile.write('INDOM\n')
for rockname,inc in self.indom.iteritems():
outfile.write(rockname+'\n')
outfile.write_values(inc,'incon2')
outfile.write('\n')
def read_noversion(self,infile):
"""Sets noversion parameter"""
self.noversion=True
def write_noversion(self,outfile):
if self.noversion: outfile.write('NOVER\n')
def read_diffusion(self,infile):
"""Reads diffusion coefficients from file"""
if ('num_components' in self.multi) and ('num_phases' in self.multi):
for comp in xrange(self.multi['num_components']):
diffs=infile.read_values('diffusion')[0:self.multi['num_phases']]
self.diffusion.append(diffs)
else: print 'Unable to read DIFFU block: no MULTI block specified.'
def write_diffusion(self,outfile):
if self.diffusion:
outfile.write('DIFFU\n')
for comp in self.diffusion: outfile.write_values(comp,'diffusion')
def read_selection(self,infile):
"""Reads selection parameters from file"""
int_selec=infile.read_values('selec1')
self.selection['integer']=int_selec
nlines=int_selec[0]
float_selec=[]
for i in xrange(nlines): float_selec+=infile.read_values('selec2')
self.selection['float']=float_selec
def write_selection(self,outfile):
if self.selection:
outfile.write('SELEC\n')
outfile.write_values(self.selection['integer'],'selec1')
nlines=self.selection['integer'][0]
for i in xrange(nlines):
i1,i2=i*8,min((i+1)*8,len(self.selection['float']))
vals=self.selection['float'][i1:i2]
if len(vals)<8: vals+=[None]*(8-len(vals))
outfile.write_values(vals,'selec2')
def read_meshmaker(self,infile):
"""Reads meshmaker data"""
read_fn={'RZ2D' : self.read_meshmaker_rz2d, 'XYZ' : self.read_meshmaker_xyz,
'MINC' : self.read_meshmaker_minc}
more=True
while more:
line=infile.readline()
if line.strip():
keyword=line[0:5].strip()
if keyword in read_fn: read_fn[keyword](infile)
else: more=False
def write_meshmaker(self,outfile):
if self.meshmaker:
outfile.write('MESHMAKER\n')
write_fn={'rz2d': self.write_meshmaker_rz2d, 'xyz': self.write_meshmaker_xyz,
'minc': self.write_meshmaker_minc}
for (stype,section) in self.meshmaker: write_fn[stype.lower()](section,outfile)
outfile.write('\n')
def read_meshmaker_rz2d(self,infile):
"""Reads RZ2D meshmaker data"""
section=('rz2d',[])
more=True
while more:
line=infile.readline()
keyword=line[0:5].strip()