Skip to content

utils.py

This module contains utility functions that are used by the pipeline during the processing of a run.

_get_skyregion_relations(row, coords, ids)

For each sky region row a list is returned that contains the ids of other sky regions that overlap with the row sky region (including itself).

Parameters:

Name Type Description Default
row pd.Series

A row from the dataframe containing all the sky regions of the run. Contains the 'id', 'centre_ra', 'centre_dec' and 'xtr_radius' columns.

required
coords SkyCoord

A SkyCoord holding the coordinates of all sky regions.

required
ids pd.core.indexes.numeric.Int64Index

The sky regions ids that match the coords.

required

Returns:

Type Description
List[int]

A list of other sky regions (including self) that are within the

List[int]

'xtr_radius' of the sky region in the row.

Source code in vast_pipeline/pipeline/utils.py
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
def _get_skyregion_relations(
    row: pd.Series,
    coords: SkyCoord,
    ids: pd.core.indexes.numeric.Int64Index
) -> List[int]:
    '''
    For each sky region row a list is returned that
    contains the ids of other sky regions that overlap
    with the row sky region (including itself).

    Args:
        row:
            A row from the dataframe containing all the sky regions of the run.
            Contains the 'id', 'centre_ra', 'centre_dec' and 'xtr_radius'
            columns.
        coords: A SkyCoord holding the coordinates of all sky regions.
        ids: The sky regions ids that match the coords.

    Returns:
        A list of other sky regions (including self) that are within the
        'xtr_radius' of the sky region in the row.
    '''
    target = SkyCoord(
        row['centre_ra'],
        row['centre_dec'],
        unit=(u.deg, u.deg)
    )

    seps = target.separation(coords)

    # place a slight buffer on the radius to make sure
    # any neighbouring fields are caught
    mask = seps <= row['xtr_radius'] * 1.1 * u.deg

    related_ids = ids[mask].to_list()

    return related_ids

_load_measurements(image, cols, start_id=0, ini_df=False)

Load the measurements for an image from the parquet file.

Parameters:

Name Type Description Default
image Image

The object representing the image for which to load the measurements.

required
cols List[str]

The columns to load.

required
start_id int

The number to start from when setting the source ids (when 'ini_df' is 'True'). Defaults to 0.

0
ini_df bool

Boolean to indicate whether these sources are part of the initial source list creation for association. If 'True' the source ids are reset ready for the first iteration. Defaults to 'False'.

False

Returns:

Type Description
pd.DataFrame

The measurements of the image with some extra values set ready for

pd.DataFrame

association .

Source code in vast_pipeline/pipeline/utils.py
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
def _load_measurements(
    image: Image,
    cols: List[str],
    start_id: int = 0,
    ini_df: bool = False
) -> pd.DataFrame:
    """
    Load the measurements for an image from the parquet file.

    Args:
        image:
            The object representing the image for which to load the
            measurements.
        cols:
            The columns to load.
        start_id:
            The number to start from when setting the source ids (when
            'ini_df' is 'True'). Defaults to 0.
        ini_df:
            Boolean to indicate whether these sources are part of the initial
            source list creation for association. If 'True' the source ids are
            reset ready for the first iteration. Defaults to 'False'.

    Returns:
        The measurements of the image with some extra values set ready for
        association .
    """
    image_centre = SkyCoord(
        image.ra,
        image.dec,
        unit=(u.deg, u.deg)
    )

    df = pd.read_parquet(image.measurements_path, columns=cols)
    df['image'] = image.name
    df['datetime'] = image.datetime
    # these are the first 'sources' if ini_df is True.
    df['source'] = df.index + start_id + 1 if ini_df else -1
    df['ra_source'] = df['ra']
    df['dec_source'] = df['dec']
    df['d2d'] = 0.
    df['dr'] = 0.
    df['related'] = None

    sources_sc = SkyCoord(df['ra'], df['dec'], unit=(u.deg, u.deg))

    seps = sources_sc.separation(image_centre).degree
    df['dist_from_centre'] = seps

    del sources_sc
    del seps

    return df

add_new_many_to_one_relations(row)

This handles the relation information being created from the many_to_one function in advanced association. It is a lot simpler than the one_to_many case as it purely just adds the new relations to the relation column, taking into account if it is already a list of relations or not (i.e. no previous relations).

Parameters:

Name Type Description Default
row pd.Series

The relation information Series from the association dataframe. Only the columns ['related_skyc1', 'new_relations'] are required.

required

Returns:

Type Description
List[int]

The new related field for the source in question, containing the

List[int]

appended ids.

Source code in vast_pipeline/pipeline/utils.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def add_new_many_to_one_relations(row: pd.Series) -> List[int]:
    """
    This handles the relation information being created from the
    many_to_one function in advanced association.
    It is a lot simpler than the one_to_many case as it purely just adds
    the new relations to the relation column, taking into account if it is
    already a list of relations or not (i.e. no previous relations).

    Args:
        row:
            The relation information Series from the association dataframe.
            Only the columns ['related_skyc1', 'new_relations'] are required.

    Returns:
        The new related field for the source in question, containing the
        appended ids.
    """
    out = row['new_relations'].copy()

    if isinstance(row['related_skyc1'], list):
        out += row['related_skyc1'].copy()

    return out

add_new_one_to_many_relations(row, advanced=False, source_ids=None)

This handles the relation information being created from the one_to_many functions in association.

Parameters:

Name Type Description Default
row pd.Series

The relation information Series from the association dataframe. Only the columns ['related_skyc1', 'source_skyc1'] are required for advanced, these are instead called ['related', 'source'] for basic.

required
advanced bool

Whether advanced association is being used which changes the names of the columns involved.

False
source_ids Optional[pd.DataFrame]

A dataframe that contains the other ids to append to related for each original source. +----------------+--------+ | source_skyc1 | 0 | |----------------+--------| | 122 | [5542] | | 254 | [5543] | | 262 | [5544] | | 405 | [5545] | | 656 | [5546] | +----------------+--------+

None

Returns:

Type Description
List[int]

The new related field for the source in question, containing the

List[int]

appended ids.

Source code in vast_pipeline/pipeline/utils.py
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
def add_new_one_to_many_relations(
    row: pd.Series, advanced: bool = False,
    source_ids: Optional[pd.DataFrame] = None
) -> List[int]:
    """
    This handles the relation information being created from the
    one_to_many functions in association.

    Args:
        row:
            The relation information Series from the association dataframe.
            Only the columns ['related_skyc1', 'source_skyc1'] are required
            for advanced, these are instead called ['related', 'source']
            for basic.
        advanced:
            Whether advanced association is being used which changes the names
            of the columns involved.
        source_ids:
            A dataframe that contains the other ids to append to related for
            each original source.
            +----------------+--------+
            |   source_skyc1 | 0      |
            |----------------+--------|
            |            122 | [5542] |
            |            254 | [5543] |
            |            262 | [5544] |
            |            405 | [5545] |
            |            656 | [5546] |
            +----------------+--------+

    Returns:
        The new related field for the source in question, containing the
        appended ids.
    """
    if source_ids is None:
        source_ids = pd.DataFrame()

    related_col = 'related_skyc1' if advanced else 'related'
    source_col = 'source_skyc1' if advanced else 'source'

    # this is the not_original case where the original source id is appended.
    if source_ids.empty:
        if isinstance(row[related_col], list):
            out = row[related_col]
            out.append(row[source_col])
        else:
            out = [row[source_col],]

    else:  # the original case to append all the new ids.
        source_ids = source_ids.loc[row[source_col]].iloc[0]
        if isinstance(row[related_col], list):
            out = row[related_col] + source_ids
        else:
            out = source_ids

    return out

backup_parquets(p_run_path)

Backups up all the existing parquet files in a pipeline run directory. Backups are named with a '.bak' suffix in the pipeline run directory.

Parameters:

Name Type Description Default
p_run_path str

The path of the pipeline run where the parquets are stored.

required

Returns:

Type Description
None

None

Source code in vast_pipeline/pipeline/utils.py
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
def backup_parquets(p_run_path: str) -> None:
    """
    Backups up all the existing parquet files in a pipeline run directory.
    Backups are named with a '.bak' suffix in the pipeline run directory.

    Args:
        p_run_path:
            The path of the pipeline run where the parquets are stored.

    Returns:
        None
    """
    parquets = (
        glob.glob(os.path.join(p_run_path, "*.parquet"))
        # TODO Remove arrow when arrow files are no longer required.
        + glob.glob(os.path.join(p_run_path, "*.arrow")))

    for i in parquets:
        backup_name = i + '.bak'
        if os.path.isfile(backup_name):
            logger.debug(f'Removing old backup file: {backup_name}.')
            os.remove(backup_name)
        shutil.copyfile(i, backup_name)

calc_ave_coord(grp)

Calculates the average coordinate of the grouped by sources dataframe for each unique group, along with defining the image and epoch list for each unique source (group).

Parameters:

Name Type Description Default
grp pd.DataFrame

The current group dataframe (unique source) of the grouped by dataframe being acted upon.

required

Returns:

Type Description
pd.Series

A pandas series containing the average coordinate along with the

pd.Series

image and epoch lists.

Source code in vast_pipeline/pipeline/utils.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
def calc_ave_coord(grp: pd.DataFrame) -> pd.Series:
    """
    Calculates the average coordinate of the grouped by sources dataframe for
    each unique group, along with defining the image and epoch list for each
    unique source (group).

    Args:
        grp: The current group dataframe (unique source) of the grouped by
            dataframe being acted upon.

    Returns:
        A pandas series containing the average coordinate along with the
        image and epoch lists.
    """
    d = {}
    grp = grp.sort_values(by='datetime')
    d['img_list'] = grp['image'].values.tolist()
    d['epoch_list'] = grp['epoch'].values.tolist()
    d['wavg_ra'] = grp['interim_ew'].sum() / grp['weight_ew'].sum()
    d['wavg_dec'] = grp['interim_ns'].sum() / grp['weight_ns'].sum()

    return pd.Series(d)

calculate_m_metric(flux_a, flux_b)

Calculate the m variability metric which is the modulation index between two fluxes. This is proportional to the fractional variability. See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105.

Parameters:

Name Type Description Default
flux_a float

flux value "A".

required
flux_b float

flux value "B".

required

Returns:

Name Type Description
float float

the m metric for flux values "A" and "B".

Source code in vast_pipeline/pipeline/utils.py
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
def calculate_m_metric(flux_a: float, flux_b: float) -> float:
    """Calculate the m variability metric which is the modulation index between two fluxes.
    This is proportional to the fractional variability.
    See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105.

    Args:
        flux_a (float): flux value "A".
        flux_b (float): flux value "B".

    Returns:
        float: the m metric for flux values "A" and "B".
    """
    return 2 * ((flux_a - flux_b) / (flux_a + flux_b))

calculate_measurement_pair_metrics(df)

Generate a DataFrame of measurement pairs and their 2-epoch variability metrics from a DataFrame of measurements. For more information on the variability metrics, see Section 5 of Mooley et al. (2016), DOI: 10.3847/0004-637X/818/2/105.

Parameters:

Name Type Description Default
df pd.DataFrame

Input measurements. Must contain columns: id, source, flux_int, flux_int_err, flux_peak, flux_peak_err, has_siblings.

required

Returns:

Type Description
pd.DataFrame

pd.DataFrame: Measurement pairs and 2-epoch metrics. Will contain columns: source - the source ID id_a, id_b - the measurement IDs flux_int_a, flux_int_b - measurement integrated fluxes in mJy flux_int_err_a, flux_int_err_b - measurement integrated flux errors in mJy flux_peak_a, flux_peak_b - measurement peak fluxes in mJy/beam flux_peak_err_a, flux_peak_err_b - measurement peak flux errors in mJy/beam vs_peak, vs_int - variability t-statistic m_peak, m_int - variability modulation index

Source code in vast_pipeline/pipeline/utils.py
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
def calculate_measurement_pair_metrics(df: pd.DataFrame) -> pd.DataFrame:
    """Generate a DataFrame of measurement pairs and their 2-epoch variability metrics
    from a DataFrame of measurements. For more information on the variability metrics, see
    Section 5 of Mooley et al. (2016), DOI: 10.3847/0004-637X/818/2/105.

    Args:
        df (pd.DataFrame): Input measurements. Must contain columns: id, source, flux_int,
            flux_int_err, flux_peak, flux_peak_err, has_siblings.

    Returns:
        pd.DataFrame: Measurement pairs and 2-epoch metrics. Will contain columns:
            source - the source ID
            id_a, id_b - the measurement IDs
            flux_int_a, flux_int_b - measurement integrated fluxes in mJy
            flux_int_err_a, flux_int_err_b - measurement integrated flux errors in mJy
            flux_peak_a, flux_peak_b - measurement peak fluxes in mJy/beam
            flux_peak_err_a, flux_peak_err_b - measurement peak flux errors in mJy/beam
            vs_peak, vs_int - variability t-statistic
            m_peak, m_int - variability modulation index
    """
    n_cpu = cpu_count() - 1

    """Create a DataFrame containing all measurement ID combinations per source.
    Resultant DataFrame will have a MultiIndex(["source", RangeIndex]) where "source" is
    the source ID and RangeIndex is an unnamed temporary ID for each measurement pair,
    unique only together with source.
    DataFrame will have columns [0, 1], each containing a measurement ID. e.g.
                       0      1
        source
        1       0      1   9284
                1      1  17597
                2      1  26984
                3   9284  17597
                4   9284  26984
        ...          ...    ...
        11105   2  11845  19961
        11124   0   3573  12929
                1   3573  21994
                2  12929  21994
        11128   0   6216  23534
    """
    measurement_combinations = (
        dd.from_pandas(df, n_cpu)
        .groupby("source")["id"]
        .apply(
            lambda x: pd.DataFrame(list(combinations(x, 2))
        ), meta={0: "i", 1: "i"},)
        .compute(num_workers=n_cpu, scheduler="processes")
    )

    """Drop the RangeIndex from the MultiIndex as it isn't required and rename the columns.
    Example resultant DataFrame:
               source   id_a   id_b
        0           1      1   9284
        1           1      1  17597
        2           1      1  26984
        3           1   9284  17597
        4           1   9284  26984
        ...       ...    ...    ...
        33640   11105  11845  19961
        33641   11124   3573  12929
        33642   11124   3573  21994
        33643   11124  12929  21994
        33644   11128   6216  23534
    Where source is the source ID, id_a and id_b are measurement IDs.
    """
    measurement_combinations = measurement_combinations.reset_index(
        level=1, drop=True
    ).rename(columns={0: "id_a", 1: "id_b"}).astype(int).reset_index()

    # Dask has a tendency to swap which order the measurement pairs are
    # defined in, even if the dataframe is pre-sorted. We want the pairs to be
    # in date order (a < b) so the code below corrects any that are not.
    measurement_combinations = measurement_combinations.join(
        df[['source', 'id', 'datetime']].set_index(['source', 'id']),
        on=['source', 'id_a'],
    )

    measurement_combinations = measurement_combinations.join(
        df[['source', 'id', 'datetime']].set_index(['source', 'id']),
        on=['source', 'id_b'], lsuffix='_a', rsuffix='_b'
    )

    to_correct_mask = (
        measurement_combinations['datetime_a']
        > measurement_combinations['datetime_b']
    )

    if np.any(to_correct_mask):
        logger.debug('Correcting measurement pairs order')
        (
            measurement_combinations.loc[to_correct_mask, 'id_a'],
            measurement_combinations.loc[to_correct_mask, 'id_b']
        ) = np.array([
            measurement_combinations.loc[to_correct_mask, 'id_b'].values,
            measurement_combinations.loc[to_correct_mask, 'id_a'].values
        ])

    measurement_combinations = measurement_combinations.drop(
        ['datetime_a', 'datetime_b'], axis=1
    )

    # add the measurement fluxes and errors
    association_fluxes = df.set_index(["source", "id"])[
        ["flux_int", "flux_int_err", "flux_peak", "flux_peak_err", "image"]
    ].rename(columns={"image": "image_name"})
    measurement_combinations = measurement_combinations.join(
        association_fluxes,
        on=["source", "id_a"],
    ).join(
        association_fluxes,
        on=["source", "id_b"],
        lsuffix="_a",
        rsuffix="_b",
    )

    # calculate 2-epoch metrics
    measurement_combinations["vs_peak"] = calculate_vs_metric(
        measurement_combinations.flux_peak_a,
        measurement_combinations.flux_peak_b,
        measurement_combinations.flux_peak_err_a,
        measurement_combinations.flux_peak_err_b,
    )
    measurement_combinations["vs_int"] = calculate_vs_metric(
        measurement_combinations.flux_int_a,
        measurement_combinations.flux_int_b,
        measurement_combinations.flux_int_err_a,
        measurement_combinations.flux_int_err_b,
    )
    measurement_combinations["m_peak"] = calculate_m_metric(
        measurement_combinations.flux_peak_a,
        measurement_combinations.flux_peak_b,
    )
    measurement_combinations["m_int"] = calculate_m_metric(
        measurement_combinations.flux_int_a,
        measurement_combinations.flux_int_b,
    )

    return measurement_combinations

calculate_vs_metric(flux_a, flux_b, flux_err_a, flux_err_b)

Calculate the Vs variability metric which is the t-statistic that the provided fluxes are variable. See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105.

Parameters:

Name Type Description Default
flux_a float

flux value "A".

required
flux_b float

flux value "B".

required
flux_err_a float

error of flux_a.

required
flux_err_b float

error of flux_b.

required

Returns:

Name Type Description
float float

the Vs metric for flux values "A" and "B".

Source code in vast_pipeline/pipeline/utils.py
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
def calculate_vs_metric(
    flux_a: float, flux_b: float, flux_err_a: float, flux_err_b: float
) -> float:
    """Calculate the Vs variability metric which is the t-statistic that the provided
    fluxes are variable. See Section 5 of Mooley et al. (2016) for details,
    DOI: 10.3847/0004-637X/818/2/105.

    Args:
        flux_a (float): flux value "A".
        flux_b (float): flux value "B".
        flux_err_a (float): error of `flux_a`.
        flux_err_b (float): error of `flux_b`.

    Returns:
        float: the Vs metric for flux values "A" and "B".
    """
    return (flux_a - flux_b) / np.hypot(flux_err_a, flux_err_b)

check_primary_image(row)

Checks whether the primary image of the ideal source dataframe is in the image list for the source.

Parameters:

Name Type Description Default
row pd.Series

Input dataframe row, with columns ['primary'] and ['img_list'].

required

Returns:

Type Description
bool

True if primary in image list else False.

Source code in vast_pipeline/pipeline/utils.py
876
877
878
879
880
881
882
883
884
885
886
887
888
def check_primary_image(row: pd.Series) -> bool:
    """
    Checks whether the primary image of the ideal source
    dataframe is in the image list for the source.

    Args:
        row:
            Input dataframe row, with columns ['primary'] and ['img_list'].

    Returns:
        True if primary in image list else False.
    """
    return row['primary'] in row['img_list']

create_measurement_pairs_arrow_file(p_run)

Creates a measurement_pairs.arrow file using the parquet outputs of a pipeline run.

Parameters:

Name Type Description Default
p_run Run

Pipeline model instance.

required

Returns:

Type Description
None

None

Source code in vast_pipeline/pipeline/utils.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
def create_measurement_pairs_arrow_file(p_run: Run) -> None:
    """
    Creates a measurement_pairs.arrow file using the parquet outputs
    of a pipeline run.

    Args:
        p_run:
            Pipeline model instance.

    Returns:
        None
    """
    logger.info('Creating measurement_pairs.arrow for run %s.', p_run.name)

    measurement_pairs_df = pd.read_parquet(
        os.path.join(
            p_run.path,
            'measurement_pairs.parquet'
        )
    )

    logger.debug('Optimising dataframe.')
    measurement_pairs_df = optimize_ints(optimize_floats(measurement_pairs_df))

    logger.debug("Loading to pyarrow table.")
    measurement_pairs_df = pa.Table.from_pandas(measurement_pairs_df)

    logger.debug("Exporting to arrow file.")
    outname = os.path.join(p_run.path, 'measurement_pairs.arrow')

    local = pa.fs.LocalFileSystem()

    with local.open_output_stream(outname) as file:
       with pa.RecordBatchFileWriter(file, measurement_pairs_df.schema) as writer:
          writer.write_table(measurement_pairs_df)

create_measurements_arrow_file(p_run)

Creates a measurements.arrow file using the parquet outputs of a pipeline run.

Parameters:

Name Type Description Default
p_run Run

Pipeline model instance.

required

Returns:

Type Description
None

None

Source code in vast_pipeline/pipeline/utils.py
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
def create_measurements_arrow_file(p_run: Run) -> None:
    """
    Creates a measurements.arrow file using the parquet outputs
    of a pipeline run.

    Args:
        p_run:
            Pipeline model instance.

    Returns:
        None
    """
    logger.info('Creating measurements.arrow for run %s.', p_run.name)

    associations = pd.read_parquet(
        os.path.join(
            p_run.path,
            'associations.parquet'
        )
    )
    images = pd.read_parquet(
        os.path.join(
            p_run.path,
            'images.parquet'
        )
    )

    m_files = images['measurements_path'].tolist()

    m_files += glob.glob(os.path.join(
        p_run.path,
        'forced*.parquet'
    ))

    logger.debug('Loading %i files...', len(m_files))
    measurements = dd.read_parquet(m_files, engine='pyarrow').compute()

    measurements = measurements.loc[
        measurements['id'].isin(associations['meas_id'].values)
    ]

    measurements = (
        associations.loc[:, ['meas_id', 'source_id']]
        .set_index('meas_id')
        .merge(
            measurements,
            left_index=True,
            right_on='id'
        )
        .rename(columns={'source_id': 'source'})
    )

    logger.debug('Optimising dataframes.')
    measurements = optimize_ints(optimize_floats(measurements))

    logger.debug("Loading to pyarrow table.")
    measurements = pa.Table.from_pandas(measurements)

    logger.debug("Exporting to arrow file.")
    outname = os.path.join(p_run.path, 'measurements.arrow')

    local = pa.fs.LocalFileSystem()

    with local.open_output_stream(outname) as file:
       with pa.RecordBatchFileWriter(file, measurements.schema) as writer:
          writer.write_table(measurements)

cross_join(left, right)

A convenience function to merge two dataframes.

Parameters:

Name Type Description Default
left pd.DataFrame

The base pandas DataFrame to merge.

required
right pd.DataFrame

The pandas DataFrame to merge to the left.

required

Returns:

Type Description
pd.DataFrame

The resultant merged DataFrame.

Source code in vast_pipeline/pipeline/utils.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
def cross_join(left: pd.DataFrame, right: pd.DataFrame) -> pd.DataFrame:
    """
    A convenience function to merge two dataframes.

    Args:
        left: The base pandas DataFrame to merge.
        right: The pandas DataFrame to merge to the left.

    Returns:
        The resultant merged DataFrame.

    """
    return (
        left.assign(key=1)
        .merge(right.assign(key=1), on='key')
        .drop('key', axis=1)
    )

get_create_img(p_run, band_id, image)

Function to fetch or create the Image and Sky Region objects for the images in the pipeline run.

Parameters:

Name Type Description Default
p_run Run

The pipeline run Django ORM object.

required
band_id int

The integer database id value of the frequency band of the image.

required
image Image

The image Django ORM object.

required

Returns:

Type Description
Image

The resulting image django ORM object, the sky region Django ORM

SkyRegion

object and a bool value denoting if the image already existed in the

bool

database.

Source code in vast_pipeline/pipeline/utils.py
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
def get_create_img(
    p_run: Run, band_id: int, image: Image
) -> Tuple[Image, SkyRegion, bool]:
    """
    Function to fetch or create the Image and Sky Region objects for the images
    in the pipeline run.

    Args:
        p_run: The pipeline run Django ORM object.
        band_id: The integer database id value of the frequency band of the
            image.
        image: The image Django ORM object.

    Returns:
        The resulting image django ORM object, the sky region Django ORM
        object and a bool value denoting if the image already existed in the
        database.
    """
    img = Image.objects.filter(name__exact=image.name)
    if img.exists():
        img = img.get()
        # Add background path if not originally provided
        if image.background_path and not img.background_path:
            img.background_path = image.background_path
            img.save()
        skyreg = get_create_skyreg(p_run, img)
        # check and add the many to many if not existent
        if not Image.objects.filter(
            id=img.id, run__id=p_run.id
        ).exists():
            img.run.add(p_run)

        return (img, skyreg, True)

    # at this stage, measurement parquet file is not created but
    # assume location
    img_folder_name = image.name.replace('.', '_')
    measurements_path = os.path.join(
        settings.PIPELINE_WORKING_DIR,
        'images',
        img_folder_name,
        'measurements.parquet'
        )
    img = Image(
        band_id=band_id,
        measurements_path=measurements_path
    )
    # set the attributes and save the image,
    # by selecting only valid (not hidden) attributes
    # FYI attributs and/or method starting with _ are hidden
    # and with __ can't be modified/called
    for fld in img._meta.get_fields():
        if getattr(fld, 'attname', None) and (
            getattr(image, fld.attname, None) is not None
        ):
            setattr(img, fld.attname, getattr(image, fld.attname))

    # get create the sky region and associate with image
    skyreg = get_create_skyreg(p_run, img)
    img.skyreg = skyreg

    img.rms_median, img.rms_min, img.rms_max = get_rms_noise_image_values(
        img.noise_path
    )

    img.save()
    img.run.add(p_run)

    return (img, skyreg, False)

get_create_img_band(image)

Return the existing Band row for the given FitsImage. An image is considered to belong to a band if its frequency is within some tolerance of the band's frequency. Returns a Band row or None if no matching band.

Parameters:

Name Type Description Default
image Image

The image Django ORM object.

required

Returns:

Type Description
Band

The band Django ORM object.

Source code in vast_pipeline/pipeline/utils.py
 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
def get_create_img_band(image: Image) -> Band:
    '''
    Return the existing Band row for the given FitsImage.
    An image is considered to belong to a band if its frequency is within some
    tolerance of the band's frequency.
    Returns a Band row or None if no matching band.

    Args:
        image: The image Django ORM object.

    Returns:
        The band Django ORM object.
    '''
    # For now we match bands using the central frequency.
    # This assumes that every band has a unique frequency,
    # which is true for the data we've used so far.
    freq = int(image.freq_eff * 1.e-6)
    freq_band = int(image.freq_bw * 1.e-6)
    # TODO: refine the band query
    for band in Band.objects.all():
        diff = abs(freq - band.frequency) / float(band.frequency)
        if diff < 0.02:
            return band

    # no band has been found so create it
    band = Band(name=str(freq), frequency=freq, bandwidth=freq_band)
    logger.info('Adding new frequency band: %s', band)
    band.save()

    return band

get_create_p_run(name, path, description=None, user=None)

Get or create a pipeline run in db, return the run django object and a flag True/False if has been created or already exists.

Parameters:

Name Type Description Default
name str

The name of the pipeline run.

required
path str

The system path to the pipeline run folder which contains the configuration file and where outputs will be saved.

required
description str

An optional description of the pipeline run.

None
user User

The Django user that launched the pipeline run.

None

Returns:

Type Description
Run

The pipeline run object and a boolean object representing whether

bool

the pipeline run already existed ('True') or not ('False').

Source code in vast_pipeline/pipeline/utils.py
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
def get_create_p_run(
    name: str, path: str, description: str=None, user: User=None
) -> Tuple[Run, bool]:
    '''
    Get or create a pipeline run in db, return the run django object and
    a flag True/False if has been created or already exists.

    Args:
        name: The name of the pipeline run.
        path: The system path to the pipeline run folder which contains the
            configuration file and where outputs will be saved.
        description: An optional description of the pipeline run.
        user: The Django user that launched the pipeline run.

    Returns:
        The pipeline run object and a boolean object representing whether
        the pipeline run already existed ('True') or not ('False').
    '''
    p_run = Run.objects.filter(name__exact=name)
    if p_run:
        return p_run.get(), True

    description = "" if description is None else description
    p_run = Run(name=name, description=description, path=path)
    if user:
        p_run.user = user
    p_run.save()

    return p_run, False

get_create_skyreg(p_run, image)

This creates a Sky Region object in Django ORM given the related image object.

Parameters:

Name Type Description Default
p_run Run

The pipeline run Django ORM object.

required
image Image

The image Django ORM object.

required

Returns:

Type Description
SkyRegion

The sky region Django ORM object.

Source code in vast_pipeline/pipeline/utils.py
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
def get_create_skyreg(p_run: Run, image: Image) -> SkyRegion:
    '''
    This creates a Sky Region object in Django ORM given the related
    image object.

    Args:
        p_run: The pipeline run Django ORM object.
        image: The image Django ORM object.

    Returns:
        The sky region Django ORM object.
    '''
    # In the calculations below, it is assumed the image has square
    # pixels (this pipeline has been designed for ASKAP images, so it
    # should always be square). It will likely give wrong results if not
    skyr = SkyRegion.objects.filter(
        centre_ra=image.ra,
        centre_dec=image.dec,
        xtr_radius=image.fov_bmin
    )
    if skyr:
        skyr = skyr.get()
        logger.info('Found sky region %s', skyr)
        if p_run not in skyr.run.all():
            logger.info('Adding %s to sky region %s', p_run, skyr)
            skyr.run.add(p_run)
        return skyr

    x, y, z = eq_to_cart(image.ra, image.dec)
    skyr = SkyRegion(
        centre_ra=image.ra,
        centre_dec=image.dec,
        width_ra=image.physical_bmin,
        width_dec=image.physical_bmaj,
        xtr_radius=image.fov_bmin,
        x=x,
        y=y,
        z=z,
    )
    skyr.save()
    logger.info('Created sky region %s', skyr)
    skyr.run.add(p_run)
    logger.info('Adding %s to sky region %s', p_run, skyr)

    return skyr

get_eta_metric(row, df, peak=False)

Calculates the eta variability metric of a source. Works on the grouped by dataframe using the fluxes of the associated measurements.

Parameters:

Name Type Description Default
row Dict[str, float]

Dictionary containing statistics for the current source.

required
df pd.DataFrame

The grouped by sources dataframe of the measurements containing all the flux and flux error information,

required
peak bool

Whether to use peak_flux for the calculation. If False then the integrated flux is used.

False

Returns:

Type Description
float

The calculated eta value.

Source code in vast_pipeline/pipeline/utils.py
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
def get_eta_metric(
    row: Dict[str, float], df: pd.DataFrame, peak: bool=False
) -> float:
    '''
    Calculates the eta variability metric of a source.
    Works on the grouped by dataframe using the fluxes
    of the associated measurements.

    Args:
        row: Dictionary containing statistics for the current source.
        df: The grouped by sources dataframe of the measurements containing all
            the flux and flux error information,
        peak: Whether to use peak_flux for the calculation. If False then the
            integrated flux is used.

    Returns:
        The calculated eta value.

    '''
    if row['n_meas'] == 1:
        return 0.

    suffix = 'peak' if peak else 'int'
    weights = 1. / df[f'flux_{suffix}_err'].values**2
    fluxes = df[f'flux_{suffix}'].values
    eta = (row['n_meas'] / (row['n_meas']-1)) * (
        (weights * fluxes**2).mean() - (
            (weights * fluxes).mean()**2 / weights.mean()
        )
    )
    return eta

get_image_list_diff(row)

Calculate the difference between the ideal coverage image list of a source and the actual observed image list. Also checks whether an epoch does in fact contain a detection but is not in the expected 'ideal' image for that epoch.

Parameters:

Name Type Description Default
row pd.Series

The row from the sources dataframe that is being iterated over.

required

Returns:

Type Description
List[str]

A list of the images missing from the observed image list. Will be

List[str]

returned as '-1' integer value if there are no missing images.

Source code in vast_pipeline/pipeline/utils.py
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
def get_image_list_diff(row: pd.Series) -> List[str]:
    """
    Calculate the difference between the ideal coverage image list of a source
    and the actual observed image list. Also checks whether an epoch does in
    fact contain a detection but is not in the expected 'ideal' image for that
    epoch.

    Args:
        row: The row from the sources dataframe that is being iterated over.

    Returns:
        A list of the images missing from the observed image list. Will be
        returned as '-1' integer value if there are no missing images.
    """
    out = list(
        filter(lambda arg: arg not in row['img_list'], row['skyreg_img_list'])
    )

    # set empty list to -1
    if not out:
        return -1

    # Check that an epoch has not already been seen (just not in the 'ideal'
    # image)
    out_epochs = [
        row['skyreg_epoch'][pair[0]] for pair in enumerate(
            row['skyreg_img_list']
        ) if pair[1] in out
    ]

    out = [
        out[pair[0]] for pair in enumerate(
            out_epochs
        ) if pair[1] not in row['epoch_list']
    ]

    if not out:
        out = -1

    return out

get_names_and_epochs(grp)

Convenience function to group together the image names, epochs and datetimes into one list object which is then returned as a pandas series. This is necessary for easier processing in the ideal coverage analysis.

Parameters:

Name Type Description Default
grp pd.DataFrame

A group from the grouped by sources DataFrame.

required

Returns:

Type Description
pd.Series

Pandas series containing the list object that contains the lists of the

pd.Series

image names, epochs and datetimes.

Source code in vast_pipeline/pipeline/utils.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
def get_names_and_epochs(grp: pd.DataFrame) -> pd.Series:
    """
    Convenience function to group together the image names, epochs and
    datetimes into one list object which is then returned as a pandas series.
    This is necessary for easier processing in the ideal coverage analysis.

    Args:
        grp: A group from the grouped by sources DataFrame.

    Returns:
        Pandas series containing the list object that contains the lists of the
        image names, epochs and datetimes.
    """
    d = {}
    d['skyreg_img_epoch_list'] = [[[x,], y, z] for x,y,z in zip(
        grp['name'].values.tolist(),
        grp['epoch'].values.tolist(),
        grp['datetime'].values.tolist()
    )]

    return pd.Series(d)

get_parallel_assoc_image_df(images, skyregion_groups)

Merge the sky region groups with the images and skyreg_ids.

Parameters:

Name Type Description Default
images List[Image]

A list of the Image objects.

required
skyregion_groups pd.DataFrame

The sky region group of each skyregion id. +----+----------------+ | | skyreg_group | |----+----------------| | 2 | 1 | | 3 | 1 | | 1 | 2 | +----+----------------+

required

Returns:

Type Description
pd.DataFrame

Dataframe containing the merged images and skyreg_id and skyreg_group.

pd.DataFrame

+----+-------------------------------+-------------+----------------+

pd.DataFrame

| | image | skyreg_id | skyreg_group |

pd.DataFrame

|----+-------------------------------+-------------+----------------|

pd.DataFrame

| 0 | VAST_2118+00A.EPOCH01.I.fits | 2 | 1 |

pd.DataFrame

| 1 | VAST_2118-06A.EPOCH01.I.fits | 3 | 1 |

pd.DataFrame

| 2 | VAST_0127-73A.EPOCH01.I.fits | 1 | 2 |

pd.DataFrame

| 3 | VAST_2118-06A.EPOCH03x.I.fits | 3 | 1 |

pd.DataFrame

| 4 | VAST_2118-06A.EPOCH02.I.fits | 3 | 1 |

pd.DataFrame

| 5 | VAST_2118-06A.EPOCH05x.I.fits | 3 | 1 |

pd.DataFrame

| 6 | VAST_2118-06A.EPOCH06x.I.fits | 3 | 1 |

pd.DataFrame

| 7 | VAST_0127-73A.EPOCH08.I.fits | 1 | 2 |

pd.DataFrame

+----+-------------------------------+-------------+----------------+

Source code in vast_pipeline/pipeline/utils.py
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
def get_parallel_assoc_image_df(
    images: List[Image], skyregion_groups: pd.DataFrame
) -> pd.DataFrame:
    """
    Merge the sky region groups with the images and skyreg_ids.

    Args:
        images:
            A list of the Image objects.
        skyregion_groups:
            The sky region group of each skyregion id.
            +----+----------------+
            |    |   skyreg_group |
            |----+----------------|
            |  2 |              1 |
            |  3 |              1 |
            |  1 |              2 |
            +----+----------------+

    Returns:
        Dataframe containing the merged images and skyreg_id and skyreg_group.
        +----+-------------------------------+-------------+----------------+
        |    | image                         |   skyreg_id |   skyreg_group |
        |----+-------------------------------+-------------+----------------|
        |  0 | VAST_2118+00A.EPOCH01.I.fits  |           2 |              1 |
        |  1 | VAST_2118-06A.EPOCH01.I.fits  |           3 |              1 |
        |  2 | VAST_0127-73A.EPOCH01.I.fits  |           1 |              2 |
        |  3 | VAST_2118-06A.EPOCH03x.I.fits |           3 |              1 |
        |  4 | VAST_2118-06A.EPOCH02.I.fits  |           3 |              1 |
        |  5 | VAST_2118-06A.EPOCH05x.I.fits |           3 |              1 |
        |  6 | VAST_2118-06A.EPOCH06x.I.fits |           3 |              1 |
        |  7 | VAST_0127-73A.EPOCH08.I.fits  |           1 |              2 |
        +----+-------------------------------+-------------+----------------+
    """
    skyreg_ids = [i.skyreg_id for i in images]

    images_df = pd.DataFrame({
        'image_dj': images,
        'skyreg_id': skyreg_ids,
    })

    images_df = images_df.merge(
        skyregion_groups,
        how='left',
        left_on='skyreg_id',
        right_index=True
    )

    images_df['image_name'] = images_df['image_dj'].apply(
        lambda x: x.name
    )

    images_df['image_datetime'] = images_df['image_dj'].apply(
        lambda x: x.datetime
    )

    return images_df

get_rms_noise_image_values(rms_path)

Open the RMS noise FITS file and compute the median, max and min rms values to be added to the image model and then used in the calculations.

Parameters:

Name Type Description Default
rms_path str

The system path to the RMS FITS image.

required

Returns:

Type Description
Tuple[float, float, float]

The median, minimum and maximum values of the RMS image.

Raises:

Type Description
IOError

Raised when the RMS FITS file cannot be found.

Source code in vast_pipeline/pipeline/utils.py
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
def get_rms_noise_image_values(rms_path: str) -> Tuple[float, float, float]:
    '''
    Open the RMS noise FITS file and compute the median, max and min
    rms values to be added to the image model and then used in the
    calculations.

    Args:
        rms_path: The system path to the RMS FITS image.

    Returns:
        The median, minimum and maximum values of the RMS image.

    Raises:
        IOError: Raised when the RMS FITS file cannot be found.
    '''
    logger.debug('Extracting Image RMS values from Noise file...')
    med_val = min_val = max_val = 0.
    try:
        with fits.open(rms_path) as f:
            data = f[0].data
            data = data[np.logical_not(np.isnan(data))]
            data = data[data != 0]
            med_val = np.median(data) * 1e+3
            min_val = np.min(data) * 1e+3
            max_val = np.max(data) * 1e+3
            del data
    except Exception:
        raise IOError(f'Could not read this RMS FITS file: {rms_path}')

    return med_val, min_val, max_val

get_src_skyregion_merged_df(sources_df, images_df, skyreg_df)

Analyses the current sources_df to determine what the 'ideal coverage' for each source should be. In other words, what images is the source missing in when it should have been seen.

Parameters:

Name Type Description Default
sources_df pd.DataFrame

The output of the association step containing the measurements associated into sources.

required
images_df pd.DataFrame

Contains the images of the pipeline run. I.e. all image objects for the run loaded into a dataframe.

required
skyreg_df pd.DataFrame

Contains the sky regions of the pipeline run. I.e. all sky region objects for the run loaded into a dataframe.

required

Returns:

Type Description
pd.DataFrame

DataFrame containing missing image information. Output format:

pd.DataFrame

+----------+----------------------------------+-----------+------------+

pd.DataFrame

| source | img_list | wavg_ra | wavg_dec |

pd.DataFrame

|----------+----------------------------------+-----------+------------+

pd.DataFrame

| 278 | ['VAST_0127-73A.EPOCH01.I.fits'] | 22.2929 | -71.8717 |

pd.DataFrame

| 702 | ['VAST_0127-73A.EPOCH01.I.fits'] | 28.8125 | -69.3547 |

pd.DataFrame

| 844 | ['VAST_0127-73A.EPOCH01.I.fits'] | 17.3152 | -72.346 |

pd.DataFrame

| 934 | ['VAST_0127-73A.EPOCH01.I.fits'] | 9.75754 | -72.9629 |

pd.DataFrame

| 1290 | ['VAST_0127-73A.EPOCH01.I.fits'] | 20.8455 | -76.8269 |

pd.DataFrame

+----------+----------------------------------+-----------+------------+

pd.DataFrame

------------------------------------------------------------------+ skyreg_img_list |

pd.DataFrame

------------------------------------------------------------------+ ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] | ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] | ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] | ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] | ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |

pd.DataFrame

------------------------------------------------------------------+

pd.DataFrame

----------------------------------+------------------------------+ img_diff | primary |

pd.DataFrame

----------------------------------+------------------------------+ ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits | ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits | ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits | ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits | ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |

pd.DataFrame

----------------------------------+------------------------------+

pd.DataFrame

------------------------------+--------------+ detection | in_primary |

pd.DataFrame

------------------------------+--------------| VAST_0127-73A.EPOCH01.I.fits | True | VAST_0127-73A.EPOCH01.I.fits | True | VAST_0127-73A.EPOCH01.I.fits | True | VAST_0127-73A.EPOCH01.I.fits | True | VAST_0127-73A.EPOCH01.I.fits | True |

pd.DataFrame

------------------------------+--------------+

Source code in vast_pipeline/pipeline/utils.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
def get_src_skyregion_merged_df(
    sources_df: pd.DataFrame, images_df: pd.DataFrame, skyreg_df: pd.DataFrame
) -> pd.DataFrame:
    """
    Analyses the current sources_df to determine what the 'ideal coverage'
    for each source should be. In other words, what images is the source
    missing in when it should have been seen.

    Args:
        sources_df:
            The output of the association  step containing the
            measurements associated into sources.
        images_df:
            Contains the images of the pipeline run. I.e. all image
            objects for the run loaded into a dataframe.
        skyreg_df:
            Contains the sky regions of the pipeline run. I.e. all
            sky region objects for the run loaded into a dataframe.

    Returns:
        DataFrame containing missing image information. Output format:
        +----------+----------------------------------+-----------+------------+
        |   source | img_list                         |   wavg_ra |   wavg_dec |
        |----------+----------------------------------+-----------+------------+
        |      278 | ['VAST_0127-73A.EPOCH01.I.fits'] |  22.2929  |   -71.8717 |
        |      702 | ['VAST_0127-73A.EPOCH01.I.fits'] |  28.8125  |   -69.3547 |
        |      844 | ['VAST_0127-73A.EPOCH01.I.fits'] |  17.3152  |   -72.346  |
        |      934 | ['VAST_0127-73A.EPOCH01.I.fits'] |   9.75754 |   -72.9629 |
        |     1290 | ['VAST_0127-73A.EPOCH01.I.fits'] |  20.8455  |   -76.8269 |
        +----------+----------------------------------+-----------+------------+
        ------------------------------------------------------------------+
         skyreg_img_list                                                  |
        ------------------------------------------------------------------+
         ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |
         ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |
         ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |
         ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |
         ['VAST_0127-73A.EPOCH01.I.fits', 'VAST_0127-73A.EPOCH08.I.fits'] |
        ------------------------------------------------------------------+
        ----------------------------------+------------------------------+
         img_diff                         | primary                      |
        ----------------------------------+------------------------------+
         ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |
         ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |
         ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |
         ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |
         ['VAST_0127-73A.EPOCH08.I.fits'] | VAST_0127-73A.EPOCH01.I.fits |
        ----------------------------------+------------------------------+
        ------------------------------+--------------+
         detection                    | in_primary   |
        ------------------------------+--------------|
         VAST_0127-73A.EPOCH01.I.fits | True         |
         VAST_0127-73A.EPOCH01.I.fits | True         |
         VAST_0127-73A.EPOCH01.I.fits | True         |
         VAST_0127-73A.EPOCH01.I.fits | True         |
         VAST_0127-73A.EPOCH01.I.fits | True         |
        ------------------------------+--------------+
    """
    logger.info("Creating ideal source coverage df...")

    merged_timer = StopWatch()

    skyreg_df = skyreg_df.drop(
        ['x', 'y', 'z', 'width_ra', 'width_dec'], axis=1
    )

    images_df['name'] = images_df['image_dj'].apply(
        lambda x: x.name
    )
    images_df['datetime'] = images_df['image_dj'].apply(
        lambda x: x.datetime
    )

    skyreg_df = skyreg_df.join(
        pd.DataFrame(
            images_df.groupby('skyreg_id').apply(
                get_names_and_epochs
            )
        ),
        on='id'
    )

    sources_df = sources_df.sort_values(by='datetime')
    # calculate some metrics on sources
    # compute only some necessary metrics in the groupby
    timer = StopWatch()
    srcs_df = parallel_groupby_coord(sources_df)
    logger.debug('Groupby-apply time: %.2f seconds', timer.reset())

    del sources_df

    # create dataframe with all skyregions and sources combinations
    src_skyrg_df = cross_join(
        srcs_df.drop(['epoch_list', 'img_list'], axis=1).reset_index(),
        skyreg_df.drop('skyreg_img_epoch_list', axis=1)
    )

    skyreg_df = skyreg_df.drop(
        ['centre_ra', 'centre_dec', 'xtr_radius'],
        axis=1
    ).set_index('id')

    src_skyrg_df['sep'] = np.rad2deg(
        on_sky_sep(
            np.deg2rad(src_skyrg_df['wavg_ra'].values),
            np.deg2rad(src_skyrg_df['centre_ra'].values),
            np.deg2rad(src_skyrg_df['wavg_dec'].values),
            np.deg2rad(src_skyrg_df['centre_dec'].values),
        )
    )

    # select rows where separation is less than sky region radius
    # drop not more useful columns and groupby source id
    # compute list of images
    src_skyrg_df = (
        src_skyrg_df.loc[
            src_skyrg_df.sep < src_skyrg_df.xtr_radius,
            ['source', 'id', 'sep']
        ].merge(skyreg_df, left_on='id', right_index=True)
        .drop('id', axis=1)
        .explode('skyreg_img_epoch_list')
    )

    del skyreg_df

    src_skyrg_df[
        ['skyreg_img_list', 'skyreg_epoch', 'skyreg_datetime']
    ] = pd.DataFrame(
        src_skyrg_df['skyreg_img_epoch_list'].tolist(),
        index=src_skyrg_df.index
    )

    src_skyrg_df = src_skyrg_df.drop('skyreg_img_epoch_list', axis=1)

    src_skyrg_df = (
        src_skyrg_df.sort_values(
            ['source', 'sep']
        )
        .drop_duplicates(['source', 'skyreg_epoch'])
        .sort_values(by='skyreg_datetime')
        .drop(
            ['sep', 'skyreg_datetime'],
            axis=1
        )
    )
    # annoyingly epoch needs to be not a list to drop duplicates
    # but then we need to sum the epochs into a list
    src_skyrg_df['skyreg_epoch'] = src_skyrg_df['skyreg_epoch'].apply(
        lambda x: [x,]
    )

    src_skyrg_df = (
        src_skyrg_df.groupby('source')
        .agg('sum') # sum because we need to preserve order
    )

    # merge into main df and compare the images
    srcs_df = srcs_df.merge(
        src_skyrg_df, left_index=True, right_index=True
    )

    del src_skyrg_df

    srcs_df['img_diff'] = srcs_df[
        ['img_list', 'skyreg_img_list', 'epoch_list', 'skyreg_epoch']
    ].apply(
        get_image_list_diff, axis=1
    )

    srcs_df = srcs_df.loc[
        srcs_df['img_diff'] != -1
    ]

    srcs_df = srcs_df.drop(
        ['epoch_list', 'skyreg_epoch'],
        axis=1
    )

    srcs_df['primary'] = srcs_df[
        'skyreg_img_list'
    ].apply(lambda x: x[0])

    srcs_df['detection'] = srcs_df[
        'img_list'
    ].apply(lambda x: x[0])

    srcs_df['in_primary'] = srcs_df[
        ['primary', 'img_list']
    ].apply(
        check_primary_image,
        axis=1
    )

    srcs_df = srcs_df.drop(['img_list', 'skyreg_img_list', 'primary'], axis=1)

    logger.info(
        'Ideal source coverage time: %.2f seconds', merged_timer.reset()
    )

    return srcs_df

group_skyregions(df)

Logic to group sky regions into overlapping groups. Returns a dataframe containing the sky region id as the index and a column containing a list of the sky region group number it belongs to.

Parameters:

Name Type Description Default
df pd.DataFrame

A dataframe containing all the sky regions of the run. Only the 'id', 'centre_ra', 'centre_dec' and 'xtr_radius' columns are required. +------+-------------+--------------+--------------+ | id | centre_ra | centre_dec | xtr_radius | |------+-------------+--------------+--------------| | 2 | 319.652 | 0.0030765 | 6.72488 | | 3 | 319.652 | -6.2989 | 6.7401 | | 1 | 21.8361 | -73.121 | 7.24662 | +------+-------------+--------------+--------------+

required

Returns:

Type Description
pd.DataFrame

The sky region group of each skyregion id.

pd.DataFrame

+----+----------------+

pd.DataFrame

| | skyreg_group |

pd.DataFrame

|----+----------------|

pd.DataFrame

| 2 | 1 |

pd.DataFrame

| 3 | 1 |

pd.DataFrame

| 1 | 2 |

pd.DataFrame

+----+----------------+

Source code in vast_pipeline/pipeline/utils.py
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
def group_skyregions(df: pd.DataFrame) -> pd.DataFrame:
    """
    Logic to group sky regions into overlapping groups.
    Returns a dataframe containing the sky region id as
    the index and a column containing a list of the
    sky region group number it belongs to.

    Args:
        df:
            A dataframe containing all the sky regions of the run. Only the
            'id', 'centre_ra', 'centre_dec' and 'xtr_radius' columns are
            required.
            +------+-------------+--------------+--------------+
            |   id |   centre_ra |   centre_dec |   xtr_radius |
            |------+-------------+--------------+--------------|
            |    2 |    319.652  |    0.0030765 |      6.72488 |
            |    3 |    319.652  |   -6.2989    |      6.7401  |
            |    1 |     21.8361 |  -73.121     |      7.24662 |
            +------+-------------+--------------+--------------+

    Returns:
        The sky region group of each skyregion id.
        +----+----------------+
        |    |   skyreg_group |
        |----+----------------|
        |  2 |              1 |
        |  3 |              1 |
        |  1 |              2 |
        +----+----------------+
    """
    sr_coords = SkyCoord(
        df['centre_ra'],
        df['centre_dec'],
        unit=(u.deg, u.deg)
    )

    df = df.set_index('id')

    results = df.apply(
        _get_skyregion_relations,
        args=(sr_coords, df.index),
        axis=1
    )

    skyreg_groups = {}

    master_done = []  # keep track of all checked ids in master done

    for skyreg_id, neighbours in results.iteritems():

        if skyreg_id not in master_done:
            local_done = []   # a local done list for the sky region group.
            # add the current skyreg_id to both master and local done.
            master_done.append(skyreg_id)
            local_done.append(skyreg_id)
            # Define the new group number based on the existing ones.
            skyreg_group = len(skyreg_groups) + 1
            # Add all the ones that we know are neighbours that were obtained
            # from _get_skyregion_relations.
            skyreg_groups[skyreg_group] = list(neighbours)

            # Now the sky region group is extended out to include all those sky
            # regions that overlap with the neighbours.
            # Each neighbour is checked and added to the local done list.
            # Checked means that for each neighbour, it's own neighbours are
            # added to the current group if not in already.
            # When the local done is equal to the skyreg group we know that
            # we have exhausted all possible neighbours and that results in a
            # sky region group.
            while sorted(local_done) != sorted(skyreg_groups[skyreg_group]):
                # Loop over each neighbour
                for other_skyreg_id in skyreg_groups[skyreg_group]:
                    # If we haven't checked this neighbour locally proceed.
                    if other_skyreg_id not in local_done:
                        # Add it to the local checked.
                        local_done.append(other_skyreg_id)
                        # Get the neighbours neighbour and add these.
                        new_vals = results.loc[other_skyreg_id]
                        for k in new_vals:
                            if k not in skyreg_groups[skyreg_group]:
                                skyreg_groups[skyreg_group].append(k)

            # Reached the end of the group so append all to the master
            # done list
            for j in skyreg_groups[skyreg_group]:
                master_done.append(j)
        else:
            # continue if already placed in group
            continue

    # flip the dictionary around
    skyreg_group_ids = {}
    for i in skyreg_groups:
        for j in skyreg_groups[i]:
            skyreg_group_ids[j]=i

    skyreg_group_ids = pd.DataFrame.from_dict(
        skyreg_group_ids, orient='index'
    ).rename(columns={0: 'skyreg_group'})

    return skyreg_group_ids

groupby_funcs(df)

Performs calculations on the unique sources to get the lightcurve properties. Works on the grouped by source dataframe.

Parameters:

Name Type Description Default
df pd.DataFrame

The current iteration dataframe of the grouped by sources dataframe.

required

Returns:

Type Description
pd.Series

Pandas series containing the calculated metrics of the source.

Source code in vast_pipeline/pipeline/utils.py
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
def groupby_funcs(df: pd.DataFrame) -> pd.Series:
    '''
    Performs calculations on the unique sources to get the
    lightcurve properties. Works on the grouped by source
    dataframe.

    Args:
        df: The current iteration dataframe of the grouped by sources
            dataframe.

    Returns:
        Pandas series containing the calculated metrics of the source.

    '''
    # calculated average ra, dec, fluxes and metrics
    d = {}
    d['img_list'] = df['image'].values.tolist()
    d['n_meas_forced'] = df['forced'].sum()
    d['n_meas'] = df['id'].count()
    d['n_meas_sel'] = d['n_meas'] - d['n_meas_forced']
    d['n_sibl'] = df['has_siblings'].sum()
    if d['n_meas_forced'] > 0:
        non_forced_sel = df['forced'] != True
        d['wavg_ra'] = (
            df.loc[non_forced_sel, 'interim_ew'].sum() /
            df.loc[non_forced_sel, 'weight_ew'].sum()
        )
        d['wavg_dec'] = (
            df.loc[non_forced_sel, 'interim_ns'].sum() /
            df.loc[non_forced_sel, 'weight_ns'].sum()
        )
        d['avg_compactness'] = df.loc[
            non_forced_sel, 'compactness'
        ].mean()
        d['min_snr'] = df.loc[
            non_forced_sel, 'snr'
        ].min()
        d['max_snr'] = df.loc[
            non_forced_sel, 'snr'
        ].max()

    else:
        d['wavg_ra'] = df['interim_ew'].sum() / df['weight_ew'].sum()
        d['wavg_dec'] = df['interim_ns'].sum() / df['weight_ns'].sum()
        d['avg_compactness'] = df['compactness'].mean()
        d['min_snr'] = df['snr'].min()
        d['max_snr'] = df['snr'].max()

    d['wavg_uncertainty_ew'] = 1. / np.sqrt(df['weight_ew'].sum())
    d['wavg_uncertainty_ns'] = 1. / np.sqrt(df['weight_ns'].sum())
    for col in ['avg_flux_int', 'avg_flux_peak']:
        d[col] = df[col.split('_', 1)[1]].mean()
    for col in ['max_flux_peak', 'max_flux_int']:
        d[col] = df[col.split('_', 1)[1]].max()
    for col in ['min_flux_peak', 'min_flux_int']:
        d[col] = df[col.split('_', 1)[1]].min()
    for col in ['min_flux_peak_isl_ratio', 'min_flux_int_isl_ratio']:
        d[col] = df[col.split('_', 1)[1]].min()

    for col in ['flux_int', 'flux_peak']:
        d[f'{col}_sq'] = (df[col]**2).mean()
    d['v_int'] = df['flux_int'].std() / df['flux_int'].mean()
    d['v_peak'] = df['flux_peak'].std() / df['flux_peak'].mean()
    d['eta_int'] = get_eta_metric(d, df)
    d['eta_peak'] = get_eta_metric(d, df, peak=True)
    # remove not used cols
    for col in ['flux_int_sq', 'flux_peak_sq']:
        d.pop(col)

    # get unique related sources
    list_uniq_related = list(set(
        chain.from_iterable(
            lst for lst in df['related'] if isinstance(lst, list)
        )
    ))
    d['related_list'] = list_uniq_related if list_uniq_related else -1

    return pd.Series(d).fillna(value={"v_int": 0.0, "v_peak": 0.0})

parallel_groupby(df)

Performs the parallel source dataframe operations to calculate the source metrics using Dask and returns the resulting dataframe.

Parameters:

Name Type Description Default
df pd.DataFrame

The sources dataframe produced by the previous pipeline stages.

required

Returns:

Type Description
pd.DataFrame

The source dataframe with the calculated metric columns.

Source code in vast_pipeline/pipeline/utils.py
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
def parallel_groupby(df: pd.DataFrame) -> pd.DataFrame:
    """
    Performs the parallel source dataframe operations to calculate the source
    metrics using Dask and returns the resulting dataframe.

    Args:
        df: The sources dataframe produced by the previous pipeline stages.

    Returns:
        The source dataframe with the calculated metric columns.
    """
    col_dtype = {
        'img_list': 'O',
        'n_meas_forced': 'i',
        'n_meas': 'i',
        'n_meas_sel': 'i',
        'n_sibl': 'i',
        'wavg_ra': 'f',
        'wavg_dec': 'f',
        'avg_compactness': 'f',
        'min_snr': 'f',
        'max_snr': 'f',
        'wavg_uncertainty_ew': 'f',
        'wavg_uncertainty_ns': 'f',
        'avg_flux_int': 'f',
        'avg_flux_peak': 'f',
        'max_flux_peak': 'f',
        'max_flux_int': 'f',
        'min_flux_peak': 'f',
        'min_flux_int': 'f',
        'min_flux_peak_isl_ratio': 'f',
        'min_flux_int_isl_ratio': 'f',
        'v_int': 'f',
        'v_peak': 'f',
        'eta_int': 'f',
        'eta_peak': 'f',
        'related_list': 'O'
    }
    n_cpu = cpu_count() - 1
    out = dd.from_pandas(df, n_cpu)
    out = (
        out.groupby('source')
        .apply(
            groupby_funcs,
            meta=col_dtype
        )
        .compute(num_workers=n_cpu, scheduler='processes')
    )

    out['n_rel'] = out['related_list'].apply(lambda x: 0 if x == -1 else len(x))

    return out

parallel_groupby_coord(df)

This function uses Dask to perform the average coordinate and unique image and epoch lists calculation. The result from the Dask compute is returned which is a dataframe containing the results for each source.

Parameters:

Name Type Description Default
df pd.DataFrame

The sources dataframe produced by the pipeline.

required

Returns:

Type Description
pd.DataFrame

The resulting average coordinate values and unique image and epoch

pd.DataFrame

lists for each unique source (group).

Source code in vast_pipeline/pipeline/utils.py
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
def parallel_groupby_coord(df: pd.DataFrame) -> pd.DataFrame:
    """
    This function uses Dask to perform the average coordinate and unique image
    and epoch lists calculation. The result from the Dask compute is returned
    which is a dataframe containing the results for each source.

    Args:
        df: The sources dataframe produced by the pipeline.

    Returns:
        The resulting average coordinate values and unique image and epoch
        lists for each unique source (group).
    """
    col_dtype = {
        'img_list': 'O',
        'epoch_list': 'O',
        'wavg_ra': 'f',
        'wavg_dec': 'f',
    }
    n_cpu = cpu_count() - 1
    out = dd.from_pandas(df, n_cpu)
    out = (
        out.groupby('source')
        .apply(calc_ave_coord, meta=col_dtype)
        .compute(num_workers=n_cpu, scheduler='processes')
    )

    return out

prep_skysrc_df(images, perc_error=0.0, duplicate_limit=None, ini_df=False)

Initialise the source dataframe to use in association logic by reading the measurement parquet file and creating columns. When epoch based association is used it will also remove duplicate measurements from the list of sources.

Parameters:

Name Type Description Default
images List[Image]

A list holding the Image objects of the images to load measurements for.

required
perc_error float

A percentage flux error to apply to the flux errors of the measurements. Defaults to 0.

0.0
duplicate_limit Optional[Angle]

The separation limit of when a source is considered a duplicate. Defaults to None in which case 2.5 arcsec is used in the 'remove_duplicate_measurements' function (usual ASKAP pixel size).

None
ini_df bool

Boolean to indicate whether these sources are part of the initial source list creation for association. If 'True' the source ids are reset ready for the first iteration. Defaults to 'False'.

False

Returns:

Type Description
pd.DataFrame

The measurements of the image(s) with some extra values set ready for

pd.DataFrame

association and duplicates removed if necessary.

Source code in vast_pipeline/pipeline/utils.py
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
def prep_skysrc_df(
    images: List[Image],
    perc_error: float = 0.,
    duplicate_limit: Optional[Angle] = None,
    ini_df: bool = False
) -> pd.DataFrame:
    '''
    Initialise the source dataframe to use in association logic by
    reading the measurement parquet file and creating columns. When epoch
    based association is used it will also remove duplicate measurements from
    the list of sources.

    Args:
        images:
            A list holding the Image objects of the images to load measurements
            for.
        perc_error:
            A percentage flux error to apply to the flux errors of the
            measurements. Defaults to 0.
        duplicate_limit:
            The separation limit of when a source is considered a duplicate.
            Defaults to None in which case 2.5 arcsec is used in the
            'remove_duplicate_measurements' function (usual ASKAP pixel size).
        ini_df:
            Boolean to indicate whether these sources are part of the initial
            source list creation for association. If 'True' the source ids are
            reset ready for the first iteration. Defaults to 'False'.

    Returns:
        The measurements of the image(s) with some extra values set ready for
        association and duplicates removed if necessary.
    '''
    cols = [
        'id',
        'ra',
        'uncertainty_ew',
        'weight_ew',
        'dec',
        'uncertainty_ns',
        'weight_ns',
        'flux_int',
        'flux_int_err',
        'flux_int_isl_ratio',
        'flux_peak',
        'flux_peak_err',
        'flux_peak_isl_ratio',
        'forced',
        'compactness',
        'has_siblings',
        'snr'
    ]

    df = _load_measurements(images[0], cols, ini_df=ini_df)

    if len(images) > 1:
        for img in images[1:]:
            df = df.append(
                _load_measurements(img, cols, df.source.max(), ini_df=ini_df),
                ignore_index=True
            )

        df = remove_duplicate_measurements(
            df, dup_lim=duplicate_limit, ini_df=ini_df
        )

    df = df.drop('dist_from_centre', axis=1)

    if perc_error != 0.0:
        logger.info('Correcting flux errors with config error setting...')
        for col in ['flux_int', 'flux_peak']:
            df[f'{col}_err'] = np.hypot(
                df[f'{col}_err'].values, perc_error * df[col].values
            )

    return df

reconstruct_associtaion_dfs(images_df_done, previous_parquet_paths)

This function is used with add image mode and performs the necessary manipulations to reconstruct the sources_df and skyc1_srcs required by association.

Parameters:

Name Type Description Default
images_df_done pd.DataFrame

The images_df output from the existing run (from the parquet).

required
previous_parquet_paths Dict[str, str]

Dictionary that contains the paths for the previous run parquet files. Keys are 'images', 'associations', 'sources', 'relations' and 'measurement_pairs'.

required

Returns:

Type Description
Tuple[pd.DataFrame, pd.DataFrame]

The reconstructed sources_df and skyc1_srs dataframes.

Source code in vast_pipeline/pipeline/utils.py
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
def reconstruct_associtaion_dfs(
    images_df_done: pd.DataFrame,
    previous_parquet_paths: Dict[str, str]
) -> Tuple[pd.DataFrame, pd.DataFrame]:
    """
    This function is used with add image mode and performs the necessary
    manipulations to reconstruct the sources_df and skyc1_srcs required by
    association.

    Args:
        images_df_done:
            The images_df output from the existing run (from the parquet).
        previous_parquet_paths:
            Dictionary that contains the paths for the previous run parquet
            files. Keys are 'images', 'associations', 'sources', 'relations'
            and 'measurement_pairs'.

    Returns:
        The reconstructed sources_df and skyc1_srs dataframes.
    """
    prev_associations = pd.read_parquet(previous_parquet_paths['associations'])

    # Get the parquet paths from the image objects
    img_meas_paths = (
        images_df_done['image_dj'].apply(lambda x: x.measurements_path)
        .to_list()
    )

    # Obtain the pipeline run path in order to fetch forced measurements.
    run_path = previous_parquet_paths['sources'].replace(
        'sources.parquet.bak', ''
    )

    # Get the forced measurement paths.
    img_fmeas_paths = []

    for i in images_df_done.image_name.values:
        forced_parquet = os.path.join(
            run_path, "forced_measurements_{}.parquet".format(
                i.replace(".", "_")
            )
        )
        if os.path.isfile(forced_parquet):
            img_fmeas_paths.append(forced_parquet)

    # Create union of paths.
    img_meas_paths += img_fmeas_paths

    # Define the columns that are required
    cols = [
        'id',
        'ra',
        'uncertainty_ew',
        'weight_ew',
        'dec',
        'uncertainty_ns',
        'weight_ns',
        'flux_int',
        'flux_int_err',
        'flux_int_isl_ratio',
        'flux_peak',
        'flux_peak_err',
        'flux_peak_isl_ratio',
        'forced',
        'compactness',
        'has_siblings',
        'snr',
        'image_id',
        'time',
    ]

    # Open all the parquets
    logger.debug(
        "Opening all measurement parquet files to use in reconstruction..."
    )
    measurements = pd.concat(
        [pd.read_parquet(f, columns=cols) for f in img_meas_paths]
    )

    # Create mask to drop measurements for epoch mode (epoch based mode).
    measurements_mask = measurements['id'].isin(
        prev_associations['meas_id'])
    measurements = measurements.loc[measurements_mask].set_index('id')

    # Set the index on images_df for faster merging.
    images_df_done['image_id'] = images_df_done['image_dj'].apply(
        lambda x: x.id).values
    images_df_done = images_df_done.set_index('image_id')

    # Merge image information to measurements
    measurements = (
        measurements.merge(
            images_df_done[['image_name', 'epoch']],
            left_on='image_id', right_index=True
        )
        .rename(columns={'image_name': 'image'})
    )

    # Drop any associations that are not used in this sky region group.
    associations_mask = prev_associations['meas_id'].isin(
        measurements.index.values)

    prev_associations = prev_associations.loc[associations_mask]

    # Merge measurements into the associations to form the sources_df.
    sources_df = (
        prev_associations.merge(
            measurements, left_on='meas_id', right_index=True
        )
        .rename(columns={
            'source_id': 'source', 'time': 'datetime', 'meas_id': 'id',
            'ra': 'ra_source', 'dec': 'dec_source',
            'uncertainty_ew': 'uncertainty_ew_source',
            'uncertainty_ns': 'uncertainty_ns_source',
        })
    )

    # Load up the previous unique sources.
    prev_sources = pd.read_parquet(
        previous_parquet_paths['sources'], columns=[
            'wavg_ra', 'wavg_dec',
            'wavg_uncertainty_ew', 'wavg_uncertainty_ns',
        ]
    )

    # Merge the wavg ra and dec to the sources_df - this is required to
    # create the skyc1_srcs below (but MUST be converted back to the source
    # ra and dec)
    sources_df = (
        sources_df.merge(
            prev_sources, left_on='source', right_index=True)
        .rename(columns={
            'wavg_ra': 'ra', 'wavg_dec': 'dec',
            'wavg_uncertainty_ew': 'uncertainty_ew',
            'wavg_uncertainty_ns': 'uncertainty_ns',
        })
    )

    # Load the previous relations
    prev_relations = pd.read_parquet(previous_parquet_paths['relations'])

    # Form relation lists to merge in.
    prev_relations = pd.DataFrame(
        prev_relations
        .groupby('from_source_id')['to_source_id']
        .apply(lambda x: x.values.tolist())
    ).rename(columns={'to_source_id': 'related'})

    # Append the relations to only the last instance of each source
    # First get the ids of the sources
    relation_ids = sources_df[
        sources_df.source.isin(prev_relations.index.values)].drop_duplicates(
            'source', keep='last'
        ).index.values
    # Make sure we attach the correct source id
    source_ids = sources_df.loc[relation_ids].source.values
    sources_df['related'] = np.nan
    relations_to_update = prev_relations.loc[source_ids].to_numpy().copy()
    relations_to_update = np.reshape(
        relations_to_update, relations_to_update.shape[0])
    sources_df.loc[relation_ids, 'related'] = relations_to_update

    # Reorder so we don't mess up the dask metas.
    sources_df = sources_df[[
        'id', 'uncertainty_ew', 'weight_ew', 'uncertainty_ns', 'weight_ns',
        'flux_int', 'flux_int_err', 'flux_int_isl_ratio', 'flux_peak',
        'flux_peak_err', 'flux_peak_isl_ratio', 'forced', 'compactness',
        'has_siblings', 'snr', 'image', 'datetime', 'source', 'ra', 'dec',
        'ra_source', 'dec_source', 'd2d', 'dr', 'related', 'epoch',
        'uncertainty_ew_source', 'uncertainty_ns_source'
    ]]

    # Create the unique skyc1_srcs dataframe.
    skyc1_srcs = (
        sources_df[sources_df['forced'] == False]
        .sort_values(by='id')
        .drop('related', axis=1)
        .drop_duplicates('source')
    ).copy(deep=True)

    # Get relations into the skyc1_srcs (as we only keep the first instance
    # which does not have the relation information)
    skyc1_srcs = skyc1_srcs.merge(
        prev_relations, how='left', left_on='source', right_index=True
)

    # Need to break the pointer relationship between the related sources (
    # deep=True copy does not truly copy mutable type objects)
    relation_mask = skyc1_srcs.related.notna()
    relation_vals = skyc1_srcs.loc[relation_mask, 'related'].to_list()
    new_relation_vals = [x.copy() for x in relation_vals]
    skyc1_srcs.loc[relation_mask, 'related'] = new_relation_vals

    # Reorder so we don't mess up the dask metas.
    skyc1_srcs = skyc1_srcs[[
        'id', 'ra', 'uncertainty_ew', 'weight_ew', 'dec', 'uncertainty_ns',
        'weight_ns', 'flux_int', 'flux_int_err', 'flux_int_isl_ratio',
        'flux_peak', 'flux_peak_err', 'flux_peak_isl_ratio', 'forced',
        'compactness', 'has_siblings', 'snr', 'image', 'datetime', 'source',
        'ra_source', 'dec_source', 'd2d', 'dr', 'related', 'epoch'
    ]].reset_index(drop=True)

    # Finally move the source ra and dec back to the sources_df ra and dec
    # columns
    sources_df['ra'] = sources_df['ra_source']
    sources_df['dec'] = sources_df['dec_source']
    sources_df['uncertainty_ew'] = sources_df['uncertainty_ew_source']
    sources_df['uncertainty_ns'] = sources_df['uncertainty_ns_source']

    # Drop not needed columns for the sources_df.
    sources_df = sources_df.drop([
        'uncertainty_ew_source', 'uncertainty_ns_source'
    ], axis=1).reset_index(drop=True)

    return sources_df, skyc1_srcs

remove_duplicate_measurements(sources_df, dup_lim=None, ini_df=False)

Remove perceived duplicate sources from a dataframe of loaded measurements. Duplicates are determined by their separation and whether this distances is within the 'dup_lim'.

Parameters:

Name Type Description Default
sources_df pd.DataFrame

The loaded measurements from two or more images.

required
dup_lim Optional[Angle]

The separation limit of when a source is considered a duplicate. Defaults to None in which case 2.5 arcsec is used (usual ASKAP pixel size).

None
ini_df bool

Boolean to indicate whether these sources are part of the initial source list creation for association. If 'True' the source ids are reset ready for the first iteration. Defaults to 'False'.

False

Returns:

Type Description
pd.DataFrame

The input sources_df with duplicate sources removed.

Source code in vast_pipeline/pipeline/utils.py
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
def remove_duplicate_measurements(
    sources_df: pd.DataFrame,
    dup_lim: Optional[Angle] = None,
    ini_df: bool = False
) -> pd.DataFrame:
    """
    Remove perceived duplicate sources from a dataframe of loaded
    measurements. Duplicates are determined by their separation and whether
    this distances is within the 'dup_lim'.

    Args:
        sources_df:
            The loaded measurements from two or more images.
        dup_lim:
            The separation limit of when a source is considered a duplicate.
            Defaults to None in which case 2.5 arcsec is used (usual ASKAP
            pixel size).
        ini_df:
            Boolean to indicate whether these sources are part of the initial
            source list creation for association. If 'True' the source ids are
            reset ready for the first iteration. Defaults to 'False'.

    Returns:
        The input sources_df with duplicate sources removed.
    """
    logger.debug('Cleaning duplicate sources from epoch...')

    if dup_lim is None:
        dup_lim = Angle(2.5 * u.arcsec)

    logger.debug(
        'Using duplicate crossmatch radius of %.2f arcsec.', dup_lim.arcsec
    )

    min_source = sources_df['source'].min()

    # sort by the distance from the image centre so we know
    # that the first source is always the one to keep
    sources_df = sources_df.sort_values(by='dist_from_centre')

    sources_sc = SkyCoord(
        sources_df['ra'],
        sources_df['dec'],
        unit=(u.deg, u.deg)
    )

    # perform search around sky to get all self matches
    idxc, idxcatalog, d2d_around, _ = sources_sc.search_around_sky(
        sources_sc, dup_lim
    )

    # create df from results
    results = pd.DataFrame(
        data={
            'source_id': idxc,
            'match_id': idxcatalog,
            'source_image': sources_df.iloc[idxc]['image'].tolist(),
            'match_image': sources_df.iloc[idxcatalog]['image'].tolist()
        }
    )

    # Drop those that are matched from the same image
    matching_image_mask = (
        results['source_image'] != results['match_image']
    )

    results = (
        results.loc[matching_image_mask]
        .drop(['source_image', 'match_image'], axis=1)
    )

    # create a pair column defining each pair ith index
    results['pair'] = results.apply(tuple, 1).apply(sorted).apply(tuple)
    # Drop the duplicate pairs (pairs are sorted so this works)
    results = results.drop_duplicates('pair')
    # No longer need pair
    results = results.drop('pair', axis=1)
    # Drop all self matches and we are left with those to drop
    # in the match id column.
    to_drop = results.loc[
        results['source_id'] != results['match_id'],
        'match_id'
    ]
    # Get the index values from the ith values
    to_drop_indexes = sources_df.iloc[to_drop].index.values
    logger.debug(
        "Dropping %i duplicate measurements.", to_drop_indexes.shape[0]
    )
    # Drop them from sources
    sources_df = sources_df.drop(to_drop_indexes).sort_values(by='ra')

    # reset the source_df index
    sources_df = sources_df.reset_index(drop=True)

    # Reset the source number
    if ini_df:
        sources_df['source'] = sources_df.index + 1

    del results

    return sources_df

Last update: March 2, 2022
Created: March 2, 2022