class cosmic.output.COSMICOutput(bpp=None, bcm=None, initC=None, kick_info=None, file=None, label=None, file_key_suffix='')[source]

Bases: object

Container for COSMIC output data components.

Can be initialized either from data components directly or by loading from an HDF5 file.

Parameters:
bpppandas.DataFrame, optional

Important evolution timestep table, by default None

bcmpandas.DataFrame, optional

User-defined timestep table, by default None

initCpandas.DataFrame, optional

Initial conditions table, by default None

kick_infopandas.DataFrame, optional

Natal kick information table, by default None

filestr, optional

Filename/path to HDF5 file to load data from, by default None

labelstr, optional

Optional label for the output instance, by default None

file_key_suffixstr, optional

Suffix to append to dataset keys when loading from file, by default ‘’. E.g. if set to ‘_singles’, datasets ‘bpp_singles’, ‘bcm_singles’, etc. will be loaded as bpp, bcm, etc.

Raises:
ValueError

If neither file nor all data components are provided.

property final_bpp[source]

Get the final timestep for each binary from the bpp table.

Returns:
final_bpppandas.DataFrame

DataFrame containing only the final timestep for each binary.

plot_detailed_evolution(bin_num, show=True, **kwargs)[source]

Plot detailed evolution for a specific binary.

Parameters:
bin_numint

Index of the binary to plot.

**kwargs

Additional keyword arguments passed to the plotting function (plotting.plot_binary_evol).

plot_distribution(x_col, y_col=None, c_col=None, when='final', fig=None, ax=None, show=True, xlabel='auto', ylabel='auto', clabel='auto', **kwargs)[source]

Plot distribution of binaries in specified columns.

Plots can be histograms (if only x_col is given) or scatter plots (if both x_col and y_col are given). Optionally, colour coding can be applied using c_col.

Parameters:
x_colstr

Column name for x-axis.

y_colstr, optional

Column name for y-axis. If None, a histogram will be plotted. By default None.

c_colstr, optional

Column name for colour coding. By default None.

whenstr, optional

When to take the values from: ‘initial’ or ‘final’. By default ‘final’.

figmatplotlib.figure.Figure, optional

Figure to plot on. If None, a new figure is created. By default None.

axmatplotlib.axes.Axes, optional

Axes to plot on. If None, new axes are created. By default None.

showbool, optional

If True, display the plot immediately. By default True.

xlabelstr, optional

Label for x-axis. If ‘auto’, uses the column name. By default ‘auto’.

ylabelstr, optional

Label for y-axis. If ‘auto’, uses the column name or ‘Count’ for histogram. By default ‘auto’.

clabelstr, optional

Label for colorbar. If ‘auto’, uses the column name. By default ‘auto

**kwargs

Additional keyword arguments passed to the plotting function.

Returns:
figmatplotlib.figure.Figure

The figure containing the plot.

axmatplotlib.axes.Axes

The axes containing the plot.

rerun_with_settings(new_settings, reset_kicks=False, inplace=False)[source]

Rerun the simulation with new settings.

Parameters:
new_settingsdict

Dictionary of new settings to apply. Any setting not included will retain its original value.

reset_kicksbool, optional

If True, reset natal kicks to be randomly sampled again. If False, retain original kicks. By default False. (You may want to reset the kicks if changing settings that affect remnant masses or kick distribution.)

inplacebool, optional

If True, update the current instance. If False, return a new instance. By default False.

Returns:
new_outputCOSMICOutput

New COSMICOutput instance with updated simulation results (only if inplace is False).

save(output_file)[source]

Save all data components to an HDF5 file

Parameters:
output_filestr

Filename/path to the HDF5 file

class cosmic.output.COSMICPopOutput(file, label=None)[source]

Bases: object

to_combined_output()[source]

Combine binaries and singles into a single COSMICOutput instance.

Returns:
combined_outputCOSMICOutput

COSMICOutput instance containing both binaries and singles.

Raises:
ValueError

If singles output is not available.

class cosmic.output.COSMICStroopOutput(bpp, bcm, initC, kick_info, samples, param_names, weights, is_hit, generation, gaussian_idx, num_explored, num_hits, fraction_explored, label=None)[source]

Bases: COSMICOutput

Results from a STROOPWAFEL adaptive importance-sampling run.

Extends COSMICOutput with the sampled parameters, importance weights, hit flags, and STROOPWAFEL bookkeeping arrays.

The link between the numpy arrays and the COSMIC tables is bin_num: samples[bin_num], weights[bin_num], and is_hit[bin_num] all correspond to the row(s) in bpp/bcm/initC/kick_info with that bin_num. Bin numbers are assigned sequentially (0-indexed) across all batches so they can be used directly as array indices.

Parameters:
bpp, bcm, initC, kick_infopandas.DataFrame

COSMIC output tables (concatenated across all batches).

samplesnumpy.ndarray

(N, D) array of sampled parameters in physical space.

param_nameslist of str

Parameter names corresponding to the columns of samples.

weightsnumpy.ndarray

(N,) importance-sampling weights.

is_hitnumpy.ndarray

(N,) boolean array; True where the system satisfied the hit criterion.

generationnumpy.ndarray

(N,) integer array — 0 = exploration phase, 1+ = refinement generation.

gaussian_idxnumpy.ndarray

(N,) integer array — -1 = drawn from prior, k = drawn from Gaussian k.

num_exploredint

Number of systems evolved during the exploration phase.

num_hitsint

Total raw hit count across all phases.

fraction_exploredfloat

Fraction of total systems used for exploration.

labelstr, optional

Human-readable label for the run, by default None

Container for COSMIC output data components.

Can be initialized either from data components directly or by loading from an HDF5 file.

Parameters:
bpppandas.DataFrame, optional

Important evolution timestep table, by default None

bcmpandas.DataFrame, optional

User-defined timestep table, by default None

initCpandas.DataFrame, optional

Initial conditions table, by default None

kick_infopandas.DataFrame, optional

Natal kick information table, by default None

filestr, optional

Filename/path to HDF5 file to load data from, by default None

labelstr, optional

Optional label for the output instance, by default None

file_key_suffixstr, optional

Suffix to append to dataset keys when loading from file, by default ‘’. E.g. if set to ‘_singles’, datasets ‘bpp_singles’, ‘bcm_singles’, etc. will be loaded as bpp, bcm, etc.

Raises:
ValueError

If neither file nor all data components are provided.

draw_representative_sample(n_samples, rng=None)[source]

Draw a representative sample of hits from the explored systems.

Performs a weighted bootstrap: hits are drawn with replacement in proportion to their importance weights, yielding a set of systems distributed according to the true (prior-weighted) population that can be analysed without any further weighting.

Parameters:
n_samplesint

Number of hits to draw.

rngnumpy.random.Generator, optional

Random number generator to use for sampling. If None, a new default generator is created.

Returns:
representative_samplenumpy.ndarray

Array of shape (n_samples, D) containing the drawn samples in physical space.

bin_numsnumpy.ndarray

Array of shape (n_samples,) containing the corresponding bin numbers, so the full evolution history of each drawn system can be recovered from the bpp/bcm/initC/kick_info tables (e.g. self.initC.loc[bin_num]).

classmethod from_file(path, label=None)[source]

Load from an HDF5 file written by save().

Parameters:
pathstr

File path to read.

labelstr, optional

Override the stored label, by default None

Returns:
COSMICStroopOutput
property hit_rate[source]

Importance-weighted hit rate: sum(w[is_hit]) / N.

Returns:
float
property hit_rate_uncertainty[source]

Standard error on the importance-weighted hit rate.

Returns std(w[is_hit], ddof=1) / sqrt(N), or 0.0 if fewer than two hits are present.

Returns:
float
save(output_file)[source]

Save to an HDF5 file.

Writes COSMIC tables via the parent save, then appends STROOPWAFEL arrays to a stroopwafel/ group.

Parameters:
output_filestr

Filename/path to create or overwrite.

class cosmic.output.STROOPWAFELCheckpoint(config, mixture, samples, is_hit, generation, gaussian_idx, bpp, bcm, initC, kick_info, num_explored, num_hits, num_hits_exploratory, fraction_explored, prior_fraction_rejected)[source]

Bases: object

Serialisable snapshot of AdaptiveSampler state after exploration.

Saving this to disk decouples the exploration + adaptation phases from the (typically more expensive) refinement phase, which is the key enabler for multi-job SLURM workflows:

# Job 1 - exploration (embarrassingly parallel within the job)
python run_explore.py          # writes  checkpoint.h5

# Job 2 - refinement (can be a larger allocation)
python run_refine.py           # reads checkpoint.h5, writes result.h5

A checkpoint is self-contained: alongside the exploration data it stores everything needed to rebuild the sampler — the parameter space, BSEDict, the derive_params/reject_systems/is_interesting callables, the remaining scalar settings, and the live RNG state — so AdaptiveSampler.from_checkpoint() needs nothing but the file. The callables and parameter space are serialised with dill.

Parameters:
configdict

Everything needed to reconstruct the AdaptiveSampler for the refinement phase: the constructor keyword arguments (parameter_space, total_systems, batch_size, BSEDict, SSEDict, is_interesting, derive_params, reject_systems, nproc, kappa, n_generations, only_save_hit_tables, min_active_fraction, min_entropy_change) plus the live rng.

mixtureGaussianMixture or None

Gaussian mixture fitted to exploration hits. None if no hits were found or adaptation has not been run yet.

samplesnumpy.ndarray

(N, D) array of explored samples in sampling space (the internal transformed space used by the mixture model). Convert to physical space with param_space.to_physical(samples).

is_hit, generation, gaussian_idxnumpy.ndarray

Per-sample flags and bookkeeping arrays (shapes (N,)).

bpp, bcm, initC, kick_infopandas.DataFrame

COSMIC output from exploration, indexed by globally unique bin_num so that samples[bin_num] gives the corresponding physical parameters.

num_exploredint

Systems evolved during exploration.

num_hitsint

Raw hit count from exploration.

num_hits_exploratoryint

Same as num_hits (stored separately for use in _refine).

fraction_exploredfloat

Adaptive fraction of total budget used for exploration.

prior_fraction_rejectedfloat

Estimated fraction of prior samples that fail physical rejection.

classmethod from_file(path)[source]

Load a checkpoint previously written by save().

Parameters:
pathstr

File path to read.

Returns:
STROOPWAFELCheckpoint
save(path)[source]

Save to an HDF5 file.

Parameters:
pathstr

File path to create or overwrite.

cosmic.output.load_initC(filename, key='initC', settings_key='initC_settings')[source]

Load an initC table from an HDF5 file.

If settings were saved separately, they are merged back into the main table.

Parameters:
filenamestr

Filename/path to the HDF5 file

keystr, optional

Dataset key to use for main table, by default “initC”

settings_keystr, optional

Dataset key to use for settings table, by default “initC_settings”

Returns:
initCpandas.DataFrame

Initial conditions table

cosmic.output.save_initC(filename, initC, key='initC', settings_key='initC_settings', force_save_all=False)[source]

Save an initC table to an HDF5 file.

Any column where every binary has the same value (setting) is saved separately with only a single copy to save space.

This will take slightly longer (a few seconds instead of 1 second) to run but will save you around a kilobyte per binary, which adds up!

Parameters:
filenamestr

Filename/path to the HDF5 file

initCpandas.DataFrame

Initial conditions table

keystr, optional

Dataset key to use for main table, by default “initC”

settings_keystr, optional

Dataset key to use for settings table, by default “initC_settings”

force_save_allbool, optional

If true, force all settings columns to be saved in the main table, by default False