posydon.interpolation
posydon.interpolation.IF_interpolation
Module for performing initial-final inteprolation.
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. Note that when using class-wise normalization only classes in interp_classes are normalized. This is the behavior for interpolation normalization but not classification normalization.
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.
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”, “linear”], “interp_classes”: [“no_MT”, “stable_MT”, “unstable_MT”, “stable_reverse_MT”], # classes not in this array will not be normalized in class-wise normalization “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”], # classes not in this array will not be normalized in class-wise normalization “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”], # classes not in this array will not be normalized in class-wise normalization “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”], # classes not in this array will not be normalized in class-wise normalization “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”], # classes not in this array will not be normalized in class-wise normalization “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”], # classes not in this array will not be normalized in class-wise normalization “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,
# 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, out_nan_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.
out_nan_keys (list of strings) – The keys for which the interpolator is supposed to provide values, but are all nan in the grid.
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.
- 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.
- 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.
- 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.
- 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.
- 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
- 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
- Return type:
Output space approximation as numpy array
- 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:
- 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.
- 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
- test_classifiers(initial_values)[source]
Method that can take in a 2-D numpy array for more efficient use of classifiers
- Parameters:
initial_values (numpy array) – A numpy array containing the in-key values of the binaries to be classified
- Return type:
Classified values
- test_interpolator(initial_values, sanitization_verbose=False)[source]
Method that can take in a 2-D numpy array for more efficient use of the interpolator
- Parameters:
initial_values (numpy array) – A numpy array containing the in-key values of the binaries to be evolved
- Return type:
Interpolated values
- 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
- class posydon.interpolation.IF_interpolation.KNNClassifier[source]
Bases:
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
- 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
- Return type:
Output space approximation as numpy array
- class posydon.interpolation.IF_interpolation.LinInterpolator[source]
Bases:
Interpolator
Class implementing Linear Interpolation.
Initialize the Interpolator.
- 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
- 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.
- class posydon.interpolation.IF_interpolation.NNInterpolator[source]
Bases:
Interpolator
Class implementing Nearest Neighbor interpolation.
Initialize the Interpolator.
- 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
ux2 (#TODO)
path (#TODO)
- 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
ind_MT (#TODO)
methods (List of strings) – List that indicates the interpolation methods
keys (List of strings) – List indicating for which variables error distributions will be plotted
path (#TODO)
- 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
v2 (#TODO)
ux2 (#TODO)
scales (#TODO)
path (#TODO)
- 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.constraints
Module to enforce constraints on interpolated quantities.
Constraints are split up into 3 types:
Astrophysical laws that must hold
Inequalities between values interpolated upon which must hold
Sums of values interpolated upon which must satisfy some inequality
For each type of constraint, different parameter dictionaries are required.
For type 1 constraints a dictionary with the following fields is required:
type - the type of constraint name - the name of the constraint dependent - the field for which the constraint must be calculated independent - the field names which are used to compute the dependent function - a function that computes the dependent from the independent
For type 2 constraints a dictionary with the following fields is required:
type - the type of constraint name - the name of the constraint fields - a multi dimensional array containing the field names in the
desired descending order (if usage with default enforcer is wanted)
- log - a boolean denoting whether or not the largest (first) field in
each constraint list is in log scale (by default false)
- function - a function that enforces the desired constraint (by default
inequality is corrected)
For type 3 constraints a dictionary with the following fields is required:
type - the type of constraint name - the name of the constraint sum - an array of fields whose sum needs to satisfy some inequality constraint - either a real number or fieldname that the sum needs to be
constrained by
- posydon.interpolation.constraints.Lnuc_func(log_LH, log_LHe, log_LZ)[source]
Total nuclear luminosity should be the sum of H, He and the rest.
- posydon.interpolation.constraints.boltzman_constraint_func(log_L, log_R)[source]
Boltzmann law constraint.
- posydon.interpolation.constraints.check_order_of_constraints()[source]
Report possible issues with the order of application of constraints.
TODO: this needs to be updated for the new types of constraints.
- posydon.interpolation.constraints.correct_inequality(fv_dict, key_sets, star, log=False)[source]
Apply an “unequality constraint” (type 2) if needed.
- Parameters:
fv_dict (dict) – The final values dictionary.
key_sets (list of lists) – List of collections of keys connected with >= inequalities (descending order). E.g., if one constraint is a >= b >= c, then key_sets is [[a, b, c], …].
star (int) – For which star (1 or 2), the constraint will be applied. E.g., star_{}_mass will be either star_1_mass or star_2_mass.
log (bool) – If True, then the largest parameter (first key), is given in log10 scale, while all the rest are in linear scale.
- Returns:
The sanitized version of fv_dict.
- Return type:
- posydon.interpolation.constraints.correct_sum(fv_dict, sum_keys, constraint)[source]
Normalize quantities should their sum does not have the expected value.
- Parameters:
- Returns:
The sanitized version of the final values dictionary.
- Return type:
- posydon.interpolation.constraints.find_constraints_to_apply(out_keys)[source]
Find out which constraints can be applied.
Find out which constraints can be applied based on the out_keys specified by the user. This function assumes that the keys for star 1 have a corresponding key in star 2 when applicable.
- posydon.interpolation.constraints.get_thickness_n_radius(fv_dict, constraint, keys)[source]
Corrects thickness and radius constraint violation of one is present.
- posydon.interpolation.constraints.kepler_3rd_law_func(period_days, mass1, mass2)[source]
Kepler’s 3rd law constraint.
- posydon.interpolation.constraints.lg_system_mdot_func(lg_system_mdot, lg_mtransfer_rate)[source]
System mdot must be less than the total mass-transfer rate.
- posydon.interpolation.constraints.sanitize_interpolated_quantities(fvalues, constraints, verbose=False)[source]
Apply constraints in final values returned from the IF interpolator.
- Parameters:
fvalues (dict) – Dictionary containing the final values returned from the initial-final interpolator evaluation method.
constraints (list of dicts) – A list of constraints that are to be applied. Can be computed using the find_constraints_to_apply function
verbose (bool) – If True, report the actions.
- Returns:
The dictionary of sanitized final values.
- Return type:
posydon.interpolation.data_scaling
Module for scaling data before and after interpolation.
- class posydon.interpolation.data_scaling.DataScaler[source]
Bases:
object
Data Normalization class.
This class provides normalizing tools for float 1D arrays. Features can be standarized or scaled to a range depending on the method chosen when calling the fit ot fit_and_transform functions.
Initialize the data scaler.
No parameters are expected. After instantiation use methods fit or fit_and_transform first to fit a scaling object to a given vector of values.
Example
>>> sc = DataScaler()
- fit(x, method='none', lower=-1.0, upper=1.0)[source]
Fit a transform of 1D numpy array x.
Computes the parameters that define the transform.
- Parameters:
x (numpy.ndarray) – expects a 1D array and finds norm values of columns
method (str) – Scaling method. Possible values: ‘min_max’, ‘max_abs’, ‘standarize’ and their log versions ‘log_min_max’, ‘neg_log_min_max’, ‘log_max_abs’, ‘log_standarize’, ‘neg_log_standarize’.
lower (float) – lower range value of x_t after (log_)min_max scaling
upper (float) – upper range value of x_t after (log_)min_max scaling
- fit_and_transform(x, method='none', lower=-1, upper=1)[source]
Fit and transform the array x according to the chosen scaling.
lower/upper will only be taken into account for (log_)min_max normalization. In this case, the transformed x will have min(x_transf) = lower, max(x_transf) = upper
- Parameters:
x (numpy.ndarray) – expects a 1D array and finds norm values of columns
method (str) – scaling method. Possible values: ‘min_max’, ‘max_abs’, ‘standarize’ and the log versions ‘log_min_max’, ‘log_max_abs’, ‘log_standarize’
lower (float) – lower range value of x_t after (log_)min_max scaling
upper (float) – upper range value of x_t after (log_)min_max scaling
- Returns:
transformed version of x
- Return type:
- inv_transform(x_t)[source]
Revert the scaling using the stored transform parameters.
- Parameters:
x_t (numpy.ndarray) – expects a 1D array to unnormalize given the fitted transform.
- Returns:
denormalized x using the stored parameters.
- Return type:
- transform(x)[source]
Transform x using the already obtained normalization values.
self.fit()` must be called first. lower/upper will only be taken into account for (log_)min_max normalization. In this case, the transformed x will have min(x_transf) = lower, max(x_transf) = upper
- Parameters:
x (numpy.ndarray) – values to normalize
- Returns:
transformed version of x
- Return type:
posydon.interpolation.eep
Module for converting a MESA history file to an EEP track.
Reference: Dotter, Aaron (2016), AJSS, 222, 1.
posydon.interpolation.interpolation
Definition of the psyTackInterp class.
- class posydon.interpolation.interpolation.GRIDInterpolator(path, verbose=False)[source]
Bases:
object
Class to interpolate between single star MESA tracks.
Initialize the GRIDInterpolator.
- posydon.interpolation.interpolation.fscale(u, lim=None, inv=False)[source]
Successively perform min-max rescaling on the last dimension of u.
- Parameters:
u (array_like) – The array which last dimension requires min-max rescaling.
lim (sequence of tuple) – The tuples have length 2 and contains the limits on the min-max rescaling. There should be one tuple for each array in the last dimension.
inv (bool) – If False then the standard min-max rescaling will be performed. If True then the inverse min-max rescaling to restore and array will be performed.
- Returns:
The rescaled/original array with the same shape as u.
- Return type:
ndarray
- posydon.interpolation.interpolation.inv_scaler(x, xmin, xmax)[source]
Restore the original array of min-max rescaled array.
- class posydon.interpolation.interpolation.psyTrackInterp(path, in_keys=None, interp_in_q=False, verbose=False)[source]
Bases:
object
Perform track interpolation for POSYDON.
Initialize the psyTrackInterp class.
- Parameters:
path (string) – The path to the training grid for the interpolator
in_keys (List of strings) – A list indicating the variables used for defining the input space, default is None
interp_in_q (boolean) – Indicates whether or not mass ratio is to be used, default is false
verbose (boolean) – Indicates whether functionality should be run in verbose mode, default is false
- load(filename)[source]
Load interpolation model to be used for predictions.
- filenamestr
path/name of pickle file to be loaded.