Model for waveform generation

class Model(filename: typing.Optional[str] = None, initial_frequency_hz: float = 10.0, srate_hz: float = 4096.0, pca_components_number: int = 30, multibanding: bool = True, parameter_ranges: mlgw_bns.data_management.ParameterRanges = ParameterRanges(mass_range=(2.0, 4.0), q_range=(1.0, 3.0), lambda1_range=(5.0, 5000.0), lambda2_range=(5.0, 5000.0), chi1_range=(-0.5, 0.5), chi2_range=(-0.5, 0.5)), extend_with_post_newtonian=True, extend_with_zeros_at_high_frequency=False, waveform_generator: typing.Optional[mlgw_bns.dataset_generation.WaveformGenerator] = None, downsampling_training: typing.Optional[mlgw_bns.downsampling_interpolation.DownsamplingTraining] = None, nn_kind: typing.Type[mlgw_bns.neural_network.NeuralNetwork] = <class 'mlgw_bns.neural_network.SklearnNetwork'>, parameter_generator: typing.Optional[mlgw_bns.dataset_generation.ParameterGenerator] = None)[source]

mlgw_bns model. This class incorporates all the functionality required to compute the downsampling indices, train a PCA model, train a neural network and predict new waveforms.

Parameters
  • filename (str, optional) – Name for the model. Saved data will be saved under this name.

    Default: None

  • initial_frequency_hz (float, optional) – Initial frequency for the waveforms.

    Default: 10.0

  • srate_hz (float, optional) – Time-domain signal rate for the waveforms, which is twice the maximum frequency of their frequency-domain version.

    Default: 4096.0

  • pca_components_number (int, optional) – Number of PCA components to use when reducing the dimensionality of the dataset. By default 30, which is high enough to reach extremely good reconstruction accuracy (mismatches smaller than \(10^{-8}\)).

    Default: 30

  • multibanding (bool, optional) – Whether to use a multibanded frequency array. See the multibanding module for more details.

    Default: True

  • parameter_ranges (ParameterRanges, optional) – Ranges for the parameters to pass to the parameter generator.

    Default: ParameterRanges(mass_range=(2.0, 4.0), q_range=(1.0, 3.0), lambda1_range=(5.0, 5000.0), lambda2_range=(5.0, 5000.0), chi1_range=(-0.5, 0.5), chi2_range=(-0.5, 0.5))

  • extend_with_post_newtonian (bool, optional) – Whether to accept frequencies lower than the minimum training frequency, providing a hybrid post-newtonian / EOB surrogate waveform. If this is False, an error will be raised if the frequencies given include ones that are too low.

    Default: True

  • extend_with_zeros_at_high_frequency (bool, optional) – Whether to accept frequencies higher than the maximum training frequency, padding the returned waveform with zeros. If this is False, an error will be raised if the frequencies given include ones that are too high.

    Default: False

  • waveform_generator (WaveformGenerator, optional) – Generator for the waveforms to be used in the training; by default None, in which case the system attempts to import the Python wrapper for TEOBResumS, failing which a BareBarePostNewtonianGenerator is used, which is unable to generate effective-one-body waveforms.

    Default: None

  • downsampling_training (DownsamplingTraining, optional) – Training algorithm for the downsampling; by default None, which means the greedy algorithm implemented in GreedyDownsamplingTraining is used.

    Default: None

  • nn_kind (Type[NeuralNetwork], optional) – Neural network implementation to use, defaults to SklearnNetwork.

    Default: <class 'mlgw_bns.neural_network.SklearnNetwork'>

  • parameter_generator (Optional[ParameterGenerator], optional) – Certain parameter generators should not be regenerated each time; if this is the case, then pass the parameter generator here. Defaults to None.

    Default: None

property file_arrays: h5py._hl.files.File

File object in which to save datasets.

Returns

file – To be used as a context manager.

Return type

h5py.File

property filename_hyper: str

File name in which to save the hyperparameters.

property filename_nn: str

File name in which to save the neural network.

generate(training_downsampling_dataset_size: Optional[int] = 64, training_pca_dataset_size: Optional[int] = 256, training_nn_dataset_size: Optional[int] = 256) None[source]

Generate a new model from scratch.

The parameters are the sizes of the three datasets to be used when training, if they are set to None they are not computed and the pre-existing values are used instead.

Raises

AssertionError – If one of the parameters is set to None but no pre-existing data is availabele for it.

Parameters
  • training_downsampling_dataset_size (int, optional) – By default 64.

    Default: 64

  • training_pca_dataset_size (int, optional) – By default 256.

    Default: 256

  • training_nn_dataset_size (int, optional) – By default 256.

    Default: 256

load(streams: Optional[tuple[IO[bytes], IO[bytes], IO[bytes]]] = None) None[source]

Load model from the files present in the current folder.

Parameters

streams (tuple[IO[bytes], IO[bytes], IO[bytes]], optional) – For internal use (specifically, loading the default model). Defaults to None (look in the current folder).

Default: None

property pca_model: mlgw_bns.principal_component_analysis.PrincipalComponentAnalysisModel

PCA model to be used for dimensionality reduction.

Return type

PrincipalComponentAnalysisModel

predict(frequencies: numpy.ndarray, params: mlgw_bns.model.ParametersWithExtrinsic)[source]

Calculate the waveforms in the plus and cross polarizations, accounting for extrinsic parameters.

This function is able to yield a sensible waveform at arbitrarily low frequencies, by hybridizing the EOB-trained high-frequency part with a Post-Newtonian approximant. This feature can be turned off with the extend_with_post_newtonian parameter of the Model object.

Parameters

frequencies (np.ndarray) –

Frequencies where to compute the waveform, in Hz.

These should always be within the range in which the model has been trained, and be careful! The model is always trained with a specific initial frequency \(f_0\), and a final frequency \(f_1\), and it is trained to reconstruct the dependence of the waveform on \(M_0 f\), where \(M_0\) is some standard mass, typically \(2.8M_{\odot}\).

Now, this means that the model can only predict in the range \(M_0 f_0 \leq M f \leq M_0 f_1\); when \(M\) differs significantly from \(M_0\) this will be quite a different range from \([f_0, f_1]\).

paramsParametersWithExtrinsic

Parameters for the waveform, both intrinsic and extrinsic.

Raises
  • FrequencyTooLowError – When the frequencies given are too low, below the training range. For speed, this is only checked against the first and last elements of the array, assuming that it is sorted. This is raised only if the PN extension of the waveform is disabled by setting extend_with_post_newtonian to False.

  • FrequencyTooHighError – When the frequencies given are too high. For speed, this is only checked against the first and last elements of the array, assuming that it is sorted. This is raised only if the extension of the waveform with zeroes is disabled by setting extend_with_zeros_at_high_frequency to False.

Returns

Cartesian plus and cross-polarized waveforms, computed at the given frequencies, measured in 1/Hz.

Return type

hp, hc (complex np.ndarray)

predict_residuals_bulk(params: mlgw_bns.dataset_generation.ParameterSet, nn: mlgw_bns.neural_network.NeuralNetwork) mlgw_bns.data_management.Residuals[source]

Make a prediction for a set of different parameters, using a network provided as a parameter.

Parameters
  • params (ParameterSet) – Parameters of the residuals to reconstruct.

  • nn (NeuralNetwork) – Neural network to use for the reconstruction

Returns

Prediction through the model plus PCA.

Return type

Residuals

property reduced_residuals: numpy.ndarray

Reduced-dimensionality residuals — in other words, PCA components — corresponding to the training_dataset.

This attribute is cached.

save_arrays(include_training_data: bool = True) None[source]

Save all big arrays contained in this object to the file defined as {filename}.h5.

set_hyper_and_train_nn(hyper: Optional[mlgw_bns.neural_network.Hyperparameters] = None) None[source]

Train the network according to the hyperparameters given, and set it as a class attribute

Parameters

hyper (Hyperparameters, optional) – Hyperparameters to use when training the network, by default None. If not given, the default is to fall back to the standard set of hyperparameters provided with the module.

Default: None

time_until_merger(frequency: float, params: mlgw_bns.model.ParametersWithExtrinsic, delta_f: Optional[float] = None) float[source]

Approximate the time left until merger for a wavorm starting at a given frequency, using the approximate Stationary Phase Approximation expression given in Marsat and Baker 2018 (eq. 20):

\(t = - \frac{1}{2 \pi} \frac{\mathrm{d} \phi}{\mathrm{d} f}\)

The derivative is computed with ninth-order central differences, because why not.

Parameters
  • frequency (float) – frequency for which to compute the time to merger.

  • params (ParametersWithExtrinsic) – Parameters of the CBC.

  • delta_f (float, optional) – delta_f for the numerical calculation of the derivative. If None (default), it is computed internally as f/1000.

    Default: None

Returns

Time or times left until merger.

Return type

Union[float, np.ndarray]

train_nn(hyper: Hyperparameters, indices: Union[list[int], slice] = slice(None, None, None)) NeuralNetwork[source]

Train a

Parameters
  • hyper (Hyperparameters) – Hyperparameters to be used in the initialization of the network.

  • indices (Union[list[int], slice], optional) – Indices used to perform a selection of a subsection of the training data; by default slice(None) which means all available training data is used.

    Default: slice(None, None, None)

Returns

Trained network.

Return type

NeuralNetwork

class ParametersWithExtrinsic(mass_ratio: float, lambda_1: float, lambda_2: float, chi_1: float, chi_2: float, distance_mpc: float, inclination: float, total_mass: float, reference_phase: float = 0.0, time_shift: float = 0.0)[source]

Parameters for the generation of a single waveform, including extrinsic parameters.

Parameters
  • mass_ratio (float) – Mass ratio of the system, \(q = m_1 / m_2\), where \(m_1 \geq m_2\), so \(q \geq 1\).

  • lambda_1 (float) – Tidal polarizability of the larger star. In papers it is typically denoted as \(\Lambda_1\); for a definition see for example section D of this paper.

  • lambda_2 (float) – Tidal polarizability of the smaller star.

  • chi_1 (float) – Aligned dimensionless spin component of the larger star. The dimensionless spin is defined as \(\chi_i = S_i / m_i^2\) in \(c = G = 1\) natural units, where \(S_i\) is the \(z\) component of the dimensionful spin vector. The \(z\) axis is defined as the one which is parallel to the orbital angular momentum of the binary.

  • chi_2 (float) – Aligned spin component of the smaller star.

  • distance_mpc (float) – Distance to the binary system, in Megaparsecs.

  • inclination (float) – Inclination — angle between the binary system’s angular momentum and the observation direction, in radians.

  • total_mass (float) – Total mass of the binary system, in solar masses.

  • reference_phase (float, optional) – This will be set as the phase of the first point of the waveform. Defaults to 0.

    Default: 0.0

  • time_shift (float, optional) – The waveform will be shifted in the time domain by this amount (measured in seconds). In the frequency domain, this means adding a linear term to the phase. Defaults to 0, which by convention means a configuration in which the merger happens at the right edge of the timeseries. This also means that, in the frequency domain, the phase at high frequencies is roughly constant.

    Default: 0.0

classmethod gw170817() mlgw_bns.model.ParametersWithExtrinsic[source]

Convenience method: an easy-to-access set of parameters, roughly corresponding to the best-fit values for GW170817.

teobresums_dict(dataset: Dataset, use_effective_frequencies: bool = True) dict[str, Union[float, int, str]][source]

Parameter dictionary in a format compatible with TEOBResumS.

The parameters are all converted to natural units.

compute_polarizations(waveform_real: np.ndarray, waveform_imag: np.ndarray, pre_plus: Union[complex, float], pre_cross: Union[complex, float]) tuple[np.ndarray, np.ndarray][source]

Compute the two polarizations of the waveform, assuming they are the same but for a differerent prefactor (which is the case for compact binary coalescences).

This function is separated out so that it can be decorated with numba.njit which allows it to be compiled — this can speed up the computation somewhat.

Parameters
  • waveform_real (np.ndarray) – Real part of the cartesian complex-valued waveform.

  • waveform_imag (np.ndarray) – Imaginary part of the cartesian complex-valued waveform.

  • pre_plus (complex) – Real-valued prefactor for the plus polarization of the waveform.

  • pre_cross (complex) – Real-valued prefactor for the cross polarization of the waveform.

Returns

Plus and cross polarizations: complex-valued arrays.

Return type

tuple[np.ndarray, np.ndarray]