Module for performing initial-final interpolation.

We showcase the initial-final interpolator which plays a critical role in the evolving binary populations. To use the initial-final interpolator we first import the IFInterpolator class from the POSYDON library.

# importing interpolator from posydon.interpolation.IF_interpolation import IFInterpolator

I. Loading a Pretrained Interpolator

To load a pretrained interpolator we need to pass in the filename argument into the IFInterpolator constructor which specifies the path to a .pkl file where the pretrained interpolator can be loaded from. POSYDON provides various pretrained models whose corresponding .pkl files can be found in the data directory of the POSYDON repository.

model = IFInterpolator()

model.load(“path/to/file.pkl”)

II. Training the Interpolator

The interpolator can be trained using an instance of the PSyGrid class which can be constructed by running ones own simulations or by loading a simulation from an h5 file stored in the data directory of the POSYDON repository. For more details on the PSyGrid class please visit the PSyGrid documentation. The IFInterpolator class relies on the BaseIFInterpolator class to perform the interpolation so parameters to construct instances of the BaseIFInterpolator classes are required to construct the IFInterpolator. These parameters are:

1. interp_method: the interpolation method to be used can be either linear, 1NN, or a list specifying which interpolation method to be used for each type of track. If interp_classes is specified and this parameter is not a list then the interpolator will use the specified method for all classes.

2. interp_classes: a list of classes that the simulation tracks can fall into. Usually specified as the mass transfer type. This only needs be specified if interp_method is a list.

3. class_method: the classification method to be used, either kNN or 1NN.

4. in_keys: the keys to be used as the input to the interpolator, by default these are star_1_mass, star_2_mass, and period_days.

5. out_keys: the keys for which the interpolator is supposed to provide values, by default all keys are used.

6. in_scaling: The scalings for the input keys, by default these scalings are optimized through Monte Carlo Cross Validation.

7. out_scaling: The scalings for the output keys, by default these scalings are optimized through Monte Carlo Cross Validation.

  1. c_keys: A list of strings specifying which classifiers are to be trained

9. c_key: A string specifying by which class the interpolator should interpolate binaries. Only to be specified in the MCInterpolator case.

For most applications specifying only the first four parameters is recommended.

from posydon.grids.psygrid import PSyGrid from posydon.interpolation.IF_interpolation import IFInterpolator

grid = PSyGrid(“path/to/h5/file.h5”) # loading grid from h5 file

interp = IFInterpolator(grid = grid, interpolators = [
{

“interp_method”: [“linear”, “linear”, “linear”], “interp_classes”: [“no_MT”, “stable_MT”, “unstable_MT”], “out_keys”: first, “class_method”: “kNN”, “c_keys”: [“interpolation_class”], “c_key”: “interpolation_class”

}, {

“interp_method”: [“linear”, “linear”, “linear”, “linear”], “interp_classes”: [“None”, “BH”, “WD”, “NS”], “out_keys”: second, “class_method”: “kNN”, “c_keys”: [‘S1_direct_state’], “c_key”: ‘S1_direct_state’

}, {

“interp_method”: [“linear”, “linear”, “linear”, “linear”], “interp_classes”: [“None”, “BH”, “WD”, “NS”], “out_keys”: third, “class_method”: “kNN”, “c_keys”: [‘S1_Fryer+12-rapid_state’], “c_key”: ‘S1_Fryer+12-rapid_state’

}, {

“interp_method”: [“linear”, “linear”, “linear”, “linear”], “interp_classes”: [“None”, “BH”, “WD”, “NS”], “out_keys”: fourth, “class_method”: “kNN”, “c_keys”: [‘S1_Fryer+12-delayed_state’], “c_key”: ‘S1_Fryer+12-delayed_state’

}, {

“interp_method”: [“linear”, “linear”, “linear”, “linear”], “interp_classes”: [“None”, “BH”, “WD”, “NS”], “out_keys”: fifth, “class_method”: “kNN”, “c_keys”: [‘S1_Sukhbold+16-engineN20_state’], “c_key”: ‘S1_Sukhbold+16-engineN20_state’

}, {

“interp_method”: [“linear”, “linear”, “linear”, “linear”], “interp_classes”: [“None”, “BH”, “WD”, “NS”], “out_keys”: sixth, “class_method”: “kNN”, “c_keys”: [‘S1_Patton&Sukhbold20-engineN20_state’], “c_key”: ‘S1_Patton&Sukhbold20-engineN20_state’

}

]) # constructing IFInterpolator

interp.train() # training interpolator

III. Using the Interpolator

Once the interpolator has been trained or loaded from a .pkl file it can be used to accomplish various tasks which most commonly are to classify a track into its class given an input vector and or to approximate a final vector given an input vector.

from posydon.binary_evol.binarystar import BinaryStar from posydon.binary_evol.singlestar import SingleStar

# creating binary, refer to BinaryStar documentation binary = BinaryStar(**binary_params,

star_1=SingleStar(**star1_params), star_2=SingleStar(**star2_params))

# evaluating returns a tuple of dictionaries interpolation, classification = interp.evaluate(binary)

Finally a trained interpolator can be easily saved by specifying a path to a .pkl file where the interpolator will be saved to.

model.save(“path/to/file.pkl”) # saving interpolator

class posydon.interpolation.IF_interpolation.BaseIFInterpolator(grid=None, in_keys=None, out_keys=None, in_scaling=None, out_scaling=None, filename=None, interp_method='linear', interp_classes=None, class_method='kNN', c_keys=None, c_key=None)[source]

Bases: object

Class handling the initial-final interpolation for POSYDON.

Initialize the BaseIFInterpolation.

Initialize the BaseIFInterpolation and if ‘filename’ is provided load a pretrained interpolator. If no filename is provided, the interpolator(s) and classifier(s) are trained upon initialization.

Parameters
  • grid (PSyGrid) – An instance of the PSyGrid class.

  • in_keys (list of strings) – The keys to be used as the input to the interpolator, by default these are star_1_mass, star_2_mass, and period_days.

  • out_keys (list of strings) – The keys for which the interpolator is supposed to provide values, by default all keys are used.

  • in_scaling (list of strings) – The scalings for the input keys, by default these scalings are optimized through Monte Carlo Cross Validation.

  • out_scaling (list of strings) – The scalings for the output keys, by default these scalings are optimized through Monte Carlo Cross Validation.

  • filename (string) – A path to a .pkl file containing a saved interpolator

  • interp_method (string or list of strings) – The interpolation method to be used can be either linear, 1NN, or a list specifying which interpolation method to be used for each type of track. If interp_classes is specified and this parameter is not a list then the interpolator will use the specified method for all classes.

  • interp_classes (list of strings) – A list of classes that the simulation tracks can fall into. Usually specified as the mass transfer type. This only needs be specified if interp_method is a list.

  • class_method (string or list of strings) – The classification method to be used, either kNN or 1NN.

  • c_keys (list of strings) – The keys for which a classifier should be trained. At a minimum should contain the keys needed for multi-class interpolation if it is requested

evaluate(binary, sanitization_verbose=False)[source]

Get the output vector approximation.

Get the output vector approximation as well as all of the classifications given a Binary Star.

Parameters

binary (BinaryStar) – A class which is an input vector which are to be classified and for which an output vector will be approximated.

Returns

Return type

Output space approximation as a tuple containing two dictionary

evaluate_mat(Xt)[source]

Get the output vector approximation.

Get the output vector approximation as well as all of the classifications given an input vector.

Parameters

Xt (numpy array) – A list of input vectors which are to be classified and for which output vectors are to be approximated.

Returns

Return type

Output space approximations as numpy arrays

load(filename)[source]

Load interpolation model, which can only be used for predictions.

Parameters

filename (str) – path/name of pickle file to be loaded.

save(filename)[source]

Save complete interpolation model.

Parameters

filename (str) – path/name of ‘.pkl’ file where the model will be saved.

test_classifier(key, Xt)[source]

Use just one specific classifier.

Parameters
  • key (string) – Name of the classifier

  • Xt (numpy array) – A list of input vectors which are to be classified.

Returns

Return type

Output space approximation as numpy array

test_classifier_prob(key, Xt)[source]

Test the classifier.

Use just one specific classifier to get the probabilities of the input being in a class

Parameters
  • key (string) – Name of the classifier

  • Xt (numpy array) – A list of input vectors which are to be classified.

Returns

Return type

Output space approximation as numpy array

test_classifiers(Xt)[source]

Use the classifiers.

Parameters

Xt (numpy array) – A list of input vectors which are to be classified.

test_interpolator(Xt)[source]

Use the interpolator to approximate output vector.

Parameters

Xt (numpy array) – A list of input vectors for which the output vectors are to be approximated.

Returns

Return type

Output space approximation as numpy array

train_classifier(grid, key, method='kNN', **options)[source]

Train a specific classifier.

gridPSyGrid

The training grid

methodstring

Specifies the classification method, default is kNN

train_classifiers(grid, method='kNN', **options)[source]

Train the classifiers.

gridPSyGrid

The training grid

methodstring

Specifies the classification method, default is kNN

train_interpolator(ic=None)[source]

Train the interpolator.

Parameters

ic (numpy array) – Contains the interpolation class for each track in the grid used for training the interpolator.

class posydon.interpolation.IF_interpolation.Classifier[source]

Bases: object

Class used as a shell parent class for all classifiers.

Initialize the Classifier.

predict(Xt)[source]

Classify and approximate classes given input vectors.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

predict_prob(Xt)[source]

Classify and get probability of input vector belonging to any class.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

train(XT, yT)[source]

Train the classifier.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding classes

train_error(XT, yT)[source]

Calculate approximation error given testing data.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding classes

class posydon.interpolation.IF_interpolation.IFInterpolator(grid=None, interpolators=None)[source]

Bases: object

Class handling initial-final interpolation.

Class handling initial-final interpolation with support to interpolate certain keys by differing classes.

Initialize the IFInterpolator class.

Parameters
  • grid (PSyGrid) – The training grid

  • interpolators (list of dictionaries) – Contain parameters for the BaseIFIneterpolators to be constructed

evaluate(binary, sanitization_verbose=False)[source]

Get the output vector approximation.

Get the output vector approximation as well as all of the classifications given a Binary Star

Parameters

binary (BinaryStar) – A class which is an input vector which are to be classified and for which an output vector will be approximated.

Returns

Return type

Output space approximation as a tuple containing two dictionary

load(filename)[source]

Load a saved IFInterpolator from a .pkl file.

Parameters

filename (string) – Path to the .pkl file

save(filename)[source]

Save the interpolator to a .pkl file.

Parameters

filename (string) – Path where .pkl file will be saved

train()[source]

Train the interpolator(s) on the PSyGrid used for construction.

class posydon.interpolation.IF_interpolation.Interpolator[source]

Bases: object

Class used as a shell parent class for all Interpolators.

Initialize the Interpolator.

predict(Xt)[source]

Interpolate and approximate output vectors given input vectors.

Parameters

XT (numpy array) – List of input vectors

train(XT, YT)[source]

Train the interpolator.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding output vectors

train_error(XT, YT)[source]

Calculate approximation error given testing data.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding output vectors

class posydon.interpolation.IF_interpolation.KNNClassifier[source]

Bases: posydon.interpolation.IF_interpolation.Classifier

Class implementing K - Nearest Neighbors classifier.

Initialize the Classifier.

predict(Xt)[source]

Classify and approximate classes given input vectors.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

predict_prob(Xt)[source]

Classify and get probability of input vector belonging to any class.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

train(XT, yT, K=5)[source]

Train the classifier.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding classes

xtrain(XT, yT, **opts)[source]

Perform cross validation to find optimal k to use in classification.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding classes

class posydon.interpolation.IF_interpolation.LinInterpolator[source]

Bases: posydon.interpolation.IF_interpolation.Interpolator

Class implementing Linear Interpolation.

Initialize the Interpolator.

predict(Xt)[source]

Interpolate and approximate output vectors given input vectors.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

train(XT, YT)[source]

Train the interpolator.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding output vectors

class posydon.interpolation.IF_interpolation.MC_Interpolator(classifier, classes, methods)[source]

Bases: object

Class implementing class-wise interpolation.

Initialize the class-wise interpolation.

classifierKNNClassifier

The classifier that is used to classify input vectors

classesList of strings

The classes in question

methodsList of strings

The methods to be used to interpolate between each class of tracks

predict(Xt)[source]

Interpolate and approximate output vectors given input vectors.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

train(XT, YT, z)[source]

Train the interpolator.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding output vectors

class posydon.interpolation.IF_interpolation.MatrixScaler(norms, XT)[source]

Bases: object

Class used to scale input and output space.

Initialize the Scaler with desired scalings.

denormalize(Xn)[source]

Unscale input X.

normalize(X)[source]

Scale input X.

class posydon.interpolation.IF_interpolation.NNInterpolator[source]

Bases: posydon.interpolation.IF_interpolation.Interpolator

Class implementing Nearest Neighbor interpolation.

Initialize the Interpolator.

predict(Xt)[source]

Interpolate and approximate output vectors given input vectors.

Parameters

XT (numpy array) – List of input vectors

Returns

Return type

Output space approximation as numpy array

train(XT, YT)[source]

Train the interpolator.

Parameters
  • XT (numpy array) – List of input vectors

  • YT (numpy array) – List of corresponding output vectors

posydon.interpolation.IF_interpolation.analize_nans(out_keys, YT, valid)[source]

Find nans in input numerical variables.

posydon.interpolation.IF_interpolation.analize_nones(classifiers, valid, grid)[source]

Find None values in input categorical variables.

posydon.interpolation.IF_interpolation.assess_models(models, grid_T, grid_t, ux2, path='./')[source]

Assess models using a grid.

Parameters
  • models (psi.Interpolator or list of psi.Interpolator) – Models to be evaluated.

  • grid_T (psg.PSyGrid) – Train grid

  • grid_t (psg.PSyGrid) – Test grid

posydon.interpolation.IF_interpolation.heatmap(CM, ax, **heat_kwargs)[source]

Plot confusion matrix as heatmap.

posydon.interpolation.IF_interpolation.is_in_ball(x, x0, ux, log)[source]

Helper function for plot_mc_classifier.

posydon.interpolation.IF_interpolation.plot_conf_matrix(CM, method, varname, labels, savename=None, **kwargs)[source]

Plot confusion matrix for classification assessment.

posydon.interpolation.IF_interpolation.plot_interp_error(Ygt, Ys, ind_MT, methods, keys, path='.')[source]

Make violin plots for the error distributions of each of the variables.

Parameters
  • Ygt (numpy array) – Ground truth of the final values of testing tracks

  • Ys (numpy array) – Model’s approximation of the final values of testing tracks

  • methods (List of strings) – List that indicates the interpolation methods

  • keys (List of strings) – List indicating for which variables error distributions will be plotted

posydon.interpolation.IF_interpolation.plot_interpolation(m, keys, v2, ux2, scales=None, path=None, **pltargs)[source]

Plot the interpolation errors by key.

Parameters
  • m (IFInterpolator) – A trained instance of the IFInterpolator

  • keys (List of strings) – Variables for which interpolation errors will be plotted

posydon.interpolation.IF_interpolation.plot_mc_classifier(m, key, XT, zT, ux2, Xt=None, zt=None, zt_pred=None, path=None, **pltargs)[source]

Plot slices illustrating decision boundaries and classification prob.

posydon.interpolation.IF_interpolation.test_mesh(XT, N)[source]

Helper function for plot_mc_classifier creating mesh for test data.

posydon.interpolation.IF_interpolation.train_and_assess(grid_train, grid_test, ux2, path, classes)[source]

Train interpolators and classes and create assesment plots.

Parameters
  • grid_train (string) – Path to training grid

  • grid_test (string) – Path to testing grid

  • ux2 (list of floats) – List containing the slices at which plots are to be generated. Slices are the 3rd variable in the input space, that is the mass of the second star for CO-HeMS and CO-HMS_RLO grids and the mass ratio for the HMS-HMS grid

  • path (string) – The path where assesment plots will be saved

  • classes (list of strings) – List containing the classes to be used in the MC-Interpolator

posydon.interpolation.IF_interpolation.xval_indices(N, percent_test=0.15, labels=None)[source]

Perform Monte Carlo Cross Validation; stratified if labels are provided.

Parameters
  • N (int) – number of samples in the data set.

  • percent_test (float) – Percentage of samples to be in the test sets. (0 < percent_test < 0.5)

Returns

1D int vectors containing the indices for train and test splits, respectively.

Return type

(np.ndarray, np.ndarray)