|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright © 2022 Université de Genève, LMU Munich - Faculty of Physics, IAP-CNRS/Sorbonne Université |
| 4 | +# |
| 5 | +# This library is free software; you can redistribute it and/or modify it under |
| 6 | +# the terms of the GNU Lesser General Public License as published by the Free |
| 7 | +# Software Foundation; either version 3.0 of the License, or (at your option) |
| 8 | +# any later version. |
| 9 | +# |
| 10 | +# This library is distributed in the hope that it will be useful, but WITHOUT |
| 11 | +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 12 | +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more |
| 13 | +# details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU Lesser General Public License |
| 16 | +# along with this library; if not, write to the Free Software Foundation, Inc., |
| 17 | +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 18 | +import itertools |
| 19 | +import os.path |
| 20 | +from argparse import ArgumentParser |
| 21 | +from configparser import ConfigParser |
| 22 | +from typing import Any, Dict |
| 23 | + |
| 24 | +import h5py |
| 25 | +import numpy as np |
| 26 | +from sourcextractor import __version__ as seversion |
| 27 | +from sourcextractor import pipeline |
| 28 | + |
| 29 | + |
| 30 | +class SNRFilter: |
| 31 | + """ |
| 32 | + Drop sources with a signal-to-noise below the configured limit. |
| 33 | + It expect sources, so it must be inserted into the pipeline *before* the partitioning |
| 34 | +
|
| 35 | + :param snr: float |
| 36 | + Signal-to-noise ratio cut |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__(self, snr: float): |
| 40 | + self.__snr = snr |
| 41 | + self.__next = None |
| 42 | + self.__dropped = [] |
| 43 | + |
| 44 | + @property |
| 45 | + def dropped(self): |
| 46 | + return self.__dropped |
| 47 | + |
| 48 | + def set_next_stage(self, stage): |
| 49 | + self.__next = stage |
| 50 | + |
| 51 | + def __call__(self, obj): |
| 52 | + """ |
| 53 | + Apply the SNR filter |
| 54 | + """ |
| 55 | + if isinstance(obj, pipeline.Source): |
| 56 | + if obj.isophotal_flux / obj.isophotal_flux_err < self.__snr: |
| 57 | + self.__dropped.append(obj) |
| 58 | + return |
| 59 | + self.__next(obj) |
| 60 | + |
| 61 | + |
| 62 | +class StoreStamps: |
| 63 | + """ |
| 64 | + Store the detection stamps into the HDF5 file |
| 65 | +
|
| 66 | + :param hd5: h5py.File |
| 67 | + Output HDF5 file |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__(self, hd5: h5py.File): |
| 71 | + self.__hd5 = hd5 |
| 72 | + self.__next = None |
| 73 | + |
| 74 | + def set_next_stage(self, stage): |
| 75 | + self.__next = stage |
| 76 | + |
| 77 | + def __store_stamp(self, source): |
| 78 | + stamp = source.detection_filtered_stamp |
| 79 | + dataset = self.__hd5.create_dataset(f'sources/{source.source_id}', data=stamp) |
| 80 | + dataset.attrs.create('CLASS', 'IMAGE', dtype='S6') |
| 81 | + dataset.attrs.create('IMAGE_VERSION', '1.2', dtype='S4') |
| 82 | + dataset.attrs.create('IMAGE_SUBCLASS', 'IMAGE_GRAYSCALE', dtype='S16') |
| 83 | + dataset.attrs.create('IMAGE_MINMAXRANGE', [np.min(stamp), np.max(stamp)]) |
| 84 | + |
| 85 | + def __call__(self, obj): |
| 86 | + """ |
| 87 | + Supports being called with a single Source, or with a Group of sources |
| 88 | + """ |
| 89 | + match type(obj): |
| 90 | + case pipeline.Source: |
| 91 | + self.__store_stamp(obj) |
| 92 | + case pipeline.Group: |
| 93 | + [self.__store_stamp(source) for source in obj] |
| 94 | + case _: |
| 95 | + print(f'Unknown {type(obj)}') |
| 96 | + self.__next(obj) |
| 97 | + |
| 98 | + |
| 99 | +def run_sourcextractor(config: Dict[str, Any], output_path: str, stamps: bool): |
| 100 | + """ |
| 101 | + Setup the sourcextractor++ pipeline, run it, and write the output to an HDF5 file |
| 102 | + """ |
| 103 | + output = h5py.File(output_path, 'w') |
| 104 | + |
| 105 | + snr_filter = SNRFilter(float(config.pop('snr', 5))) |
| 106 | + with pipeline.Context(config): |
| 107 | + stages = [pipeline.Segmentation(), pipeline.Partition(), snr_filter, pipeline.Grouping(), pipeline.Deblending()] |
| 108 | + if stamps: |
| 109 | + stages.append(StoreStamps(output)) |
| 110 | + stages.append(pipeline.NumpyOutput()) |
| 111 | + pipe = pipeline.Pipeline(stages) |
| 112 | + result = pipe().to_numpy() |
| 113 | + print(f'Dropped {len(snr_filter.dropped)} sources') |
| 114 | + |
| 115 | + output.create_dataset(os.path.basename(config['detection-image']), data=result) |
| 116 | + output.close() |
| 117 | + print(f'{output_path} created!') |
| 118 | + |
| 119 | + |
| 120 | +def parse_config_file(path: str) -> Dict[str, Any]: |
| 121 | + """ |
| 122 | + Parse a sourcextractor++ (like) config file into a dictionary |
| 123 | + """ |
| 124 | + parser = ConfigParser() |
| 125 | + with open(path, 'rt') as fd: |
| 126 | + parser.read_file(itertools.chain(['[main]'], fd)) |
| 127 | + return {k: v for k, v in parser.items('main')} |
| 128 | + |
| 129 | + |
| 130 | +# Entry point |
| 131 | +if __name__ == '__main__': |
| 132 | + print(f'Running sourcextractor++ {seversion}') |
| 133 | + |
| 134 | + parser = ArgumentParser() |
| 135 | + parser.add_argument('--output-file', type=str, metavar='HDF5', default='output.h5', help='Output file') |
| 136 | + parser.add_argument('--with-stamps', action='store_true', default=False, help='Store source stamps') |
| 137 | + parser.add_argument('config_file', type=str, metavar='CONFIGURATION', help='Configuration file') |
| 138 | + |
| 139 | + args = parser.parse_args() |
| 140 | + run_sourcextractor(parse_config_file(args.config_file), args.output_file, args.with_stamps) |
0 commit comments