-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake4-seed.py
More file actions
822 lines (675 loc) · 26.8 KB
/
Copy pathmake4-seed.py
File metadata and controls
822 lines (675 loc) · 26.8 KB
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
#!/usr/bin/env python3
"""
CA DENDRITIC SOLIDIFICATION SEED / RESTART HELPER
make4-seed.py
Build a matched CA restart set from a previous CA grid output.
Purpose
-------
This is the Python helper version of the old Fortran option-40 / SEEDCA
workflow. Generated with AI assistance to help rework the F77 code.
It is intended for continuation runs: a developed dendrite/mushy
region is copied from the top of a previous simulation and placed at the
bottom of a new, smaller CA window.
The helper writes a matched restart package:
xgrid_seed.txt reseeded starting grid
xthermal_seed.csv thermal history shifted so t=0 matches the seed
xparam_seed.txt parameter file pointing to the two files above
Default continuation behavior
-----------------------------
The top HSEED rows of the old grid are copied to rows 1..HSEED of the new
grid. The copied temperatures are preserved. Rows above HSEED are filled as
fresh liquid using:
TEMP(J) = TSEEDTOP + GRAD*(J - HSEED)
where TSEEDTOP is the copied temperature at the top of the seed band and GRAD
is in K/cell.
The restart undercooling written to xparam_seed.txt is:
DTSEED = TL0 - TSEEDTOP
where TL0 = TMP + MLIQ*C0.
Optional diagnostic anchoring
----------------------------
With --diag data.csv and --anchor-tip-undercooling, the helper reads the last
valid tip undercooling from the diagnostic CSV and shifts the copied seed-band
temperatures so:
TSEEDTOP = TL0 - DTtip_last
This is a designed restart mode. The default mode is the closer match to the
old option-40 continuation behavior.
Programming approach
--------------------
Lean, self-contained, console-based helper. The source is intentionally plain
and easy to edit.
"""
import sys
import re
import csv
from pathlib import Path
# =====================================================================
# USER SETTINGS / DEFAULTS
# =====================================================================
PARAM_FILE_DEFAULT = "xparam.txt"
OLD_GRID_DEFAULT = "grid.txt"
OUT_PARAM_DEFAULT = "xparam_seed.txt"
OUT_GRID_DEFAULT = "xgrid_seed.txt"
OUT_THERMAL_DEFAULT = "xthermal_seed.csv"
HSEED_DEFAULT = 150
NUNITS = 1000.0
PH_LIQUID = 0.0
ORIENT_LIQUID = 0.0
YREF_FRAC_DEFAULT = 0.5
GRID_HEADER = " X Y #liqCells Lcomp Scomp Phase Temp Orient\n"
# =====================================================================
# BASIC HELPERS
# =====================================================================
def ask_string(prompt, default):
ans = input(f"{prompt} [{default}]: ").strip()
if ans == "":
return default
return ans
def ask_int(prompt, default):
while True:
ans = input(f"{prompt} [{default}]: ").strip()
if ans == "":
return int(default)
try:
return int(ans)
except ValueError:
print("Please enter an integer value.")
def ask_float(prompt, default):
while True:
ans = input(f"{prompt} [{default:g}]: ").strip()
if ans == "":
return float(default)
try:
return float(ans)
except ValueError:
print("Please enter a numeric value.")
def yes_no(prompt, default=True):
tag = "Y/n" if default else "y/N"
ans = input(f"{prompt} [{tag}]: ").strip().lower()
if ans == "":
return default
return ans in ("y", "yes")
def normalize_name(name):
s = name.strip().lower()
for ch in (" ", "_", "-", "(", ")", "[", "]", "/"):
s = s.replace(ch, "")
return s
def parse_value(text):
s = text.strip()
try:
if "." in s or "E" in s.upper():
return float(s)
return int(s)
except ValueError:
return s
def format_value(val):
if isinstance(val, float):
return f"{val:14.8E}"
if isinstance(val, int):
return f"{val:14.8E}"
return str(val)
# =====================================================================
# PARAMETER FILE ROUTINES
# =====================================================================
def read_param_lines(filename):
rows = []
params = {}
path = Path(filename)
if not path.exists():
return rows, params
with open(path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
raw = line.rstrip("\n")
s = raw.strip()
if not s or s.startswith("#"):
rows.append((None, None, raw))
continue
if "#" in s:
s_no_comment = s.split("#", 1)[0].strip()
else:
s_no_comment = s
parts = re.split(r"\s+", s_no_comment, maxsplit=1)
if len(parts) < 2:
rows.append((None, None, raw))
continue
name = parts[0].upper()
val = parse_value(parts[1])
params[name] = val
rows.append((name, val, raw))
return rows, params
def get_float(params, name, default):
key = name.upper()
if key in params:
return float(params[key])
return float(default)
def get_int(params, name, default):
key = name.upper()
if key in params:
return int(round(float(params[key])))
return int(default)
def get_text(params, name, default):
key = name.upper()
if key in params:
return str(params[key])
return default
def liquidus_temperature(params, c0):
tmp = get_float(params, "TMP", 327.502)
mliq = get_float(params, "MLIQ", -2.326)
return tmp + mliq * c0
def write_restart_params(filename, param_rows, params, updates):
out_params = dict(params)
for name, val in updates.items():
out_params[name.upper()] = val
written = set()
with open(filename, "w", encoding="utf-8") as f:
for name, _val, raw in param_rows:
if name is None:
f.write(raw + "\n")
continue
key = name.upper()
if key in out_params:
f.write(f"{key:<8} {format_value(out_params[key])}\n")
written.add(key)
for key, val in updates.items():
key = key.upper()
if key not in written:
f.write(f"{key:<8} {format_value(val)}\n")
written.add(key)
# =====================================================================
# DIAGNOSTIC CSV ROUTINES
# =====================================================================
def find_csv_column(names, choices):
lookup = {}
for name in names:
lookup[normalize_name(name)] = name
for choice in choices:
key = normalize_name(choice)
if key in lookup:
return lookup[key]
return None
def read_last_tip_undercooling(filename):
path = Path(filename)
if not path.exists():
raise ValueError("Diagnostic CSV not found: " + filename)
choices = [
"undercoolavg(degC)",
"undercoolavg",
"tipundercooling(degC)",
"tipundercooling",
"dttip(degC)",
"dttip",
"DTCA(degC)",
"DTCA",
]
last = None
col = None
with open(path, "r", newline="", encoding="utf-8", errors="replace") as f:
reader = csv.DictReader(f)
if reader.fieldnames is None:
raise ValueError("Diagnostic CSV has no header: " + filename)
col = find_csv_column(reader.fieldnames, choices)
if col is None:
raise ValueError("Could not find tip-undercooling column in: " + filename)
for row in reader:
text = row.get(col, "")
if text is None:
continue
text = str(text).strip()
if text == "":
continue
try:
last = float(text)
except ValueError:
continue
if last is None:
raise ValueError("No valid tip-undercooling values found in: " + filename)
return last, col
# =====================================================================
# GRID FILE ROUTINES
# =====================================================================
def parse_grid_line(line):
s = line.rstrip("\n")
if not s.strip():
return None
if s.lstrip().startswith("X Y"):
return None
parts = s.split()
if len(parts) >= 8:
try:
return (
int(parts[0]), int(parts[1]),
float(parts[2]), float(parts[3]), float(parts[4]),
float(parts[5]), float(parts[6]), float(parts[7])
)
except ValueError:
pass
try:
return (
int(s[0:4]), int(s[4:8]),
float(s[8:18]), float(s[18:28]), float(s[28:38]),
float(s[38:48]), float(s[48:58]), float(s[58:68])
)
except (ValueError, IndexError):
return None
def read_old_grid(filename):
cells = {}
xmin = xmax = ymin = ymax = None
nvalid = 0
with open(filename, "r", encoding="utf-8", errors="replace") as f:
for line in f:
row = parse_grid_line(line)
if row is None:
continue
x, y = row[0], row[1]
cells[(x, y)] = row
nvalid += 1
if xmin is None:
xmin = xmax = x
ymin = ymax = y
else:
xmin = min(xmin, x)
xmax = max(xmax, x)
ymin = min(ymin, y)
ymax = max(ymax, y)
if nvalid <= 0:
raise ValueError("No valid grid rows found in old grid file.")
return cells, xmin, xmax, ymin, ymax, nvalid
def write_grid(filename, rows):
with open(filename, "w", encoding="utf-8") as f:
f.write(GRID_HEADER)
for row in rows:
x, y, liq, lcomp, scomp, phase, temp, angle = row
f.write(
f"{x:4d}{y:4d}"
f"{liq:10.3f}{lcomp:10.3f}{scomp:10.3f}"
f"{phase:10.2f}{temp:10.2f}{angle:10.4f}\n"
)
# =====================================================================
# SEED CONSTRUCTION
# =====================================================================
def make_seed_grid(old_cells, old_ymax, xlen, ylen, hseed, c0, grad,
target_tseedtop=None):
if hseed < 1:
raise ValueError("HSEED must be at least 1.")
if hseed >= ylen:
raise ValueError("HSEED must be smaller than YLEN.")
y_first = old_ymax - hseed + 1
y_last = old_ymax
rows = []
copied = 0
missing = 0
tseedtop = None
for jnew in range(1, hseed + 1):
jold = y_first + jnew - 1
for i in range(1, xlen + 1):
row = old_cells.get((i, jold))
if row is None:
missing += 1
liq = NUNITS
lcomp = c0
scomp = 0.0
phase = PH_LIQUID
temp = 0.0
angle = ORIENT_LIQUID
else:
_xold, _yold, liq, lcomp, scomp, phase, temp, angle = row
copied += 1
if jnew == hseed and i == 1:
tseedtop = temp
rows.append((i, jnew, liq, lcomp, scomp, phase, temp, angle))
if tseedtop is None or tseedtop < 1.0:
for i in range(1, xlen + 1):
row = old_cells.get((i, y_last))
if row is not None:
tseedtop = row[6]
break
if tseedtop is None:
raise ValueError("Could not determine TSEEDTOP from old grid.")
original_tseedtop = tseedtop
temp_shift = 0.0
if target_tseedtop is not None:
temp_shift = float(target_tseedtop) - tseedtop
newrows = []
for row in rows:
x, y, liq, lcomp, scomp, phase, temp, angle = row
newrows.append((x, y, liq, lcomp, scomp, phase,
temp + temp_shift, angle))
rows = newrows
tseedtop = float(target_tseedtop)
for j in range(hseed + 1, ylen + 1):
temp = tseedtop + grad * float(j - hseed)
for i in range(1, xlen + 1):
rows.append((i, j, NUNITS, c0, 0.0, PH_LIQUID,
temp, ORIENT_LIQUID))
info = {
"old_y_first": y_first,
"old_y_last": y_last,
"copied": copied,
"missing": missing,
"tseedtop_original": original_tseedtop,
"tseedtop": tseedtop,
"temp_shift": temp_shift,
"top_temp": tseedtop + grad * float(ylen - hseed),
}
return rows, info
# =====================================================================
# THERMAL CSV ROUTINES
# =====================================================================
def thermal_columns(fieldnames):
c_time = find_csv_column(fieldnames, ["time_s", "time(s)", "time"])
c_tref = find_csv_column(fieldnames, ["Tref_C", "Tref(C)", "Tref"])
c_gx = find_csv_column(fieldnames, ["Gx_K_per_m", "Gx", "Gx(K/m)"])
c_gy = find_csv_column(fieldnames, ["Gy_K_per_m", "Gy", "Gy(K/m)"])
c_g = find_csv_column(fieldnames, ["G_K_per_m", "G", "grad", "gradient"])
return c_time, c_tref, c_gx, c_gy, c_g
def read_first_thermal_row(filename):
with open(filename, "r", newline="", encoding="utf-8", errors="replace") as f:
reader = csv.DictReader(f)
if reader.fieldnames is None:
raise ValueError("Thermal CSV has no header: " + filename)
row = next(reader, None)
if row is None:
raise ValueError("Thermal CSV has no data rows: " + filename)
c_time, c_tref, c_gx, c_gy, c_g = thermal_columns(reader.fieldnames)
if c_tref is None:
raise ValueError("Thermal CSV needs a Tref column.")
tref = float(row[c_tref])
time0 = float(row[c_time]) if c_time is not None and row[c_time] != "" else 0.0
return time0, tref, c_time, c_tref
def restart_tref_from_seed(tseedtop, grad, hseed, ylen, yref_frac):
jref = 1.0 + float(yref_frac) * float(ylen - 1)
return tseedtop + grad * (jref - float(hseed))
def write_shifted_thermal(infile, outfile, target_tref0):
time0, old_tref0, _c_time, _c_tref = read_first_thermal_row(infile)
shift = float(target_tref0) - old_tref0
with open(infile, "r", newline="", encoding="utf-8", errors="replace") as fin:
reader = csv.DictReader(fin)
fieldnames = reader.fieldnames
if fieldnames is None:
raise ValueError("Thermal CSV has no header: " + infile)
c_time, c_tref, _c_gx, _c_gy, _c_g = thermal_columns(fieldnames)
if c_tref is None:
raise ValueError("Thermal CSV needs a Tref column.")
with open(outfile, "w", newline="", encoding="utf-8") as fout:
writer = csv.DictWriter(fout, fieldnames=fieldnames)
writer.writeheader()
for row in reader:
if c_time is not None and row.get(c_time, "") != "":
try:
row[c_time] = f"{float(row[c_time]) - time0:.8e}"
except ValueError:
pass
try:
row[c_tref] = f"{float(row[c_tref]) + shift:.8e}"
except ValueError:
pass
writer.writerow(row)
info = {
"thermal_old_tref0": old_tref0,
"thermal_new_tref0": target_tref0,
"thermal_shift": shift,
"thermal_time0": time0,
}
return info
# =====================================================================
# COMMAND LINE / INTERACTIVE INPUT
# =====================================================================
class Args:
pass
def default_args():
a = Args()
a.param_file = PARAM_FILE_DEFAULT
a.old_grid = OLD_GRID_DEFAULT
a.param_out = OUT_PARAM_DEFAULT
a.grid_out = OUT_GRID_DEFAULT
a.thermal_in = None
a.thermal_out = OUT_THERMAL_DEFAULT
a.hseed = HSEED_DEFAULT
a.xlen = None
a.ylen = None
a.c0 = None
a.grad = None
a.yref_frac = YREF_FRAC_DEFAULT
a.fin = None
a.diag = None
a.anchor_tip_undercooling = False
a.dtseed = None
a.no_thermal = False
a.quiet = False
a.interactive = False
return a
def parse_args(argv):
args = default_args()
i = 1
if len(argv) == 1:
args.interactive = True
return args
positional = []
while i < len(argv):
arg = argv[i]
if arg in ("-i", "--interactive"):
args.interactive = True
elif arg in ("-p", "--param", "--param-file"):
i += 1; args.param_file = argv[i]
elif arg == "--param-out":
i += 1; args.param_out = argv[i]
elif arg in ("-o", "--output", "--grid-out"):
i += 1; args.grid_out = argv[i]
elif arg == "--thermal-in":
i += 1; args.thermal_in = argv[i]
elif arg == "--thermal-out":
i += 1; args.thermal_out = argv[i]
elif arg == "--hseed":
i += 1; args.hseed = int(argv[i])
elif arg == "--xlen":
i += 1; args.xlen = int(argv[i])
elif arg == "--ylen":
i += 1; args.ylen = int(argv[i])
elif arg == "--c0":
i += 1; args.c0 = float(argv[i])
elif arg == "--grad":
i += 1; args.grad = float(argv[i])
elif arg == "--yref-frac":
i += 1; args.yref_frac = float(argv[i])
elif arg == "--fin":
i += 1; args.fin = float(argv[i])
elif arg == "--diag":
i += 1; args.diag = argv[i]
elif arg in ("--anchor-tip-undercooling", "--use-last-undercooling"):
args.anchor_tip_undercooling = True
elif arg == "--dtseed":
i += 1; args.dtseed = float(argv[i])
elif arg == "--no-thermal":
args.no_thermal = True
elif arg == "--quiet":
args.quiet = True
elif arg in ("-h", "--help"):
print_usage()
raise SystemExit(0)
else:
positional.append(arg)
i += 1
if len(positional) >= 1:
args.old_grid = positional[0]
if len(positional) >= 2:
args.param_file = positional[1]
return args
def print_usage():
print("Usage:")
print(" python3 make4-seed.py")
print(" python3 make4-seed.py old_grid.txt xparam.txt")
print()
print("Main outputs:")
print(" --param-out FILE restart parameter file [xparam_seed.txt]")
print(" --grid-out FILE restart grid file [xgrid_seed.txt]")
print(" --thermal-out FILE restart thermal CSV [xthermal_seed.csv]")
print()
print("Options:")
print(" --thermal-in FILE input thermal CSV; default THFIL from xparam")
print(" --hseed N seed-band height in rows [150]")
print(" --xlen N override XLEN from parameter file")
print(" --ylen N override YLEN from parameter file")
print(" --c0 C override C0 from parameter file")
print(" --grad G override GRAD from parameter file, K/cell")
print(" --yref-frac F thermal reference y fraction [0.5]")
print(" --fin T update FIN in restart parameter file")
print(" --diag FILE diagnostic CSV containing tip undercooling")
print(" --anchor-tip-undercooling")
print(" designed restart: TSEEDTOP=TL0-last_DTtip")
print(" --dtseed K explicit restart undercooling override")
print(" --no-thermal do not write shifted thermal CSV")
print(" --quiet suppress summary")
def interactive_update(args, params):
print()
print("============================================================")
print("CA SEED / RESTART PACKAGE HELPER")
print("============================================================")
args.param_file = ask_string("Input parameter file", args.param_file)
param_rows, params2 = read_param_lines(args.param_file)
params.clear()
params.update(params2)
args.old_grid = ask_string("Old CA grid/output file", args.old_grid)
args.param_out = ask_string("Output restart parameter file", args.param_out)
args.grid_out = ask_string("Output restart grid file", args.grid_out)
tin_default = get_text(params, "THFIL", "xthermal.csv")
args.thermal_in = ask_string("Input thermal CSV", tin_default)
args.thermal_out = ask_string("Output restart thermal CSV", args.thermal_out)
args.xlen = ask_int("XLEN", get_int(params, "XLEN", 200))
args.ylen = ask_int("YLEN", get_int(params, "YLEN", 400))
args.hseed = ask_int("Seed height HSEED", args.hseed)
args.c0 = ask_float("C0 (wt%)", get_float(params, "C0", 8.0))
args.grad = ask_float("GRAD above seed (K/cell)", get_float(params, "GRAD", 0.0))
args.yref_frac = ask_float("Thermal reference y fraction", args.yref_frac)
# Optional research/debug mode:
# This shifts the copied seed band so its top temperature matches
# TL0 - last diagnostic tip undercooling. It is not the normal
# continuation workflow, so it is intentionally not prompted here.
#
# if yes_no("Anchor seed top to last diagnostic tip undercooling", False):
# args.anchor_tip_undercooling = True
# args.diag = ask_string("Diagnostic CSV", "data.csv")
# if yes_no("Anchor seed top to last diagnostic tip undercooling", False):
# args.anchor_tip_undercooling = True
# args.diag = ask_string("Diagnostic CSV", "data.csv")
if yes_no("Override restart FIN", False):
args.fin = ask_float("Restart FIN (s)", get_float(params, "FIN", 10.0))
args.quiet = not yes_no("Print summary after writing", True)
return param_rows, params
# =====================================================================
# SUMMARY
# =====================================================================
def print_summary(args, old_bounds, grid_info, thermal_info, restart_info, nold, nout):
xmin, xmax, ymin, ymax = old_bounds
print()
print("Restart package written")
print("============================================================")
print("Parameter file :", args.param_out)
print("Grid file :", args.grid_out)
if not args.no_thermal:
print("Thermal CSV :", args.thermal_out)
print("Old grid file :", args.old_grid)
print("Input parameter file :", args.param_file)
print("Old grid bounds : X=[%d,%d] Y=[%d,%d]" % (xmin, xmax, ymin, ymax))
print("Old valid rows :", nold)
print("New grid : %d x %d" % (args.xlen, args.ylen))
print("Seed band height :", args.hseed)
print("Old rows copied : %d through %d" %
(grid_info["old_y_first"], grid_info["old_y_last"]))
print("Copied cells :", grid_info["copied"])
if grid_info["missing"] > 0:
print("Missing copied cells :", grid_info["missing"], " (!! check dimensions/file)")
print("Liquid fill rows : %d through %d" % (args.hseed + 1, args.ylen))
print("C0 liquid fill : %.6g wt%%" % args.c0)
print("GRAD above seed : %.6g K/cell" % args.grad)
print("TSEEDTOP original : %.6g C" % grid_info["tseedtop_original"])
if abs(grid_info["temp_shift"]) > 1.0e-12:
print("Grid temp shift : %.6g K" % grid_info["temp_shift"])
print("TSEEDTOP anchored : %.6g C" % grid_info["tseedtop"])
else:
print("TSEEDTOP : %.6g C" % grid_info["tseedtop"])
print("TL0 : %.6g C" % restart_info["tl0"])
print("Restart DTSEED : %.6g K" % restart_info["dtseed"])
print("Restart Tref0 : %.6g C" % restart_info["target_tref0"])
print("New top temperature : %.6g C" % grid_info["top_temp"])
if restart_info.get("diag_file"):
print("Diagnostic CSV :", restart_info["diag_file"])
print("Undercooling column :", restart_info["diag_column"])
print("Last tip undercooling: %.6g K" % restart_info["diag_undercooling"])
if thermal_info:
print("Thermal old Tref0 : %.6g C" % thermal_info["thermal_old_tref0"])
print("Thermal shift : %.6g K" % thermal_info["thermal_shift"])
print("Thermal time reset : old first time %.6g s -> 0" %
thermal_info["thermal_time0"])
print("Output grid rows :", nout)
print("============================================================")
# =====================================================================
# MAIN PROGRAM
# =====================================================================
def main():
args = parse_args(sys.argv)
param_rows, params = read_param_lines(args.param_file)
if args.interactive:
param_rows, params = interactive_update(args, params)
else:
if args.xlen is None:
args.xlen = get_int(params, "XLEN", 200)
if args.ylen is None:
args.ylen = get_int(params, "YLEN", 400)
if args.c0 is None:
args.c0 = get_float(params, "C0", 8.0)
if args.grad is None:
args.grad = get_float(params, "GRAD", 0.0)
if args.thermal_in is None:
args.thermal_in = get_text(params, "THFIL", "xthermal.csv")
old_cells, xmin, xmax, ymin, ymax, nold = read_old_grid(args.old_grid)
if xmin != 1 or xmax < args.xlen:
print("Warning: old grid X range may not cover requested XLEN.")
if (ymax - ymin + 1) < args.hseed:
raise ValueError("Old grid is shorter than HSEED.")
tl0 = liquidus_temperature(params, args.c0)
target_tseedtop = None
restart_info = {"tl0": tl0}
if args.dtseed is not None:
target_tseedtop = tl0 - args.dtseed
restart_info["dtseed_source"] = "command line --dtseed"
elif args.anchor_tip_undercooling:
if args.diag is None:
raise ValueError("Use --diag FILE with --anchor-tip-undercooling.")
dt_tip, diag_col = read_last_tip_undercooling(args.diag)
target_tseedtop = tl0 - dt_tip
restart_info.update({
"diag_file": args.diag,
"diag_column": diag_col,
"diag_undercooling": dt_tip,
"dtseed_source": "diagnostic tip undercooling",
})
rows, grid_info = make_seed_grid(
old_cells, ymax, args.xlen, args.ylen, args.hseed,
args.c0, args.grad, target_tseedtop
)
dtseed_restart = tl0 - grid_info["tseedtop"]
target_tref0 = restart_tref_from_seed(
grid_info["tseedtop"], args.grad, args.hseed, args.ylen, args.yref_frac
)
restart_info["dtseed"] = dtseed_restart
restart_info["target_tref0"] = target_tref0
write_grid(args.grid_out, rows)
thermal_info = None
if not args.no_thermal:
thermal_info = write_shifted_thermal(args.thermal_in, args.thermal_out, target_tref0)
updates = {
"PARFIL": args.param_out,
"GRIDFIL": args.grid_out,
"THFIL": args.thermal_out if not args.no_thermal else args.thermal_in,
"DTSEED": dtseed_restart,
"XLEN": args.xlen,
"YLEN": args.ylen,
}
if args.fin is not None:
updates["FIN"] = args.fin
write_restart_params(args.param_out, param_rows, params, updates)
if not args.quiet:
print_summary(args, (xmin, xmax, ymin, ymax), grid_info,
thermal_info, restart_info, nold, len(rows))
return 0
if __name__ == "__main__":
raise SystemExit(main())