Skip to content

[1/6] Parallel frame generation in generate_observation_sequence - #300

Open
alexisyslau wants to merge 18 commits into
mainfrom
parallel/local-multiprocess
Open

alexisyslau wants to merge 18 commits into
mainfrom
parallel/local-multiprocess

Conversation

@alexisyslau

@alexisyslau alexisyslau commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes and reference any relevant issues (don't forget the #)

Part of #256. Part 1/6 of a stack

PR What Risk Review focus
#300 (this one) generate_observation_sequence can run a visit's PSFs and frames in parallel through a frame_runner, with reproducible per-frame seeds High: changes a public function (needed) everything below
#301 mpi_runtime.py: an MPI frame_runner (manager/worker task queue) Medium: opt-in, new dependency rank roles, error handling
#318 2D scene injection: the disk is convolved once per visit (when injected) via _simulate_disk and added to every satellite spot and science frame (_add_disk) Medium: changes observation.py, needs validation in parallel disk added to every segment when injected, header from each segment's optics (sim_info update)
#319 2D scene injection CPGS: generate_observation_scenario_from_cpgs takes an optional twoD_scene_info for the target star Low: one optional argument whether the reference star never has a disk
#302 CPU allocation helper, two example scripts, example SLURM scripts, the parallel tests Low how to run, how to pick -n
#311 Docs page "How to simulate an observation (serial or parallel)" Low: docs only sizing CPUs, memory and -n; using it in your own script

Merge bottom-up: #300, #301, #318, #319, #302, #311. Reading the docstring in the example scripts (#302) and #311 docs should help reviewing this PR. Output of the runs in various modes can be found in #302 .

Terms

  • Observation scenario: all the visits in one CPGS file (generate_observation_scenario_from_cpgs). Visits run one after another.
  • Visit = observation sequence: one star, one roll angle, one visit_id; one generate_observation_sequence call.
  • Segment: consecutive frames of a visit with the same optics state (DM with or without satellite spots, SATSPOTS flag) and the same detector setup. Up to 4 per visit: satellite spot background, positive, negative, science (which is not the case for time series)
  • Frame: one exposure = its segment's PSF + its own EMCCD noise, saved as one L1 file.

What changes

generate_observation_sequence (and generate_observation_scenario_from_cpgs, which calls it per visit) get two optional arguments:

  • frame_runner(func, args_list): runs a list of independent tasks and returns their results in order. Default None = serial, in this process (same as main). functools.partial(run_parallel, n_jobs=n) uses local worker processes; [2/6] MPI frame_runner setups  #301 adds an MPI one.
  • seed: base seed for the detector noise (see below). Default None = as on main.

A visit now runs in two rounds through frame_runner:

  1. PSF round: sequence_segments gives each segment its own copy of the optics (the caller's optics is no longer changed by add_satspot/remove_satspot, which gets from the latest main), and prepare_frame_tasks runs one _compute_psf task per segment, all at once.
  2. Detector round: every frame of the visit is one _apply_detector task (segment PSF + noise), all at once.

With zindex/zval_m_i (speckle variation, one optics state per frame) there is one round: every frame is a _generate_one_frame task (its own PROPER run + detector). zval_m_i has one row per frame of the whole visit, satellite spot frames first. The time series itself still has to be supplied by the caller. This is not tested as it requires #164 time-series branches

Note: Polarimetry is not parallelised further: the 4 PROPER calls of a POL PSF stay inside get_host_star_psf.

corgisim/parallel_executor.py (new, partly adapted from corgihowfsc): run_parallel with a spawn pool whose workers may start their own processes (PROPER opens its own pool per PSF). spawn, not fork, so workers don't inherit the parent's RNG state.

While the tasks run, it logs progress and memory use (main process, subprocesses, available memory) every minute, and raises a WorkerDiedError with a memory report if a worker dies (e.g. killed for running out of memory, exit code -9), instead of multiprocessing.Pool hanging forever. An optional timeout raises a TimeoutError. It does not check memory before the run (see #311 for sizing).

Seeds

Each frame gets its own seed, derived from the base seed and the frame's position in the visit (frame_seeds, numpy.random.SeedSequence), so the frames are the same with serial, any number of workers, or MPI, and on every rerun. The CPGS function gives each visit its own sub-seed (SeedSequence(seed).spawn). _apply_detector seeds numpy's RNG just for that frame and restores the caller's state afterwards. With seed=None nothing is seeded: serial runs behave as on main; parallel runs are statistically correct but not having the same noise pattern across runs.

Behaviour changes compared with main (please check these - and make sure they are what we want)

  • The caller's optics is not modified by the satellite spot sequence any more (each segment works on a copy); only optics.visit_id and optics.visit_type are still set on it.
  • When saving, each frame's FTIMEUTC is the start of its exposure (t0 + the exposure times of the frames before it) instead of the wall clock, so L1 filenames differ from main. Frames shorter than 0.1 s (e.g. 0 s satellite spot frames in some CPGS files) are spaced by 0.1 s so filenames stay unique. VISITID is written to the primary header.
  • satspot_keywords is now required when satspots_are_present (a ValueError otherwise), since we need satspots in the generate_observing_sequence function

Questions

  • Updating the requirements? now we need mpi4py

Checklist before requesting a review

  • I have verified that test_minimal.py passes and I have added a test there if appropriate.
  • I have verified that the relevant tests pass. (not applicable, its in the top PR)
  • Explain what has been changed in observation.py, and the logic why we setup like this when generate_observation_sequence (emccd vs optics)
  • Explain what I have done to the optics state for sat spots and keywords update
  • Write out the overall structure in here, just explain the new terms and how frame parallelisation work in the plain term (mpi things later)

Checklist before merging

  • I have checked the complete tests pass on that branch (check the Github Actions tab)

Stack created with GitHub Stacks CLI • Give Feedback 💬

Stack created with GitHub Stacks CLI • Give Feedback 💬

@alexisyslau
alexisyslau added this pull request to stack #303 October 15, 2026 17:31
@alexisyslau alexisyslau self-assigned this Oct 15, 2026
@alexisyslau
alexisyslau force-pushed the parallel/local-multiprocess branch 3 times, most recently from f9e9731 to b35b813 Compare October 21, 2026 13:16
@alexisyslau alexisyslau changed the title parallel/local multiprocess [1/4] Parallel frame generation in generate_observation_sequence Oct 22, 2026
@alexisyslau
alexisyslau marked this pull request as ready for review October 22, 2026 16:12
@alexisyslau alexisyslau linked an issue Oct 22, 2026 that may be closed by this pull request
@alexisyslau
alexisyslau requested a review from sfr348 October 22, 2026 19:28
@alexisyslau
alexisyslau force-pushed the parallel/local-multiprocess branch from b35b813 to 89b6925 Compare October 30, 2026 00:00

@sfr348 sfr348 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic looks good, small nomenclature change request.

Comment thread corgisim/observation.py
"""
Split an observation sequence into segments, in the order the frames are taken.

A segment is a consecutive block of frames in one visit that share the same optics

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same back-end optics or front end optics or both?

Comment thread corgisim/observation.py
Comment on lines +201 to +207
- `zindex is None`: the frames of a segment share its optics state. The PSFs are
computed first, one `_compute_psf` task per segment through `frame_runner` (so the
segments' PSFs run in parallel). Every frame task is then only the detector step
(`_apply_detector`).
- `zindex is not None`: every frame has its own optics state, so every frame task is
one PROPER run plus the detector step (`_generate_one_frame`). The rows of `zval_m_i`
follow the frames in sequence order, across all segments.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

small thing but thoughout can you clarify when 'optics state' refers to the backend optics, the front-end optics, or the optics variable that gets passed to proper?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps if you want to clarify that is CorgiOptics, you can just called it that: CorgiOptics

Comment thread corgisim/observation.py
Comment on lines +235 to +246
n_frames_total = sum(segment['n_frames'] for segment in segments)
if zval_m_i is None or len(zval_m_i) != n_frames_total:
raise ValueError(f'zindex is given, so zval_m_i needs one row per frame of the sequence ({n_frames_total} rows, '
'in the order the frames are taken: satellite spot frames, if any, then science frames)')

# Each frame has its own optics state (zval_m_i[i]), so each frame is its own PROPER run
args_list = []
for segment in segments:
for i in range(segment['n_frames']):
keyword_updates = {'zindex': zindex, 'zval_m': zval_m_i[len(args_list)]}
args_list.append((scene, segment['optics'], segment['detector'], segment['exp_time'], full_frame, loc_x, loc_y, keyword_updates, seeds[len(args_list)]))
return _generate_one_frame, args_list

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note for self to come back to

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be in the nested PRs but where do the Zvals come from? If it is from OS11 is there a way to interpolate based on the actual timing between frames? (this doesn't need to be in this PR, just curious of the plan.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is linked #246 (built by Alexis Bidot and I am going to finish this afterwards). Essentially we are taking the zernike coefficient from OS11, interpolate between frames, and try to introduce speckle variations under certain conditions. Hence zindex and zval_m in here, since we have a rough idea on how to introduce speckle variation.

Comment thread corgisim/observation.py
Comment on lines +384 to +385
min_step = timedelta(seconds=0.1)
frame_start = datetime.fromisoformat(simulatedImage_list[0].image_on_detector[1].header['FTIMEUTC'])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be 3s?

@alexisyslau
alexisyslau removed this pull request from stack #303 November 4, 2026 15:35
@alexisyslau
alexisyslau added this pull request to stack #320 November 4, 2026 15:36
@alexisyslau alexisyslau changed the title [1/4] Parallel frame generation in generate_observation_sequence [1/6] Parallel frame generation in generate_observation_sequence Nov 4, 2026

@maxwellmb maxwellmb left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see comments for some requested changes.

Also, how do we approach tests in the stacked PR? I'm surprised not to see any new tests here...

Comment thread corgisim/observation.py
Generate emccd frame on already defined simulated scene.

Args:
sim_scene: output of optics.get_host_star_psf() or inject_point_sources().

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Specifically a SimulatedImage object, right?

Comment thread corgisim/observation.py
satspots_are_present = False, satspots_detector = None, satspots_exptime = None, satspots_number_of_frames = None, satspot_keywords = None,
vistype = 'CGIVST_TDD_OBS', visit_id= '0200001001001001001', save_as_fits= False, output_dir=None, full_frame= False, loc_x=None, loc_y=None):

def _apply_detector(sim_scene, detector, exp_time, full_frame, loc_x, loc_y, seed=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

take away _ everywhere please, not needed.
Do we want to make full_frame, and loc_x and loc_y kwargs?

Comment thread corgisim/observation.py
optics = copy.copy(optics)
optics.optics_keywords = {**optics.optics_keywords, **(keyword_updates or {})}
for name, value in (attr_updates or {}).items():
setattr(optics, name, value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the current init function does a LOT and it makes me worried that just changing an attribute like this might miss something. What you checked to see if we can do this always?

Comment thread corgisim/observation.py
return optics


def _compute_psf(scene, optics):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this name is misleading since it also does the point sources.

Comment thread corgisim/observation.py
Comment on lines +201 to +207
- `zindex is None`: the frames of a segment share its optics state. The PSFs are
computed first, one `_compute_psf` task per segment through `frame_runner` (so the
segments' PSFs run in parallel). Every frame task is then only the detector step
(`_apply_detector`).
- `zindex is not None`: every frame has its own optics state, so every frame task is
one PROPER run plus the detector step (`_generate_one_frame`). The rows of `zval_m_i`
follow the frames in sequence order, across all segments.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps if you want to clarify that is CorgiOptics, you can just called it that: CorgiOptics

Comment thread corgisim/observation.py
exp_time (float): The exposure time for each individual frame in seconds.
n_frames (int): The number of frames to generate in this observation sequence, satellite spots frames not included.
satspots_present (bool): If yes, the sequence will generate 3xsatspots_number_of_frames satellite spots frames
satspots_are_present (bool): If True, the sequence also has 3*satspots_number_of_frames satellite spot frames.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why change this keyword argument? It might break old scripts.

@alexisyslau alexisyslau Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

satspots_present was changed on main in the def ... but not the docstring for some reasons. Here just changing the docstring to reflect the changes.

def generate_observation_sequence ( scene, optics, detector, exp_time, n_frames,
satspots_are_present = False, satspots_detector = None, satspots_exptime = None, satspots_number_of_frames = None, satspot_keywords = None,
vistype = 'CGIVST_TDD_OBS', visit_id= '0200001001001001001', save_as_fits= False, output_dir=None, full_frame= False, loc_x=None, loc_y=None):
"""
Generates a sequence of simulated observations and places them on a detector.
This function orchestrates the simulation of a given astrophysical scene through
the instrument optics and then onto the detector. It first generates the host star's
PSF, then injects any defined off-axis point sources into the simulated scene.
Finally, it uses the detector model to create a detector image, optionally
generating either a sub-array or a full-frame image for each exposure.
Each observation sequence corresponds to a single visit at a specific roll angle.
Args:
scene (corgisim.scene.Scene): The scene object containing information about
the host star and any specified point sources.
optics (corgisim.instrument.CorgiOptics): The optics object defining the
instrument configuration, including the telescope and coronagraph.
detector (corgisim.instrument.CorgiDetector): The detector object defining
the detector characteristics and noise properties.
exp_time (float): The exposure time for each individual frame in seconds.
n_frames (int): The number of frames to generate in this observation sequence, satellite spots frames not included.
satspots_present (bool): If yes, the sequence will generate 3xsatspots_number_of_frames satellite spots frames

Comment thread corgisim/observation.py
# satspot and science frames can have different exposure times
frame_exp_times = [segment['exp_time'] for segment in segments for i in range(segment['n_frames'])]

if save_as_fits:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason we don't want frame saving done by the runner?

@alexisyslau
alexisyslau force-pushed the parallel/local-multiprocess branch from a2292d9 to 26fa18a Compare November 17, 2026 18:14
@alexisyslau
alexisyslau force-pushed the parallel/local-multiprocess branch from 26fa18a to fc6c258 Compare November 19, 2026 14:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

add multiprocessing setup

3 participants