-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessRM.py
More file actions
executable file
·2161 lines (1917 loc) · 87.5 KB
/
Copy pathprocessRM.py
File metadata and controls
executable file
·2161 lines (1917 loc) · 87.5 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
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
#!/usr/bin/env python3
"""
==================================================================
____ ____ __ __
| _ \\ _ __ ___ ___ ___ ___ ___| _ \\| \\/ |
| |_) | '__/ _ \\ / __/ _ \\/ __/ __| |_) | |\\/| |
| __/| | | (_) | (_| __/\\__ \\__ \\ _ <| | | |
|_| |_| \\___/ \\___\\___||___/___/_| \\_\\_||_|
processRM - RM Synthesis Pipeline Orchestrator
RM-synthesis made simple
==================================================================
Modeled after processMeerKAT.
Usage:
BUILD a new config (you provide a full-Stokes IQUV cube + freq list):
processRM -B -F mycube_IQUV.fits -f mycube.freqlist.txt
processRM -B -F mycube_IQUV.fits -f freqs.txt -C run1.txt # custom name
RUN an existing config:
processRM -R myconfig.txt
processRM -R myconfig.txt -s # also auto-submit
After build/setup, run:
./submit_pipeline.sh # submits SLURM jobs
./fullSummary # check pipeline status
"""
__version__ = '2.0'
import argparse
import os
import sys
import glob
import json
import shutil
import logging
import re
import subprocess
from datetime import datetime
from time import gmtime
import config_parser
import cube_validator
import region_parser
# ---- Container helpers ------------------------------------------------------
# All Python that needs astropy / RM-Tools runs inside the rm-env container;
# the helpers below run small snippets of cube_validator / region_parser via
# `singularity exec`. The local import paths exist only as a no-op fast path
# when astropy happens to be available on the host; logs don't mention that
# distinction because the container is the only intended source.
def _resolve_rm_container_path(args):
"""Resolve the rm-env.sif location BUILD should call into.
Priority: --rm-container override > install default (~/processRM/container).
The config-file value isn't consulted here because BUILD runs before the
workdir config is written.
"""
if getattr(args, 'rm_container_override', None):
return os.path.abspath(os.path.expanduser(args.rm_container_override))
return os.path.join(SCRIPT_DIR, 'container', 'rm-env.sif')
class _LoginNodeUnsupported(RuntimeError):
"""singularity exec itself can't run here and we have no usable fallback.
On ilifu this typically means we're on the login node AND `sacctmgr`
didn't return a default account for the srun wrapper."""
def _on_compute_node():
"""True when we're inside a SLURM allocation (srun/sbatch/small-sesh).
Outside one, $SLURM_JOB_ID is unset -- that's the login node."""
return bool(os.environ.get('SLURM_JOB_ID'))
_SLURM_DEFAULT_ACCOUNT_CACHE = [] # sentinel: empty = not resolved yet
_SLURM_VALID_ACCOUNTS_CACHE = [] # sentinel: empty = not resolved yet
_SLURM_ACCOUNT_WARNED = set() # preferred accounts we've already warned about
def _slurm_default_account():
"""User's DefaultAccount from `sacctmgr`. Cached per process."""
if _SLURM_DEFAULT_ACCOUNT_CACHE:
return _SLURM_DEFAULT_ACCOUNT_CACHE[0]
user = os.environ.get('USER', '')
account = None
if user:
try:
result = subprocess.run(
['sacctmgr', '-nP', 'show', 'user', user, 'format=DefaultAccount'],
capture_output=True, text=True, timeout=10,
)
if result.returncode == 0:
first = (result.stdout or '').strip().splitlines()
if first and first[0].strip():
account = first[0].strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
_SLURM_DEFAULT_ACCOUNT_CACHE.append(account)
return account
def _slurm_valid_accounts():
"""Every SLURM account this user can submit under, from `sacctmgr`.
Returns [] if sacctmgr is unavailable (in which case we can't validate
the user's choice and silently accept it)."""
if _SLURM_VALID_ACCOUNTS_CACHE:
return _SLURM_VALID_ACCOUNTS_CACHE[0]
user = os.environ.get('USER', '')
accounts = []
if user:
try:
result = subprocess.run(
['sacctmgr', '-nP', 'show', 'association',
f'user={user}', 'format=Account'],
capture_output=True, text=True, timeout=10,
)
if result.returncode == 0:
seen = set()
for line in (result.stdout or '').splitlines():
acct = line.strip()
if acct and acct not in seen:
seen.add(acct)
accounts.append(acct)
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
_SLURM_VALID_ACCOUNTS_CACHE.append(accounts)
return accounts
def _resolve_slurm_account(preferred=None):
"""Pick the SLURM account to use for an srun-wrapped container exec.
Priority:
1. `preferred` (typically the config's [slurm] account) -- used as-is
when sacctmgr can't enumerate the user's accounts (we trust the
user) or when it's in the user's valid list.
2. If `preferred` is given but is NOT in the user's valid list, warn
(once per preferred value) and fall back to the user's
DefaultAccount.
3. If `preferred` is empty/None, return the DefaultAccount.
Returns None if no account can be determined at all.
"""
preferred = (preferred or '').strip().strip("'\"") or None
if preferred is None:
return _slurm_default_account()
valid = _slurm_valid_accounts()
if not valid or preferred in valid:
return preferred
if preferred not in _SLURM_ACCOUNT_WARNED:
_SLURM_ACCOUNT_WARNED.add(preferred)
default = _slurm_default_account()
logger.warning(
f" -> SLURM account '{preferred}' from the config is NOT in "
f"your list of valid accounts ({', '.join(valid)}). "
f"Falling back to your default account "
f"({default if default else 'unknown'}). Edit [slurm] account "
f"in the config to one of the valid accounts to silence this."
)
return _slurm_default_account()
def _container_python(container_path, code, timeout=180, account=None):
"""Run a Python snippet inside the rm-env container; return stdout (str).
On a compute node (``$SLURM_JOB_ID`` is set) we call singularity exec
directly. On a login node we wrap it in ``srun`` so the snippet runs
on a compute node and stdout streams back to the caller's terminal --
ilifu login nodes don't grant user-namespace mappings, so a direct
singularity exec there would always fail.
``account`` (optional) is the preferred SLURM account from the config;
if the user doesn't have access to it we fall back to their default
(and warn once). Pass None to always use the default.
Raises:
FileNotFoundError -- container_path doesn't exist, or singularity
/ srun binary missing.
_LoginNodeUnsupported -- we're on a login node but can't determine a
SLURM account for the srun wrapper.
RuntimeError -- non-zero exit from the snippet itself.
"""
if not os.path.exists(container_path):
raise FileNotFoundError(container_path)
if _on_compute_node():
cmd = ['singularity', '--quiet', 'exec', container_path,
'python3', '-c', code]
outer_timeout = timeout
else:
# Login node -> srun a tiny compute slot. Defaults match
# processMeerKAT's lightweight validation jobs: 1 CPU, 2 GB, 5 min.
account = _resolve_slurm_account(preferred=account)
if account is None:
raise _LoginNodeUnsupported(
"BUILD-time validation needs to run on a compute node but "
"couldn't determine your SLURM account (sacctmgr did not "
"return a DefaultAccount). Set one with: "
"`sacctmgr modify user name=$USER set DefaultAccount=<account>` "
"or grab a compute session manually (e.g. `small-sesh`)."
)
logger.info(f" -> running validation on a compute node via srun "
f"(account={account}, this can take a few seconds)...")
cmd = ['srun', '--quiet',
'--partition=Main',
'--time=00:05:00',
'--mem=2G',
'--cpus-per-task=1',
f'--account={account}',
'singularity', '--quiet', 'exec', container_path,
'python3', '-c', code]
# Generous wall-time -- queue wait + exec time.
outer_timeout = timeout + 600
try:
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=outer_timeout,
)
except FileNotFoundError as e:
raise FileNotFoundError(str(e))
if result.returncode != 0:
err = (result.stderr or result.stdout or 'exec failed').strip()
# If srun managed to land us on a node that ALSO can't unshare
# namespaces, or if we're on a compute node misconfigured the same
# way, surface the cleaner message instead of the raw Apptainer dump.
if 'setgroups' in err or 'user namespace mappings' in err:
raise _LoginNodeUnsupported(
"singularity exec couldn't unshare a user namespace even on "
"the compute node it ran on. Try a different partition or "
"ask ilifu support."
)
raise RuntimeError(err)
return result.stdout
def _validate_cube_via_container(container_path, cube_path, freqlist_path, account=None):
"""Re-run cube_validator.validate_freqlist_against_cube inside the container.
``account`` (optional): preferred SLURM account from the config; falls
back to user's default if not in the user's valid-accounts list.
Returns the same dict structure the local helper does. Raises
``cube_validator.CubeStructureError`` if the validation failed inside the
container (a real structural problem with the cube, not an env issue).
"""
code = (
"import sys, json\n"
f"sys.path.insert(0, {SCRIPT_DIR!r})\n"
"import cube_validator\n"
"try:\n"
f" info = cube_validator.validate_freqlist_against_cube({cube_path!r}, {freqlist_path!r})\n"
# the axes dict is fine; ints are JSON-safe
" print(json.dumps({'ok': True, 'info': info}))\n"
"except cube_validator.CubeStructureError as e:\n"
" print(json.dumps({'ok': False, 'error': str(e)}))\n"
)
stdout = _container_python(container_path, code, account=account)
payload = json.loads(stdout.strip().splitlines()[-1])
if not payload['ok']:
raise cube_validator.CubeStructureError(payload['error'])
return payload['info']
def _has_beam_info_via_container(container_path, cube_path, account=None):
"""Re-run cube_validator.has_beam_info inside the container."""
code = (
"import sys, json\n"
f"sys.path.insert(0, {SCRIPT_DIR!r})\n"
"import cube_validator\n"
f"print(json.dumps(cube_validator.has_beam_info({cube_path!r})))\n"
)
stdout = _container_python(container_path, code, account=account)
return json.loads(stdout.strip().splitlines()[-1])
def _naxis2_via_container(container_path, cube_path, account=None):
"""Return NAXIS2 (image height in pixels) read inside the container."""
code = (
"import json\n"
"from astropy.io import fits\n"
f"print(json.dumps(int(fits.getheader({cube_path!r})['NAXIS2'])))\n"
)
stdout = _container_python(container_path, code, account=account)
return json.loads(stdout.strip().splitlines()[-1])
def _transpose_cube_via_container(container_path, cube_path, account=None):
"""Run cube_validator.transpose_cube_in_place inside the container.
Returns True if a transpose actually happened, False otherwise.
"""
code = (
"import sys, json\n"
f"sys.path.insert(0, {SCRIPT_DIR!r})\n"
"import cube_validator\n"
f"changed = cube_validator.transpose_cube_in_place({cube_path!r})\n"
"print(json.dumps(bool(changed)))\n"
)
stdout = _container_python(container_path, code, timeout=600, account=account)
return json.loads(stdout.strip().splitlines()[-1])
def _parse_region_via_container(container_path, region_path, cube_path, account=None):
"""Re-run region_parser.parse_region_file inside the container.
Loads the cube's WCS header inside the container so world-coord regions
can be converted to pixel coords. Returns the same list of dicts the
local helper does.
"""
code = (
"import sys, json\n"
f"sys.path.insert(0, {SCRIPT_DIR!r})\n"
"from astropy.io import fits\n"
"import region_parser\n"
f"hdr = fits.getheader({cube_path!r})\n"
f"regs = region_parser.parse_region_file({region_path!r}, hdr)\n"
"print(json.dumps(regs))\n"
)
stdout = _container_python(container_path, code, account=account)
return json.loads(stdout.strip().splitlines()[-1])
def update_config_inplace(config_path, updates):
"""Update specific keys in an INI file while preserving comments, blank lines,
and column alignment of inline comments.
Python's configparser.write() drops all inline comments, which would destroy
the per-parameter guidance baked into default_config.txt. This function does
a line-by-line rewrite that touches only the value of targeted keys.
updates: dict mapping (section, key) -> new value (string, already quoted/formatted)
"""
with open(config_path) as f:
lines = f.readlines()
# group 1 = indent, 2 = key, 3 = ' = ' (with surrounding whitespace),
# 4 = value (greedy stop at whitespace+#), 5 = trailing whitespace, 6 = comment, 7 = newline
line_re = re.compile(
r'^(\s*)([A-Za-z_]\w*)(\s*=\s*)(.*?)([ \t]*)(#.*)?(\r?\n?)$'
)
section_re = re.compile(r'^\s*\[([^\]]+)\]')
current_section = None
out = []
for line in lines:
sec_match = section_re.match(line)
if sec_match:
current_section = sec_match.group(1)
out.append(line)
continue
stripped = line.strip()
if not stripped or stripped.startswith('#'):
out.append(line)
continue
m = line_re.match(line)
if not (m and current_section):
out.append(line)
continue
indent, key, eq, old_value, gap, comment, newline = m.groups()
comment = comment or ''
gap = gap or ''
target = (current_section, key)
if target not in updates:
out.append(line)
continue
new_value = updates[target]
if comment:
# Keep the comment at its original column for alignment
original_value_end = len(indent) + len(key) + len(eq) + len(old_value)
comment_col = original_value_end + len(gap)
new_value_end = len(indent) + len(key) + len(eq) + len(new_value)
needed_gap = max(comment_col - new_value_end, 1)
out.append(f"{indent}{key}{eq}{new_value}{' ' * needed_gap}{comment}{newline}")
else:
out.append(f"{indent}{key}{eq}{new_value}{newline}")
with open(config_path, 'w') as f:
f.writelines(out)
class ColoredFormatter(logging.Formatter):
"""Tint the level name green/orange/red; leave the message alone."""
GREEN = '\033[92m'
ORANGE = '\033[93m'
RED = '\033[91m'
RESET = '\033[0m'
def format(self, record):
original_level = record.levelname
if original_level == 'INFO':
record.levelname = f'{self.GREEN}INFO{self.RESET}'
elif original_level == 'WARNING':
record.levelname = f'{self.ORANGE}WARN{self.RESET}'
elif original_level in ('ERROR', 'CRITICAL'):
record.levelname = f'{self.RED}{original_level}{self.RESET}'
formatted = super().format(record)
record.levelname = original_level
return formatted
logging.Formatter.converter = gmtime
logger = logging.getLogger(__name__)
_handler = logging.StreamHandler(stream=sys.stdout) # stdout so it interleaves with print() output
_handler.setFormatter(ColoredFormatter(fmt="%(asctime)-15s %(levelname)s: %(message)s"))
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
logger.propagate = False
THIS_PROG = os.path.realpath(__file__)
SCRIPT_DIR = os.path.dirname(THIS_PROG)
TEMPLATES_DIR = os.path.join(SCRIPT_DIR, 'templates')
AUX_DIR = os.path.join(SCRIPT_DIR, 'aux_scripts')
DEFAULT_CONFIG = os.path.join(SCRIPT_DIR, 'default_config.txt')
MASTER_SCRIPT = 'submit_pipeline.sh'
# ilifu-specific paths and settings
ILIFU_CONTAINER_DIR = '/idia/software/containers'
ILIFU_PROJECTS_DIR = '/idia/projects'
ILIFU_USERS_DIR = '/users'
ILIFU_DEFAULT_CONTAINER = '/idia/software/containers/casa-6.4.4-modular.simg'
def check_ilifu_environment():
"""
Verify the user is running on the ilifu cluster.
processRM is designed ONLY for ilifu and will not work elsewhere.
"""
ilifu_indicators = [
ILIFU_CONTAINER_DIR,
ILIFU_USERS_DIR,
]
found = [p for p in ilifu_indicators if os.path.exists(p)]
if not found:
logger.error("=" * 60)
logger.error("processRM is designed ONLY for the ilifu cluster")
logger.error("=" * 60)
logger.error("This system does not appear to be on ilifu:")
for p in ilifu_indicators:
logger.error(f" - {p}: NOT FOUND")
logger.error("")
logger.error("Please ssh into ilifu first:")
logger.error(" ssh -A amani@slurm.ilifu.ac.za")
logger.error("")
sys.exit(1)
# Check SLURM is available (sbatch command)
if not shutil.which('sbatch'):
logger.error("sbatch not found in PATH.")
logger.error("processRM requires SLURM (only available on ilifu compute environment).")
logger.error("If you are on the login node, ensure 'bash -l' is loaded.")
sys.exit(1)
# Pipeline template scripts (copied into working dir)
PIPELINE_SCRIPTS = [
'create_subimage.py',
'create_subimage_rmsy_cube.py',
'run_parallel_rmsy.py',
'merge_image_parts.py',
]
# Aux scripts (copied into working dir)
AUX_SCRIPTS = [
'fullSummary',
]
def parse_args():
"""Parse command-line arguments for processRM."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# BUILD a config from a full Stokes IQUV cube + freq list (default name: myconfig.txt)
processRM -B -F mycube_IQUV.fits -f mycube.freqlist.txt
# BUILD with a custom config name
processRM -B -F mycube_IQUV.fits -f mycube.freqlist.txt -C run1.txt
# BUILD with a specific chunk count
processRM -B -F mycube_IQUV.fits -f freqs.txt --chunks 50
# BUILD and submit immediately
processRM -B -F mycube_IQUV.fits -f freqs.txt -s
# RUN an existing config (regenerate submit_pipeline.sh from it)
processRM -R myconfig.txt
# RUN and submit immediately
processRM -R myconfig.txt -s
"""
)
parser.add_argument('-B', '--build', action='store_true',
help='BUILD mode: generate a new config from the inputs given via '
'-F / -f / -r / --chunks. Does not submit anything unless -s is '
'also passed. Mutually exclusive with -R.')
parser.add_argument('-F', '--fitsfile',
help='BUILD mode: path to the full-Stokes IQUV radio-continuum cube '
'(e.g. mycube_IQUV.fits). processRM extracts Stokes I, Q, and U '
'internally; standalone Q/U cubes are not accepted. Relative or '
'absolute paths are fine — processRM will symlink the file into '
'the current directory so all outputs land here.')
parser.add_argument('-f', '--freqlist',
help='Path to frequency list (.txt). Required when -B is used.')
parser.add_argument('-r', '--region-file', dest='region_file', default=None,
help='Optional CARTA region file (.crtf or .ds9, pixel or world). '
'Boxed regions only. Each box becomes an independent processing '
'branch. When set, the config [data] crop/pointing values are ignored.')
parser.add_argument('-C', '--config',
help='Optional name for the config built from -F '
'(default: myconfig.txt).')
parser.add_argument('-R', '--run',
dest='run_config',
help='RUN mode: load an existing config file and regenerate '
'submit_pipeline.sh from it (no FITS inputs needed).')
parser.add_argument('-s', '--submit', action='store_true',
help='Auto-submit the pipeline after generation')
parser.add_argument('--chunks', type=int,
help='Number of chunks to split image into (must be <= parallel in config)')
parser.add_argument('--workdir', default=None,
help='Working directory (defaults to current directory)')
parser.add_argument('--rm-container', dest='rm_container_override', default=None,
help='Override path to rm-env.sif (default: ~/processRM/container/rm-env.sif). '
'Use this if you moved the container to a project-shared location.')
parser.add_argument('--version', action='version', version=f'processRM {__version__}')
args = parser.parse_args()
return args
def setup_workdir(workdir):
"""Create working directory and required subdirectories."""
if workdir is None:
workdir = os.getcwd()
workdir = os.path.abspath(workdir)
if not os.path.exists(workdir):
os.makedirs(workdir)
logger.info(f"Created working directory: {workdir}")
# Create subdirectories
for subdir in ['logs', 'processing', 'errors']:
path = os.path.join(workdir, subdir)
if not os.path.exists(path):
os.makedirs(path)
# Create error subdirectories for organization
error_subdirs = ['extract', 'rmsynth', 'rmclean', 'merge']
for subdir in error_subdirs:
path = os.path.join(workdir, 'errors', subdir)
if not os.path.exists(path):
os.makedirs(path)
return workdir
def copy_pipeline_scripts(workdir):
"""Copy template scripts into the working directory."""
for script in PIPELINE_SCRIPTS:
src = os.path.join(TEMPLATES_DIR, script)
dst = os.path.join(workdir, script)
if not os.path.exists(src):
logger.warning(f"Template script not found: {src}")
continue
shutil.copy2(src, dst)
os.chmod(dst, 0o755)
logger.info(f"Copied: {script}")
for script in AUX_SCRIPTS:
src = os.path.join(AUX_DIR, script)
dst = os.path.join(workdir, script)
if not os.path.exists(src):
logger.warning(f"Aux script not found: {src}")
continue
shutil.copy2(src, dst)
os.chmod(dst, 0o755)
logger.info(f"Copied: {script}")
def validate_ilifu_path(path, label="file"):
"""
Validate that a path is on the ilifu filesystem.
Warn if the path is outside expected ilifu mountpoints.
"""
abs_path = os.path.abspath(path)
ilifu_mounts = ['/idia/', '/users/', '/scratch/', '/home/']
on_ilifu_fs = any(abs_path.startswith(m) for m in ilifu_mounts)
if not on_ilifu_fs:
logger.warning(f" -> {label} path '{abs_path}' may not be on ilifu filesystem.")
logger.warning(" Expected location like /idia/projects/... or /users/...")
def link_into_workdir(src_path, workdir, label="file"):
"""
Ensure src_path is accessible by basename inside workdir.
Returns the basename to use in the config.
Pipeline scripts (run_parallel_rmsy.py / create_subimage.py) embed the input
filename into chunk filenames (e.g. processing/part_1_<input>.im). If the
user passes '../foo.fits' or an absolute path, that breaks. We sidestep this
by symlinking the real file into workdir under its basename, and storing only
the basename in the config. The pipeline then sees a simple local filename
while the user keeps their data wherever it actually lives.
"""
src_abs = os.path.abspath(src_path)
basename = os.path.basename(src_abs)
dst = os.path.join(workdir, basename)
if os.path.abspath(dst) == src_abs:
# Already in workdir — nothing to do
return basename
if os.path.lexists(dst):
# Existing entry. If it's a symlink to the same target, fine; otherwise warn.
try:
if os.path.islink(dst) and os.readlink(dst) == src_abs:
logger.info(f" -> {label}: existing symlink already points to {src_abs}")
return basename
except OSError:
pass
logger.warning(f" -> {label}: '{dst}' already exists and is not our symlink; using it as-is")
return basename
os.symlink(src_abs, dst)
logger.info(f" -> {label}: linked {dst} -> {src_abs}")
return basename
def build_config_from_args(args, workdir):
"""
BUILD mode: write a config file from -F / -f / etc. and exit.
No symlinks are created, no pipeline scripts are copied, no
submit_pipeline.sh is generated. The config records ABSOLUTE paths
to the input files; the RUN mode (-R) is what materialises symlinks
and scaffolding when the user is ready to actually launch.
Returns the path to the new config file.
"""
if not args.freqlist:
logger.error("-f/--freqlist is required when using -F/--fitsfile")
sys.exit(1)
if not os.path.exists(args.freqlist):
logger.error(f"Frequency list not found: {args.freqlist}")
sys.exit(1)
validate_ilifu_path(args.freqlist, label="freqlist")
# -F must be a single full-Stokes IQUV cube. Q/U-only inputs are not accepted.
fits_files = args.fitsfile.split()
if len(fits_files) != 1:
logger.error(
"-F expects exactly one path: a full-Stokes IQUV radio-continuum cube. "
f"Got {len(fits_files)} entries. Q/U-only inputs are no longer supported."
)
sys.exit(1)
fits_full = os.path.abspath(fits_files[0])
if not os.path.exists(fits_full):
logger.error(f"FITS file not found: {fits_full}")
sys.exit(1)
validate_ilifu_path(fits_full, label="fits_full")
freqlist = os.path.abspath(args.freqlist)
# ---- Cube structure + freqlist validation (BUILD-time) ----
# Runs inside the rm-env container (where astropy lives). If the container
# isn't built yet we defer to RUN, which uses the same container.
primary_cube = fits_full
rm_container_path = _resolve_rm_container_path(args)
cube_info = None
try:
cube_info = cube_validator.validate_freqlist_against_cube(primary_cube, freqlist)
except cube_validator.CubeStructureError as e:
msg = str(e)
if 'astropy is required' in msg:
try:
cube_info = _validate_cube_via_container(
rm_container_path, primary_cube, freqlist
)
except FileNotFoundError as fe:
logger.warning(f" -> skipping BUILD-time cube validation: container "
f"not found at {fe}. Run setup.sh to fetch it. "
f"RUN will validate.")
except _LoginNodeUnsupported as e:
logger.warning(f" -> skipping BUILD-time cube validation: {e}")
except RuntimeError as re_err:
logger.warning(f" -> cube validation failed inside the container: "
f"{re_err}. RUN will retry.")
except cube_validator.CubeStructureError as ce:
logger.error(str(ce))
sys.exit(1)
else:
logger.error(msg)
sys.exit(1)
if cube_info:
logger.info(
f"cube structure OK: NAXIS={cube_info['naxis']}, "
f"FREQ on axis {cube_info['freq_axis']} ({cube_info['freq_nchans']} chans), "
f"STOKES on axis {cube_info['stokes_axis']}, freqlist lines={cube_info['freqlist_lines']}"
)
if cube_info['needs_transpose']:
logger.warning(
" -> axes are (RA, DEC, STOKES, FREQ). RUN mode will auto-transpose "
"the (symlinked) cube to (RA, DEC, FREQ, STOKES) before chunking. "
"The original file on /idia/ or /users/ is NOT modified."
)
# ---- Region file: parse + preview if provided ----
# World-coord regions need astropy's WCS to convert RA/Dec to pixels, so
# the parse runs inside the container.
region_file_abs = ''
if args.region_file:
region_file_abs = os.path.abspath(args.region_file)
if not os.path.exists(region_file_abs):
logger.error(f"Region file not found: {region_file_abs}")
sys.exit(1)
validate_ilifu_path(region_file_abs, label="region_file")
wcs_header = None
try:
from astropy.io import fits as _fits
wcs_header = _fits.getheader(primary_cube)
except Exception:
pass
regions = None
try:
regions = region_parser.parse_region_file(region_file_abs, wcs_header)
except region_parser.RegionParseError as e:
if 'no cube WCS was supplied' in str(e):
try:
regions = _parse_region_via_container(
rm_container_path, region_file_abs, primary_cube
)
except FileNotFoundError as fe:
logger.warning(f" -> skipping BUILD-time region preview: container "
f"not found at {fe}. RUN will parse.")
except _LoginNodeUnsupported as e:
logger.warning(f" -> skipping BUILD-time region preview: {e}")
except RuntimeError as re_err:
logger.warning(f" -> region parsing failed inside the container: "
f"{re_err}. RUN will retry.")
else:
logger.error(f"Region file '{region_file_abs}': {e}")
sys.exit(1)
if regions:
logger.info(f"parsed {len(regions)} region(s) from "
f"{os.path.basename(region_file_abs)}:")
for line in region_parser.describe_regions(regions):
logger.info(f" -> {line}")
logger.warning(
" -> region_file overrides [data] crop and pointing in the config."
)
# Copy default config to workdir under user-chosen name (or 'myconfig.txt')
config_name = args.config if args.config else 'myconfig.txt'
if not config_name.endswith('.txt'):
config_name += '.txt'
config_path = os.path.join(workdir, os.path.basename(config_name))
if os.path.exists(config_path):
# Move the existing config to <name>.bck (overwriting any older
# backup) so a fresh BUILD never silently loses the user's last
# set of edits. Restore by `mv myconfig.txt.bck myconfig.txt`.
backup_path = config_path + '.bck'
shutil.move(config_path, backup_path)
logger.warning(f"Existing config backed up to: {backup_path}")
shutil.copy2(DEFAULT_CONFIG, config_path)
logger.info(f"Created config file: {config_path}")
# Use the parsed default config to determine the rm_container fallback,
# then write all updates back via the format-preserving inline updater so
# the per-parameter comments in default_config.txt survive.
taskvals, _ = config_parser.parse_config(config_path)
updates = {
('data', 'fits_full'): f"'{fits_full}'",
('data', 'freqlist'): f"'{freqlist}'",
('data', 'region_file'): f"'{region_file_abs}'",
}
if args.chunks:
updates[('chunking', 'chunks')] = str(args.chunks)
if args.submit:
updates[('slurm', 'submit')] = 'True'
# Resolve rm_container path: --rm-container > current value in config > install default
default_rm_container = os.path.join(SCRIPT_DIR, 'container', 'rm-env.sif')
if args.rm_container_override:
rm_container = os.path.abspath(os.path.expanduser(args.rm_container_override))
else:
existing = (taskvals.get('slurm', {}).get('rm_container') or '').strip()
rm_container = existing or default_rm_container
updates[('slurm', 'rm_container')] = f"'{rm_container}'"
if not os.path.exists(rm_container):
logger.warning(f" -> rm_container path does not exist yet: {rm_container}")
logger.warning(" If you haven't run setup.sh, do so to fetch the container.")
logger.warning(" Or pass --rm-container <path> to point at an existing .sif.")
update_config_inplace(config_path, updates)
# Beam-info heads-up (the config now exists, so the user can act on the
# advice by editing it before running -R). RUN re-checks and refuses to
# submit if this is still in a bad state.
_check_beam_for_sigma(primary_cube, taskvals, config_path, hard=False,
rm_container_path=rm_container_path)
# [CHANGE 2026-06-16]: Geometry preview
# The chunker uses int(NAXIS2 / parallel) which truncates, and the last chunk
# absorbs the remainder. Print that math up front so the user can sanity-check
# before submitting a 100-task array.
_preview_chunk_geometry(args, fits_full, workdir, taskvals)
return config_path
def _check_beam_for_sigma(cube_path, taskvals, config_path, hard,
rm_container_path=None, account=None):
"""Verify that the cube has the beam metadata PyBDSF needs to build a
noise map, but ONLY when the config asks for sigma cleaning AND no
pre-computed noise map is supplied.
Reads the live [rmclean] threshold and [noise] noise_map from ``taskvals``
so the check reflects whatever the user has (or hasn't) edited in the
config. Returns True if it's safe to proceed.
``hard=False`` (BUILD): on failure, log a WARN block and return False.
The config has just been created, so the user can act on the advice
by editing it before they run ``-R``.
``hard=True`` (RUN): on failure, log an ERROR block and ``sys.exit(1)``.
We're about to submit SLURM jobs that would crash inside the noise stage.
"""
try:
cfg_threshold = float(taskvals.get('rmclean', {}).get('threshold', -5))
except (TypeError, ValueError):
cfg_threshold = -5.0
cfg_noise_map = (taskvals.get('noise', {}).get('noise_map') or '').strip()
if cfg_threshold >= 0 or cfg_noise_map:
return True # absolute mode, or user supplied their own noise map -> no PyBDSF needed
try:
beam = cube_validator.has_beam_info(cube_path)
except ImportError:
# Beam check runs inside the container (where astropy lives).
if rm_container_path is None:
beam = None
else:
try:
beam = _has_beam_info_via_container(rm_container_path, cube_path,
account=account)
except _LoginNodeUnsupported as e:
if not hard:
logger.warning(f" -> skipping BUILD-time beam-info check: {e}")
return True
raise
except (FileNotFoundError, RuntimeError) as e:
if not hard:
logger.warning(f" -> skipping BUILD-time beam-info check: "
f"container check failed ({e}). RUN will "
f"validate before submitting any jobs.")
return True
raise
if beam is not None:
logger.info(f"beam info OK ({beam}); sigma cleaning will use a PyBDSF noise map.")
return True
log = logger.error if hard else logger.warning
title = ("REFUSING TO RUN: sigma cleaning requested but cube has no beam metadata"
if hard else
"Heads-up: the default sigma cleaning won't work for this cube")
log("=" * 60)
log(title)
log("=" * 60)
log(f" cube: {cube_path}")
log(f" threshold: {cfg_threshold} (negative => N-sigma per pixel)")
log("")
log("PyBDSF (used to build the noise map) needs either:")
log(" - BMAJ/BMIN/BPA in the primary FITS header, or")
log(" - a CASA-style BEAMS table HDU (per-channel beam parameters)")
log("Neither was found in your cube.")
log("")
log(f"Edit {config_path}, pick one, then continue:")
log(" 1. Switch to an absolute cutoff:")
log(" [rmclean] threshold = 0.0000010 # positive = Jy/beam/RMSF")
log(" 2. Pre-compute a 2D noise map yourself and point at it:")
log(" [noise] noise_map = '/path/to/noise_map.fits'")
log(" 3. Re-image the cube so it retains beam metadata, then re-build.")
if hard:
log("")
sys.exit(1)
return False
def _preview_chunk_geometry(args, fits_full, workdir, taskvals):
"""Read NAXIS2 from the input cube and log how it will be split.
Runs the read inside the rm-env container so the preview works on the
login node too.
"""
if not fits_full or not os.path.exists(fits_full):
return
naxis2 = None
try:
from astropy.io import fits
naxis2 = int(fits.getheader(fits_full)['NAXIS2'])
except Exception:
try:
naxis2 = _naxis2_via_container(_resolve_rm_container_path(args), fits_full)
except (FileNotFoundError, RuntimeError):
return # silently skip if neither path works -- chunk preview is non-essential
parallel = int(taskvals.get('chunking', {}).get('parallel', 100))
chunks = int(args.chunks) if args.chunks else \
int(taskvals.get('chunking', {}).get('chunks', parallel))
y_size = naxis2 // parallel
residual = naxis2 - parallel * y_size
last_size = y_size + residual
logger.info(
f"chunk geometry: NAXIS2={naxis2}, parallel={parallel}, "
f"y_size={y_size}px, last chunk={last_size}px (residual={residual}px absorbed)"
)
if chunks < parallel:
logger.warning(
f" -> chunks ({chunks}) < parallel ({parallel}): only {chunks} tasks will run, "
f"covering {chunks * y_size} of {naxis2} rows. Outputs may be incomplete."
)
_SINGLE_CUBE_BODY = r"""
# ---- SINGLE-CUBE FLOW (no region file in config) ----
BASENAME=$(basename "$FITS_FULL" .fits)
FITS_Q="${BASENAME}.stokesQ.fits"
FITS_U="${BASENAME}.stokesU.fits"
FITS_I="${BASENAME}.stokesI.fits"
# Stage 1: Extract Stokes I, Q, U from the full IQUV cube (gated by [run] stages='extract')
if has_stage extract; then
if [ "$RESUME" = "True" ] && [ -f "$FITS_Q" ] && [ -f "$FITS_U" ] && [ -f "$FITS_I" ]; then
echo "[Stage 1] SKIP — Stokes Q/U/I already extracted."
else
echo "[Stage 1] Extracting Stokes I/Q/U from full IQUV cube..."
singularity --quiet exec "$RM_CONTAINER" python3 ./create_subimage.py --inputcube "$FITS_FULL"
echo " -> Created: $FITS_Q"
echo " -> Created: $FITS_U"
echo " -> Created: $FITS_I"
fi
else
echo "[Stage 1] Skipping extract ([run] stages=$STAGES)"
fi
# Stage 1.5: Per-pixel noise map (PyBDSF on Stokes I).
# Skip when [rmclean] threshold is positive (absolute mode) or when the user
# supplied a pre-computed noise map in [noise] noise_map.
# Also gated by 'extract' stage membership (the noise map is part of the
# input-preparation stage from the pipeline's perspective).
NOISE_MAP="noise_map.fits"
SLURMID_NOISE=""
if ! has_stage extract; then
echo "[Stage 1.5] Skipping noise map ([run] stages=$STAGES)"
elif [ -n "$NOISE_MAP_CFG" ]; then
echo "[Stage 1.5] Using pre-supplied noise map from config: $NOISE_MAP_CFG"
NOISE_MAP="$NOISE_MAP_CFG"
elif awk "BEGIN{exit !($THRESHOLD < 0)}"; then
if [ "$RESUME" = "True" ] && [ -f "$NOISE_MAP" ]; then
# Re-run: noise map from a previous submission is still on disk.
echo "[Stage 1.5] $NOISE_MAP already exists -- skipping noise generation."
else
echo "[Stage 1.5] Submitting make_noise.sbatch (sigma mode, threshold=$THRESHOLD)..."
cat > make_noise.sbatch <<NOISEEOF
#!/bin/bash
#SBATCH --nodes=${NODES}
#SBATCH --ntasks-per-node=${NTASKS_PER_NODE}
#SBATCH --cpus-per-task=${CPUS_PER_TASK}
#SBATCH --mem=${MEM_NOISE}GB
#SBATCH --job-name=noise
#SBATCH --output=logs/noise-%j.out
#SBATCH --error=logs/noise-%j.err
#SBATCH --partition=${PARTITION}
#SBATCH --time=${TIME}
#SBATCH --account=$ACCOUNT
set -e
export PYTHONDONTWRITEBYTECODE=1
cd "$WORKDIR"