Repository navigation
Expand file tree
/
Copy pathrunpart2.py
More file actions
107 lines (98 loc) · 5.46 KB
/
Copy pathrunpart2.py
File metadata and controls
107 lines (98 loc) · 5.46 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
"""AstroSimBench Part 2 runner (lessons 2A-2G and 2R).
Usage
-----
python runpart2.py Run 2A-2G and 2R; save all figures.
python runpart2.py --only 2A 2R Run selected lessons in course order.
python runpart2.py --show Display figures; close windows to continue.
python runpart2.py --list List the lessons without running them.
Each lesson runs in a separate process using the current interpreter and
the project directory.
"""
from pathlib import Path
import argparse
import importlib.util
import os
import subprocess
import sys
ROOT = Path(__file__).resolve().parent
EXPERIMENTS = (
('2A', 'Full planetary three-body: physical perturbation and numerical error', 'exp2a_planetary_three_body.py'),
('2B', 'Convergence order and error-cost comparison', 'exp2b_convergence_efficiency.py'),
('2C', 'Perturbation-strength scan', 'exp2c_perturbation_scan.py'),
('2D', 'Long-term invariants, orbital elements, and phase', 'exp2d_long_term_dynamics.py'),
('2E', 'Close encounters and step selection', 'exp2e_close_encounter.py'),
('2F', 'Spatial three-body motion and total angular momentum vector', 'exp2f_spatial_three_body.py'),
('2G', 'Sensitive three-body motion and reference validity window', 'exp2g_reference_horizon.py'),
('2R', 'Massless tracer and circular restricted three-body motion', 'exp2r_restricted_three_body.py'),
)
def main(argv=None):
"""Run the selected lessons in course order and return the batch exit status."""
# Avoid interrupting long runs if a Windows terminal cannot display a character.
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=[item[0] for item in EXPERIMENTS], metavar='ID',
help='Run selected lessons, for example --only 2A 2F 2R')
parser.add_argument('--show', action='store_true', help='Show figures one at a time; close each window to continue')
parser.add_argument('--list', action='store_true', help='List experiments and exit')
args = parser.parse_args(argv)
if args.list:
for code, title, filename in EXPERIMENTS:
print(f'{code} {title}\n experiments/three_body/{filename}')
return 0
# Preserve lesson parameters: the default runs all eight full default experiments.
selected = [item for item in EXPERIMENTS if args.only is None or item[0] in args.only]
folder = ROOT/'experiments'/'three_body'
missing_files = [str(folder/name) for _, _, name in selected if not (folder/name).is_file()]
if missing_files:
print('Experiment files missing. Merge the complete experiments folder into the project root: ', file=sys.stderr)
for filename in missing_files:
print(filename, file=sys.stderr)
return 2
missing = [name for name in ('numpy', 'matplotlib', 'rebound', 'astrosimbench')
if importlib.util.find_spec(name) is None]
if missing:
print('Missing dependencies: '+', '.join(missing), file=sys.stderr)
print('At the project root containing pyproject.toml, run: ', file=sys.stderr)
print('python -m pip install -e ".[plots,reference]"', file=sys.stderr)
return 2
# Pass argument lists directly to subprocesses without a shell; supports Windows paths with spaces.
env = os.environ.copy()
env['PYTHONUTF8'] = '1'
env['PYTHONIOENCODING'] = 'utf-8'
env['PYTHONPATH'] = str(ROOT)+(os.pathsep+env['PYTHONPATH'] if env.get('PYTHONPATH') else '')
print('Run order: '+' -> '.join(item[0] for item in selected), flush=True)
print(f'Results directory: {ROOT / "results" / "part2"}', flush=True)
print('Each run creates a separate result directory; 2D defaults to 100 inner orbital periods.', flush=True)
completed, failed = [], []
for index, (code, title, filename) in enumerate(selected, 1):
print(f'\n[{index}/{len(selected)}] {code}: {title}', flush=True)
command = [sys.executable, '-u', str(folder/filename)]
if not args.show:
command.append('--no-show')
try:
result = subprocess.run(command, cwd=ROOT, env=env, check=False)
except KeyboardInterrupt:
print('\nStopped subsequent experiments; saved results have been retained.', file=sys.stderr, flush=True)
return 130
except OSError as exc:
print(f'{code} could not start: {exc}', file=sys.stderr, flush=True)
failed.append(code)
continue
if result.returncode == 0:
completed.append(code)
print(f'{code} completed.', flush=True)
else:
failed.append(code)
print(f'{code} exit code {result.returncode}; continuing to the next lesson. Error details remain above.', file=sys.stderr, flush=True)
print('\nPart 2 results for this run:', flush=True)
print('Completed: '+(', '.join(completed) or 'None'), flush=True)
if failed:
print('Incomplete: '+', '.join(failed), flush=True)
print('After fixing the issue, rerun: python runpart2.py --only '+' '.join(failed), flush=True)
print('Completed means execution finished; assess numerical accuracy using diagnostic figures and tables.', flush=True)
return 1 if failed else 0
if __name__ == '__main__':
raise SystemExit(main())