scitex.session API Reference
scitex-session — @session decorator + lifecycle management (standalone).
- scitex.session.start(sys=None, plt=None, file=None, sdir=None, sdir_suffix=None, args=None, os=None, random=None, np=None, torch=None, seed=42, agg=False, fig_size_mm=(160, 100), fig_scale=1.0, dpi_display=100, dpi_save=300, fontsize='small', autolayout=False, show_execution_flow=False, hide_top_right_spines=True, alpha=0.9, line_width=1.0, clear_logs=False, verbose=True)[source]
Initialize experiment session with reproducibility settings.
- Parameters:
sys (module, optional) – Python sys module for I/O redirection
plt (module, optional) – Matplotlib pyplot module for plotting configuration
file (str, optional) – Script file path. If None, automatically detected
sdir (Union[str, Path], optional) – Save directory path
sdir_suffix (str, optional) – Suffix to append to save directory
args (object, optional) – Command line arguments or configuration object
seed (int, default=42) – Random seed for reproducibility
agg (bool, default=False) – Whether to use matplotlib Agg backend
verbose (bool, default=True) – Whether to print detailed information
- Returns:
(CONFIGS, stdout, stderr, plt, COLORS, rng)
- Return type:
- scitex.session.close(CONFIG, message=':)', notify=False, verbose=True, exit_status=None, archive_format=None)[source]
Close experiment session and finalize logging.
- Parameters:
CONFIG (DotDict) – Configuration dictionary from start()
message (str, default=':)') – Completion message
notify (bool, default=False) – Whether to send notification
verbose (bool, default=True) – Whether to print verbose output
exit_status (int, optional) – Exit status code (0=success, 1=error, None=finished)
archive_format (str, optional) – If set (e.g. “tar.gz”), replace the FINISHED dest dir with a single archive file.
None(default) preserves the original copytree-only behavior bit-for-bit.
- scitex.session.running2finished(CONFIG, exit_status=None, remove_src_dir=True, max_wait=60, archive_format=None)[source]
Move session from RUNNING to FINISHED directory.
- Parameters:
CONFIG (dict) – Session configuration dictionary
exit_status (int, optional) – Exit status code (0=success, 1=error, None=finished)
remove_src_dir (bool, default=True) – Whether to remove source directory after copy
max_wait (int, default=60) – Maximum seconds to wait for copy operation
archive_format (str, optional) – If set (e.g. “tar.gz”), replace the FINISHED dest dir with a single archive file (1 inode instead of N).
None(default) preserves the original copytree-only behavior bit-for-bit.
- Returns:
Updated configuration with new SDIR
- Return type:
- scitex.session.session(func=None, *, verbose=False, agg=True, notify=False, sdir_suffix=None, archive_format=None, **session_kwargs)[source]
Decorator to wrap a function in a scitex session.
Automatically handles:
CLI argument parsing from the function signature
Session initialization (logging, output directories)
Execution
Cleanup
Error handling
This decorator is designed for script entry points. The decorated function should be called without arguments from
if __name__ == '__main__':to trigger CLI parsing and session management.- Parameters:
func (callable, optional) – Function to wrap (set automatically by the decorator).
verbose (bool, default False) – Enable verbose logging.
agg (bool, default True) – Use matplotlib’s Agg backend (non-interactive).
notify (bool, default False) – Send notification on completion.
sdir_suffix (str, optional) – Suffix for the output directory name (defaults to function name).
archive_format (str, optional) – If set (e.g.
"tar.gz"), replace FINISHED_SUCCESS/<session>/ with a single archive file (1 inode vs 7).**session_kwargs – Additional session configuration parameters forwarded to
scitex_session.start/scitex_session.close.
- Returns:
The wrapped function; calling it with no arguments triggers CLI parsing + session management. Calling it with arguments bypasses session management entirely and invokes the function directly (useful for in-process tests).
- Return type:
callable
Examples
Bare decorator (auto CLI from signature):
@stx.session def analyze(data_path: str, threshold: float = 0.5): '''Analyze data file.''' data = stx.io.load(data_path) result = process(data, threshold) stx.io.save(result, "output.csv") return 0 if __name__ == '__main__': analyze() # CLI mode with session management # CLI: python script.py --data-path data.csv --threshold 0.7
Decorator with options:
@stx.session(verbose=True, notify=True) def train_model(model_name: str, epochs: int = 10): '''Train ML model.''' # Available as globals: CONFIG, plt, COLORS, rngg, logger. logger.info(f"Session ID: {CONFIG['ID']}") logger.info(f"Output directory: {CONFIG['SDIR_RUN']}") # ... training code ... return 0 if __name__ == '__main__': train_model()
Notes
Function name can be anything (not just
main).Calling with arguments bypasses session management:
analyze('/path', 0.5).Only one session-managed function per script.
Do NOT call multiple
@sessiondecorated functions from one script.Do NOT nest session-decorated function calls without arguments.
When called without arguments (CLI mode), the decorator injects these into the wrapped function’s module globals:
CONFIG(dict): Session configuration with ID, SDIR, paths, etc.plt(module):matplotlib.pyplotconfigured for the session.COLORS(CustomColors): Color palette for consistent plotting.rngg(RandomStateManager): Reproducibility manager; creates named generators viarngg("name").
- scitex.session.run(func, parse_args=None, **session_kwargs)[source]
Run a function with session management — explicit alternative to
@session.- Parameters:
func (callable) – Function to run.
parse_args (callable, optional) – Custom argument parser. If
None, an argparse parser is auto-generated fromfunc’s signature via_create_parser().**session_kwargs – Forwarded to
scitex_session.start/close.
- Return type:
- Returns:
int – Exit status.
0on success; non-zero on failure (also re-raised).Example:: –
- def main(args):
# … your code … return 0
- if __name__ == ‘__main__’:
stx.session.run(main)
- class scitex.session.SessionManager[source]
Bases:
objectManages experiment sessions with tracking and lifecycle management.
- get_active_sessions()[source]
Get all active sessions.
- Returns:
Dictionary of active session information
- Return type:
Dict[str, Any]
- scitex.session.archive_session_dir(src_dir, format='tar.gz', remove_src=True, compresslevel=1)[source]
Compress a single session dir into a single archive file.
Writes to a temp path adjacent to the destination, then atomically renames into place. Only after the archive exists and passes a size sanity check do we delete the source (when
remove_src=True). On any error the source is left untouched.- Returns:
Absolute path to the final archive file.
- Return type:
Path
- scitex.session.restore_session_archive(archive_path, dest_dir=None, remove_archive=False)[source]
Extract a session archive back into a session directory.
Extraction is done into a temp dir adjacent to the final destination and atomically renamed into place. If
remove_archive=Truethe archive file is deleted only after a successful rename.- Returns:
Absolute path to the restored directory.
- Return type:
Path
- scitex.session.archive_existing(root, older_than_days=None, format='tar.gz', pattern=None, dry_run=True, max_dirs=None, track_bytes=False, use_fd=True)[source]
Bulk compress every session-shaped child of
root.- Parameters:
track_bytes (bool, default False) – When True, run a per-candidate
dir_size()(os.walk + getsize per file) so thatbytes_in/bytes_outin the returned summary are populated. Off by default because the size accounting adds a measurable per-session overhead on top of the mandatory tar IO (observed on neurovista 2026-05-25: 80,408 sessions / 47 min wall-clock — the byte stats are a meaningful contributor).use_fd (bool, default True) – Forwarded to
iter_session_candidates. When True andfdis installed, candidate enumeration uses the parallel subprocess path; otherwise the Pythoniterdir+statpath.
- Returns:
Summary {scanned, candidates, archived, skipped, failed, bytes_in, bytes_out}.
bytes_inandbytes_outstay at 0 whentrack_bytesis False.- Return type: