1-generate_sample.py 11.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
The "main script" of this repository: Read in a configuration file and
generate synthetic GW data according to the provided specifications.
"""


import argparse
import numpy as np
import os
import sys
import time

from itertools import count

from utils.configfiles import read_ini_config, read_json_config
from utils.hdffiles import NoiseTimeline
from utils.samplefiles import SampleFile
from utils.samplegeneration import generate_sample
from utils.waveforms import WaveformParameterGenerator

# -----------------------------------------------------------------------------
# MAIN CODE
# -----------------------------------------------------------------------------

if __name__ == '__main__':

    script_start = time.time()
    
    # Set up the parser and add arguments
    parser = argparse.ArgumentParser(description='Generate a GW data sample.')
    parser.add_argument('--config-file',
                        help='Name of the JSON configuration file which '
                             'controls the sample generation process.',
                        default='default.json')

    # Parse the arguments that were passed when calling this script
    command_line_arguments = vars(parser.parse_args())

    # -------------------------------------------------------------------------
    # Read in JSON config file specifying the sample generation process
    # -------------------------------------------------------------------------

    # Build the full path to the config file
    json_config_name = command_line_arguments['config_file']
    json_config_path = os.path.join('.', 'config_files', json_config_name)
    
    # Read the JSON configuration into a dict
    print('Reading and validating in JSON configuration file...', end=' ')
    config = read_json_config(json_config_path)
    print('Done!')

    # -------------------------------------------------------------------------
    # Read in INI config file specifying the static_args and variable_args
    # -------------------------------------------------------------------------

    # Build the full path to the waveform params file
    ini_config_name = config['waveform_params_file_name']
    ini_config_path = os.path.join('.', 'config_files', ini_config_name)

    # Read in the variable_arguments and static_arguments
    print('Reading and validating in INI configuration file...', end=' ')
    variable_arguments, static_arguments = read_ini_config(ini_config_path)
    print('Done!\n')

    # -------------------------------------------------------------------------
    # Shortcuts and random seed
    # -------------------------------------------------------------------------

    # Set the random seed for this script
    np.random.seed(config['random_seed'])

    # Define some useful shortcuts
    random_seed = config['random_seed']

    # -------------------------------------------------------------------------
    # Construct a generator for sampling waveform parameters
    # -------------------------------------------------------------------------

    # Initialize a waveform parameter generator that can sample injection
    # parameters from the distributions specified in the config file
    waveform_parameter_generator = \
        WaveformParameterGenerator(config_file=ini_config_path,
                                   random_seed=random_seed)

    # Wrap it in a generator expression so that we can we can easily sample
    # from it by calling next(waveform_parameters)
    waveform_parameters = \
        (waveform_parameter_generator.draw() for _ in iter(int, 1))

90
    print('Using synthetic noise! (background_data_directory = None)\n')
91

92
93
94
95
96
97
    # Create a iterator that returns a fake "event time", which we will
    # use as a seed for the RNG to ensure the reproducibility of the
    # generated synthetic noise.
    # For the HDF file path that contains that time, we always yield
    # None, so that we know that we need to generate synthetic noise.
    noise_times = ((1000000000 + _, None) for _ in count())
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

    # -------------------------------------------------------------------------
    # Define a convenience function to generate arguments for the simulation
    # -------------------------------------------------------------------------

    def generate_arguments(injection=True):

        # Only sample waveform parameters if we are making an injection
        waveform_params = next(waveform_parameters) if injection else None

        # Return all necessary arguments as a dictionary
        return dict(static_arguments=static_arguments,
                    event_tuple=next(noise_times),
                    waveform_params=waveform_params)

    # -------------------------------------------------------------------------
    # Finally: Create our samples!
    # -------------------------------------------------------------------------

    # Keep track of all the samples (and parameters) we have generated
    samples = dict(injection_samples=[], noise_samples=[])
    injection_parameters = dict(injection_samples=[], noise_samples=[])

121
    for sample_type in ['injection_samples', 'noise_samples']:
122

123
124
125
126
127
128
129
130
        # ---------------------------------------------------------------------
        # Define some sample_type-specific shortcuts
        # ---------------------------------------------------------------------
        
        if sample_type == 'injection_samples':
            print('Generating samples containing an injection...')
            n_samples = config['n_injection_samples']
            arguments_generator = \
131
                (generate_arguments(injection=True) for _ in iter(int, 1))
132
133
134
135
136
137
138
139
140
141
            
        else:
            print('Generating samples *not* containing an injection...')
            n_samples = config['n_noise_samples']
            arguments_generator = \
                (generate_arguments(injection=False) for _ in iter(int, 1))

        # ---------------------------------------------------------------------
        # If we do not need to generate any samples, skip ahead:
        # ---------------------------------------------------------------------
142

143
144
145
        if n_samples == 0:
            print('Done! (n_samples=0)\n')
            continue
146
147

        results_list = []
148
149
150
151
152
153
154
155
156
157
        # ---------------------------------------------------------------------
        # Loop over injections or noise:
        # ---------------------------------------------------------------------
        for i in range(n_samples):
            print('Generating the',i,'th samples\n')
            arguments = next(arguments_generator)
            print(arguments)
            result = generate_sample(**arguments)
            results_list.append(result)
            
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        # ---------------------------------------------------------------------
        # Process results in the results_list
        # ---------------------------------------------------------------------

        # Separate the samples and the injection parameters
        samples[sample_type], injection_parameters[sample_type] = \
            zip(*results_list)

        # Sort all results by the event_time
        idx = np.argsort([_['event_time'] for _ in list(samples[sample_type])])
        samples[sample_type] = \
            list([samples[sample_type][i] for i in idx])
        injection_parameters[sample_type] = \
            list([injection_parameters[sample_type][i] for i in idx])

173
174
175
176
        if sample_type == 'injection_samples':
            print('Signal+noise generation completed!\n')
        else:
            print('Noise generation completed!\n')
177
178
179
180
181
182
183
184
185
186
187
188
189
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
219
220
221

    # -------------------------------------------------------------------------
    # Compute the normalization parameters for this file
    # -------------------------------------------------------------------------

    print('Computing normalization parameters for sample...', end=' ')

    # Gather all samples (with and without injection) in one list
    all_samples = list(samples['injection_samples'] + samples['noise_samples'])

    # Group all samples by detector
    h1_samples = [_['h1_strain'] for _ in all_samples]
    l1_samples = [_['l1_strain'] for _ in all_samples]

    # Stack recordings along first axis
    h1_samples = np.vstack(h1_samples)
    l1_samples = np.vstack(l1_samples)
    
    # Compute the mean and standard deviation for both detectors as the median
    # of the means / standard deviations for each sample. This is more robust
    # towards outliers than computing "global" parameters by concatenating all
    # samples and treating them as a single, long time series.
    normalization_parameters = \
        dict(h1_mean=np.median(np.mean(h1_samples, axis=1), axis=0),
             l1_mean=np.median(np.mean(l1_samples, axis=1), axis=0),
             h1_std=np.median(np.std(h1_samples, axis=1), axis=0),
             l1_std=np.median(np.std(l1_samples, axis=1), axis=0))
    
    print('Done!\n')

    # -------------------------------------------------------------------------
    # Create a SampleFile dict from list of samples and save it as an HDF file
    # -------------------------------------------------------------------------

    print('Saving the results to HDF file ...', end=' ')

    # Initialize the dictionary that we use to create a SampleFile object
    sample_file_dict = dict(command_line_arguments=command_line_arguments,
                            injection_parameters=dict(),
                            injection_samples=dict(),
                            noise_samples=dict(),
                            normalization_parameters=normalization_parameters,
                            static_arguments=static_arguments)

    # Collect and add samples (with and without injection)
222
223
    for sample_type in ['injection_samples', 'noise_samples']:
        for key in ['event_time', 'h1_strain', 'l1_strain']:
224
225
226
227
228
229
230
231
            if samples[sample_type]:
                value = np.array([_[key] for _ in list(samples[sample_type])])
            else:
                value = None
            sample_file_dict[sample_type][key] = value

    # Collect and add injection_parameters (ignore noise samples here, because
    # for those, the injection_parameters are always None)
232
233
234
    #other_keys = ['h1_signal', 'h1_snr', 'l1_signal', 'l1_snr', 'scale_factor']
    other_keys = ['h1_signal', 'h1_output_signal','h1_snr', 'l1_signal','l1_output_signal', 'l1_snr', 'scale_factor']

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
    for key in list(variable_arguments + other_keys):
        if injection_parameters['injection_samples']:
            value = np.array([_[key] for _ in
                              injection_parameters['injection_samples']])
        else:
            value = None
        sample_file_dict['injection_parameters'][key] = value

    # Construct the path for the output HDF file
    output_dir = os.path.join('.', 'output')
    if not os.path.exists(output_dir):
        os.mkdir(output_dir)
    sample_file_path = os.path.join(output_dir, config['output_file_name'])

    # Create the SampleFile object and save it to the specified output file
    sample_file = SampleFile(data=sample_file_dict)
    sample_file.to_hdf(file_path=sample_file_path)

    print('Done!')

    # Get file size in MB and print the result
    sample_file_size = os.path.getsize(sample_file_path) / 1024**2
    print('Size of resulting HDF file: {:.2f}MB'.format(sample_file_size))
    print('')

    # -------------------------------------------------------------------------
    # Postliminaries
    # -------------------------------------------------------------------------

    # PyCBC always create a copy of the waveform parameters file, which we
    # can delete at the end of the sample generation process
    duplicate_path = os.path.join('.', config['waveform_params_file_name'])
    if os.path.exists(duplicate_path):
        os.remove(duplicate_path)

    # Print the total run time
    print('Total runtime: {:.1f} seconds!'.format(time.time() - script_start))
    print('')