Skip to content

events

  • Define events over a bcm (or bcm-like) dataframe via a boolean mask created with the helper build_mask or your own custom mask. Extract contiguous time intervals per binary/star where the mask holds and select summary statistics to report on columns of interest during the events with get_events. Include key information about binary interaction (whether underwent RLOF/CEE/No interaction before/during event, what stages (kstars) accreted or donated at, whether merged and what merger_type was) using include_interaction_info=True (requires the bpp).

eventlab.events

Define an event of interest, and generate a catalog of the event from a COSMIC bcm/bpp including useful, user-specified, properties of the event-hosting-binary before and during the event.

build_mask(events, mask_list, mask_logic='and')

Combine the list of (column, op, val) conditions in mask_list into a single boolean mask over events, using exact column names, according to the specified logic mask_logic.

Parameters:

Name Type Description Default
events DataFrame

The dataframe to build the mask over (typically the COSMIC bcm with sufficient time resolution, but any dataframe with the referenced columns works in principle).

required
mask_list list of tuple

Each tuple is of the form (column, op, value) where op is one of 'greater', 'less', 'greater_equal', 'less_equal', 'equal', 'not_equal'.

required
mask_logic str

'and' or 'or' -- how to combine the individual conditions. Default is 'and'.

'and'

Returns:

Name Type Description
mask ndarray

Boolean array the same length as events.

Examples:

>>> rsg_mask_1 = build_mask(bcm,
...                         [('lum_1', 'greater_equal', 1e4),
...                          ('lum_1', 'less_equal', 6e5),
...                          ('teff_1', 'greater_equal', 2900),
...                          ('teff_1', 'less_equal', 4500)],
...                         mask_logic='and')
>>> rsg_mask_2 = build_mask(bcm,
...                         [('lum_2', 'greater_equal', 1e4),
...                          ('lum_2', 'less_equal', 6e5),
...                          ('teff_2', 'greater_equal', 2900),
...                          ('teff_2', 'less_equal', 4500)],
...                         mask_logic='and')
>>> rsg_mask = rsg_mask_1 | rsg_mask_2
>>> mass_transfer_mask = build_mask(bcm,
...                                 [('RRLO_1', 'greater', 1),
...                                  ('RRLO_2', 'greater', 1)],
...                                 mask_logic='or')
Source code in src/eventlab/events.py
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
def build_mask(events, mask_list, mask_logic='and'):
    """
    Combine the list of (`column`, `op`, `val`) conditions in `mask_list` into a single boolean
    mask over `events`, using exact column names, according to the specified logic `mask_logic`.

    Parameters
    ----------
    events : pandas.DataFrame
        The dataframe to build the mask over (typically the COSMIC ``bcm`` with 
        sufficient time resolution, but any dataframe with the referenced columns
        works in principle).
    mask_list : list of tuple
        Each tuple is of the form ``(column, op, value)`` where ``op`` is
        one of ``'greater'``, ``'less'``, ``'greater_equal'``,
        ``'less_equal'``, ``'equal'``, ``'not_equal'``.
    mask_logic : str, optional
        ``'and'`` or ``'or'`` -- how to combine the individual conditions.
        Default is ``'and'``.

    Returns
    -------
    mask : numpy.ndarray
        Boolean array the same length as ``events``.

    Examples
    --------
    >>> rsg_mask_1 = build_mask(bcm,
    ...                         [('lum_1', 'greater_equal', 1e4),
    ...                          ('lum_1', 'less_equal', 6e5),
    ...                          ('teff_1', 'greater_equal', 2900),
    ...                          ('teff_1', 'less_equal', 4500)],
    ...                         mask_logic='and')
    >>> rsg_mask_2 = build_mask(bcm,
    ...                         [('lum_2', 'greater_equal', 1e4),
    ...                          ('lum_2', 'less_equal', 6e5),
    ...                          ('teff_2', 'greater_equal', 2900),
    ...                          ('teff_2', 'less_equal', 4500)],
    ...                         mask_logic='and')
    >>> rsg_mask = rsg_mask_1 | rsg_mask_2
    >>> mass_transfer_mask = build_mask(bcm,
    ...                                 [('RRLO_1', 'greater', 1),
    ...                                  ('RRLO_2', 'greater', 1)],
    ...                                 mask_logic='or')
    """
    if mask_logic not in ('and', 'or'):
        raise ValueError("mask_logic must be 'and' or 'or'")

    if not mask_list:
        raise ValueError("mask_list must contain at least one (column, op, value) tuple")

    mask = np.ones(len(events), dtype=bool) if mask_logic == 'and' else np.zeros(len(events), dtype=bool)

    for mask_piece in mask_list:
        if len(mask_piece) != 3:
            raise ValueError(f"Each mask piece must be a tuple of (column, op, value), got {mask_piece}")

        col, op, val = mask_piece

        if col not in events.columns:
            raise KeyError(f"Column '{col}' not found in events dataframe")

        if op not in VALID_OPS:
            raise ValueError(f"Unsupported operation '{op}'. Must be one of {VALID_OPS}")

        if op == 'greater':
            cond = events[col] > val
        elif op == 'less':
            cond = events[col] < val
        elif op == 'greater_equal':
            cond = events[col] >= val
        elif op == 'less_equal':
            cond = events[col] <= val
        elif op == 'equal':
            cond = events[col] == val
        elif op == 'not_equal':
            cond = events[col] != val
        else:
            raise ValueError(f'Unsupported operation: {op}')

        mask = (mask & cond) if mask_logic == 'and' else (mask | cond)

    return np.asarray(mask)

get_events(bcm, mask, stats_dict=None, include_interaction_info=False, bpp=None)

Generate an event catalog: one row per contiguous interval where mask holds (event may be instantaneous like CCSNe without issue), for each binary in bcm.

Parameters:

Name Type Description Default
bcm DataFrame

The COSMIC bcm table (or a similar dataframe with bin_num and tphys columns) to extract intervals from.

required
mask ndarray

Boolean array, same length as bcm, defining which rows count as "in the event." Build with :func:build_mask or construct by hand for arbitrary custom logic.

required
stats_dict dict

Dictionary of {column: [stat, ...]} specifying summary statistics to compute over each interval, e.g. {'teff_1': ['min', 'max'], 'lum_2': ['mean'], 'rad_2': ['median'], 'sep': ['first', 'last']}. Columns can be any column in bcm, independent of what was used to build mask. Stat options are 'max', 'min', 'median', 'mean', 'first', 'last'.

None
include_interaction_info bool

If True, augment each interval with pre-/during-event interaction and merger history. Requires bpp to be provided. Default is False. Adds the following columns:

  • pre_event_interactions: interaction type before the event -- 'None | 'RLOF' | 'CEE' (CEE takes precedence over RLOF if both occurred).
  • during_event_interactions: interaction type during the event -- 'None' | 'RLOF' | 'CEE' (CEE takes precedence over RLOF if both occurred).
  • pre_event_merger: True if a merger occurred before the event.
  • during_event_merger: True if a merger occurred during the event (False if pre_event_merger is True).
  • pre_event_merger_type: the merger_type value if merged pre-event, else 'None'.
  • during_event_merger_type: the merger_type value if merged during the event, else 'None' (always 'None' if pre_event_merger is True).
  • pre_event_donor_kstars_*: string of each kstar value at which the star (1 or 2) donated to its companion. Potential values include '' (star * did not donate), '1' (star * donated only on the MS) or longer '1-3-5' (mass transfer continued as star * was in all 3 phases).
  • pre_event_accretor_kstars_*: same as pre_event_donor_kstars_*, but the types of star * as it accreted from a companion.
  • during_event_donor_kstars_*: same as pre_event_donor_kstars_*, but for the event window.
  • during_event_accretor_kstars_*: same as pre_event_accretor_kstars_*, but for the event window.
False
bpp DataFrame

The COSMIC bpp dataframe. Required if include_interaction_info is True (needed to evaluate MT stability); ignored otherwise.

None

Returns:

Name Type Description
event_df DataFrame

One row per contiguous interval, sorted by bin_num and tphys_start, with columns:

  • bin_num: the binary's identifier
  • tphys_start: time the interval begins
  • tphys_end: time the interval ends
  • duration: tphys_end - tphys_start
  • any <column>_<stat> columns requested via stats_dict
  • if include_interaction_info=True, the additional columns documented above.

Examples:

>>> mask_1 = build_mask(bcm, [('kstar_1', 'equal', 7),
...                           ('mass_1', 'greater_equal', 2),
...                           ('mass_1', 'less_equal', 8)])
>>> mask_2 = build_mask(bcm, [('kstar_2', 'equal', 7),
...                           ('mass_2', 'greater_equal', 2),
...                           ('mass_2', 'less_equal', 8)])
>>> event_df_1 = get_events(bcm,
...                         mask_1,
...                         stats_dict={'teff_1': ['min', 'max'], 'lum_1': ['mean', 'median'], 'sep': ['first', 'last']},
...                         include_interaction_info=True,
...                         bpp=bpp)
>>> event_df_2 = get_events(bcm,
...                         mask_2,
...                         stats_dict={'teff_2': ['min', 'max'], 'lum_2': ['mean', 'median'], 'sep': ['first', 'last']},
...                         include_interaction_info=True,
...                         bpp=bpp)
>>> event_df_1['star'] = 1
>>> event_df_2['star'] = 2
>>> event_df = pd.merge(event_df_1, event_df_2, how='outer').sort_values(['bin_num', 'tphys_start']).reset_index(drop=True)
Source code in src/eventlab/events.py
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
def get_events(bcm,
               mask,
               stats_dict=None,
               include_interaction_info=False,
               bpp=None):
    """
    Generate an event catalog: one row per contiguous interval where
    ``mask`` holds (event may be instantaneous like CCSNe without issue), for each binary in ``bcm``.

    Parameters
    ----------
    bcm : pandas.DataFrame
        The COSMIC ``bcm`` table (or a similar dataframe with ``bin_num`` and
        ``tphys`` columns) to extract intervals from.
    mask : numpy.ndarray
        Boolean array, same length as ``bcm``, defining which rows count
        as "in the event." Build with :func:`build_mask` or construct by
        hand for arbitrary custom logic.
    stats_dict : dict, optional
        Dictionary of ``{column: [stat, ...]}`` specifying summary
        statistics to compute over each interval, e.g.
        ``{'teff_1': ['min', 'max'], 'lum_2': ['mean'], 'rad_2': ['median'], 'sep': ['first', 'last']}``.
        Columns can be any column in ``bcm``, independent of what was used
        to build ``mask``. Stat options are ``'max'``, ``'min'``,
        ``'median'``, ``'mean'``, ``'first'``, ``'last'``.
    include_interaction_info : bool, optional
        If True, augment each interval with pre-/during-event interaction
        and merger history. Requires ``bpp`` to be provided. Default is
        False. Adds the following columns:

        - ``pre_event_interactions``: interaction type before the event
          -- 'None | 'RLOF' | 'CEE' (CEE takes precedence over RLOF if both occurred).
        - ``during_event_interactions``: interaction type during the event
          -- 'None' | 'RLOF' | 'CEE' (CEE takes precedence over RLOF if both occurred).
        - ``pre_event_merger``: True if a merger occurred before the event.
        - ``during_event_merger``: True if a merger occurred during the
          event (False if ``pre_event_merger`` is True).
        - ``pre_event_merger_type``: the ``merger_type`` value if merged
          pre-event, else 'None'.
        - ``during_event_merger_type``: the ``merger_type`` value if
          merged during the event, else 'None' (always 'None' if
          ``pre_event_merger`` is True).
        - ``pre_event_donor_kstars_*``: string of each kstar value at which the
          star (1 or 2) donated to its companion. Potential values include '' (star * did not donate),
          '1' (star * donated only on the MS) or longer '1-3-5' (mass transfer continued as star * was in all 3 phases).
        - ``pre_event_accretor_kstars_*``: same as ``pre_event_donor_kstars_*``, but the types of star * as it accreted from a companion.
        - ``during_event_donor_kstars_*``: same as ``pre_event_donor_kstars_*``, but for the event window.
        - ``during_event_accretor_kstars_*``: same as ``pre_event_accretor_kstars_*``, but for the event window.
    bpp : pandas.DataFrame, optional
        The COSMIC ``bpp`` dataframe. Required if ``include_interaction_info``
        is True (needed to evaluate MT stability); ignored otherwise.

    Returns
    -------
    event_df : pandas.DataFrame
        One row per contiguous interval, sorted by ``bin_num`` and
        ``tphys_start``, with columns:

        - ``bin_num``: the binary's identifier
        - ``tphys_start``: time the interval begins
        - ``tphys_end``: time the interval ends
        - ``duration``: ``tphys_end - tphys_start``
        - any ``<column>_<stat>`` columns requested via ``stats_dict``
        - if ``include_interaction_info=True``, the additional columns
          documented above.

    Examples
    --------
    >>> mask_1 = build_mask(bcm, [('kstar_1', 'equal', 7),
    ...                           ('mass_1', 'greater_equal', 2),
    ...                           ('mass_1', 'less_equal', 8)])
    >>> mask_2 = build_mask(bcm, [('kstar_2', 'equal', 7),
    ...                           ('mass_2', 'greater_equal', 2),
    ...                           ('mass_2', 'less_equal', 8)])
    >>> event_df_1 = get_events(bcm,
    ...                         mask_1,
    ...                         stats_dict={'teff_1': ['min', 'max'], 'lum_1': ['mean', 'median'], 'sep': ['first', 'last']},
    ...                         include_interaction_info=True,
    ...                         bpp=bpp)
    >>> event_df_2 = get_events(bcm,
    ...                         mask_2,
    ...                         stats_dict={'teff_2': ['min', 'max'], 'lum_2': ['mean', 'median'], 'sep': ['first', 'last']},
    ...                         include_interaction_info=True,
    ...                         bpp=bpp)
    >>> event_df_1['star'] = 1
    >>> event_df_2['star'] = 2
    >>> event_df = pd.merge(event_df_1, event_df_2, how='outer').sort_values(['bin_num', 'tphys_start']).reset_index(drop=True)
    """

    records = []
    if mask is not None:
        records.extend(_collect_intervals(
            bcm, mask, stats_dict=stats_dict,
        ))

    base_cols = ['bin_num', 'tphys_start', 'tphys_end', 'duration']
    if not records:
        return pd.DataFrame(columns=base_cols)

    df = pd.DataFrame(records)
    other_cols = sorted(c for c in df.columns if c not in base_cols)
    df = df[base_cols + other_cols]
    df = df.sort_values(['bin_num', 'tphys_start']).reset_index(drop=True)

    if include_interaction_info:
        if bpp is None:
            raise ValueError("bpp must be provided if include_interaction_info is True")
        df = _add_interaction_info(df, bpp, bcm)

    return df