Repository navigation
Expand file tree
/
Copy pathrunpart3.py
More file actions
115 lines (107 loc) · 7.53 KB
/
Copy pathrunpart3.py
File metadata and controls
115 lines (107 loc) · 7.53 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
"""AstroSimBench Part 3 runner (lessons 3A-3E, then the 3F summary).
Usage
-----
python runpart3.py Run 3A-3E, then build 3F.
python runpart3.py --only 3D 3E Run selected lessons in course order.
python runpart3.py --only 3F Summarize existing project results only.
python runpart3.py --show Display figures; close windows to continue.
python runpart3.py --list List the lessons without running them.
Repeat --results-root PATH to add earlier result folders as 3F inputs.
Each batch writes its own folder; 3F reads that batch plus existing Part 1
and Part 2 results.
"""
from pathlib import Path
from datetime import datetime
import argparse,importlib.util,json,os,subprocess,sys
ROOT=Path(__file__).resolve().parent
EXPERIMENTS=(
('3A','Five bodies: planar and spatial comparison','exp3a_five_body.py','3A_five_body'),
('3B','Body count and computational cost','exp3b_n_scaling.py','3B_n_scaling'),
('3C','Inner and outer orbital timescales','exp3c_timescale_span.py','3C_timescale_span'),
('3D','Three-dimensional self-gravitating cluster','exp3d_self_gravitating_cluster.py','3D_self_gravitating_cluster'),
('3E','Statistical comparison beyond the reference window','exp3e_ensemble_statistics.py','3E_ensemble_statistics'),
('3F','Measured integrator regime chart','exp3f_regime_chart.py','3F_regime_chart'))
def save_status(batch,completed,failed,skipped,selected):
"""Write execution status, kept separate from scientific target compliance."""
(batch/'batch_summary.json').write_text(json.dumps(dict(
status='completed' if not failed and not skipped else 'incomplete',
selected=selected,completed=completed,failed=failed,skipped=skipped,
note='execution completion is separate from numerical accuracy and statistical compatibility'),
ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
def main(argv=None):
"""Run the selected lessons in course order and return the batch exit status."""
for stream in (sys.stdout,sys.stderr):
if hasattr(stream,'reconfigure'):stream.reconfigure(errors='replace')
parser=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--only',nargs='+',type=str.upper,choices=[r[0] for r in EXPERIMENTS],metavar='ID',help='Run selected lessons, for example --only 3A 3F')
parser.add_argument('--show',action='store_true',help='Show figures; close windows to continue')
parser.add_argument('--list',action='store_true',help='List experiments and exit')
parser.add_argument('--output',type=Path,help='Parent directory for this batch, default results/part3')
parser.add_argument('--results-root',type=Path,action='append',default=[],help='Additional existing result directory passed to 3F')
args=parser.parse_args(argv)
if args.list:
for code,title,name,_ in EXPERIMENTS:print(f'{code} {title}\n experiments/n_body/{name}')
return 0
selected=[r for r in EXPERIMENTS if args.only is None or r[0] in args.only]
codes=[r[0] for r in selected];folder=ROOT/'experiments'/'n_body'
missing=[str(folder/name) for _,_,name,_ in selected if not (folder/name).is_file()]
if missing:
print('Experiment files missing. Merge the complete package into the project root:\n'+'\n'.join(missing),file=sys.stderr);return 2
sys.path.insert(0,str(ROOT))
dependencies=('numpy','matplotlib') if codes==['3F'] else ('numpy','matplotlib','astrosimbench','rebound')
missing=[n for n in dependencies if importlib.util.find_spec(n) is None]
if missing:
print('Missing dependencies: '+', '.join(missing)+'\nAt the project root run: python -m pip install -e ".[plots,reference]"',file=sys.stderr);return 2
extra_roots=[p.resolve() for p in args.results_root]
if any(not p.is_dir() for p in extra_roots):
print('--results-root must be an existing directory.',file=sys.stderr);return 2
base=args.output.resolve() if args.output else ROOT/'results'/'part3'
batch=base/datetime.now().strftime('batch_%Y%m%d_%H%M%S_%f');batch.mkdir(parents=True,exist_ok=False)
env=os.environ.copy();env['PYTHONUTF8']='1';env['PYTHONIOENCODING']='utf-8'
env['PYTHONPATH']=str(ROOT)+(os.pathsep+env['PYTHONPATH'] if env.get('PYTHONPATH') else '')
# Default to single-thread BLAS for small Newton systems; respect the user's existing environment settings.
env.setdefault('OPENBLAS_NUM_THREADS','1');env.setdefault('OMP_NUM_THREADS','1')
completed,failed,skipped=[],[],[]
print('Run order: '+' -> '.join(codes)+f'\nBatch output: {batch}',flush=True)
for index,(code,title,name,lesson_dir) in enumerate(selected,1):
# If the batch is incomplete, do not let F fill missing Part 3 data from older runs and imply success.
if code=='3F' and failed:
skipped.append(code);print('3F skipped: resolve the earlier experiment failures in this batch first.',flush=True);continue
command=[sys.executable,'-u',str(folder/name),'--output',str(batch)]
if not args.show:command.append('--no-show')
if code=='3F':
roots=([ROOT/'results'] if codes==['3F'] else [batch,ROOT/'results'/'part1',ROOT/'results'/'part2'])
for p in [*roots,*extra_roots]:
if p.is_dir():command.extend(['--results-root',str(p)])
print(f'\n[{index}/{len(selected)}] {code}: {title}',flush=True)
try:
outcome=subprocess.run(command,cwd=ROOT,env=env,check=False)
except KeyboardInterrupt:
failed.append(code);skipped.extend(c for c in codes[index:] if c not in skipped)
save_status(batch,completed,failed,skipped,codes);print('\nStopped; saved results retained.',flush=True);return 130
except OSError as exc:
failed.append(code);print(f'{code} could not start: {exc}',file=sys.stderr,flush=True);continue
completion=list((batch/lesson_dir).glob('*/completion.json'))
if outcome.returncode!=0 or len(completion)!=1:
failed.append(code);print(f'{code} incomplete (exit code {outcome.returncode}); continuing to the next independent lesson.',file=sys.stderr,flush=True)
else:
try:
report=json.loads(completion[0].read_text(encoding='utf-8'))
if not isinstance(report,dict):raise ValueError('completion must be an object')
except (OSError,ValueError) as exc:
failed.append(code)
print(f'{code} could not read completion marker: {exc}',file=sys.stderr,flush=True)
save_status(batch,completed,failed,skipped,codes)
continue
# Numerical failure differs from unmet accuracy targets, reference floors, budget skips, and statistical incompatibility.
if report.get('status')!='completed' or report.get('failed_runs',report.get('numerical_failures',0)):
failed.append(code);print(f'{code} recorded numerical failures; inspect this lesson\'s results.',file=sys.stderr,flush=True)
else:completed.append(code);print(code+' completed.',flush=True)
save_status(batch,completed,failed,skipped,codes)
save_status(batch,completed,failed,skipped,codes)
print('\nCompleted: '+(', '.join(completed) or 'None'),flush=True)
if failed:print('Incomplete: '+', '.join(failed),flush=True)
if skipped:print('Skipped: '+', '.join(skipped),flush=True)
print('Read lesson checks for accuracy and statistics; successful execution does not mean every method meets its target.',flush=True)
return 1 if failed or skipped else 0
if __name__=='__main__':raise SystemExit(main())