FeatureSpace.hpp 19 KB
Newer Older
1
// Copyright 2021 Thomas A. R. Purcell
2
//
3
4
5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
10
11
12
13
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
14

15
/** @file feature_creation/feature_space/FeatureSpace.hpp
16
 *  @brief Defines the class for creating/operating on a feature space in SISSO
17
 *
18
 *  @author Thomas A. R. Purcell (tpurcell90)
19
20
21
 *  @bug No known bugs.
 */

Thomas Purcell's avatar
Thomas Purcell committed
22
23
24
#ifndef FEATURE_SPACE
#define FEATURE_SPACE

25
#include <boost/filesystem.hpp>
Thomas Purcell's avatar
Thomas Purcell committed
26

27
#include <utility>
Thomas Purcell's avatar
Thomas Purcell committed
28

Thomas Purcell's avatar
Thomas Purcell committed
29
#include "feature_creation/node/utils.hpp"
30
#include "inputs/InputParser.hpp"
Thomas Purcell's avatar
Thomas Purcell committed
31
32

#include "mpi_interface/MPI_Interface.hpp"
33
#include "mpi_interface/MPI_Ops.hpp"
Thomas Purcell's avatar
Thomas Purcell committed
34
35
#include "mpi_interface/serialize_tuple.h"

Thomas Purcell's avatar
Thomas Purcell committed
36
#include "utils/project.hpp"
37
#include "mpi_interface/MPI_Interface.hpp"
Thomas Purcell's avatar
Thomas Purcell committed
38

39
40
41
42
#ifdef PY_BINDINGS
    namespace np = boost::python::numpy;
    namespace py = boost::python;
#endif
43

44
// DocString: cls_feat_space
45
/**
46
 * @brief Feature Space for SISSO calculations. It stores and performs all actions on the feature space for SISSO.
47
48
 *
 */
Thomas Purcell's avatar
Thomas Purcell committed
49
50
class FeatureSpace
{
Thomas Purcell's avatar
Thomas Purcell committed
51
52
    std::vector<node_ptr> _phi_selected; //!< A vector containing all of the selected features
    std::vector<node_ptr> _phi; //!< A vector containing all features generated (Not including those created on the Fly during SIS)
53
    std::vector<node_ptr> _phi_0; //!< A vector containing all of the Primary features
54

55
    #ifdef PARAMETERIZE
Thomas Purcell's avatar
Thomas Purcell committed
56
57
58
59
60
61
62
63
    std::vector<node_ptr> _phi_reparam; //!< A vector containing the features created when reparameterizating using the residuals
    std::vector<int> _end_no_params; //!< A vector containing the indexes of each rung where parameterized nodes start
    std::vector<int> _start_rung_reparam; //!< A vector containing the indexes of each rung where parameterized nodes start

    std::vector<un_param_op_node_gen> _un_param_operators; //!< Vector containing all parameterized unary operators with free parameters
    std::vector<bin_param_op_node_gen> _com_bin_param_operators; //!< Vector containing all parameterized commutable binary operators with free parameters
    std::vector<bin_param_op_node_gen> _bin_param_operators; //!< Vector containing all parameterized binary operators with free parameters
    std::vector<std::string> _allowed_param_ops; //!< Vector containing all allowed operators strings for operators with free parameters
64
    #endif
65

Thomas Purcell's avatar
Thomas Purcell committed
66
67
68
69
    std::vector<std::string> _allowed_ops; //!< Vector containing all allowed operators strings
    std::vector<un_op_node_gen> _un_operators; //!< Vector containing all unary operators
    std::vector<bin_op_node_gen> _com_bin_operators; //!< Vector containing all commutable binary operators
    std::vector<bin_op_node_gen> _bin_operators; //!< Vector containing all binary operators
70

71
    std::vector<double> _prop_train; //!< The value of the property vector for each training sample
Thomas Purcell's avatar
Thomas Purcell committed
72
    std::vector<double> _scores; //!< The projection scores for each feature
73

74
    const std::vector<int> _task_sizes_train; //!< Number of training samples per task
Thomas Purcell's avatar
Thomas Purcell committed
75
76
77
78
    std::vector<int> _start_rung; //!< Vector containing the indexes where each rung starts in _phi
    const std::string _project_type; //!< The type of LossFunction to use when projecting the features onto a property
    const std::string _feature_space_file; //!< File to output the computer readable representation of the selected features to
    const std::string _feature_space_summary_file; //!< File to output the human readable representation of the selected features to
79

Thomas Purcell's avatar
Thomas Purcell committed
80
81
    std::function<bool(const double*, const int, const double, const std::vector<double>&, const double, const int, const int)> _is_valid; //!< Function used to determine of a feature is too correlated to previously selected features
    std::function<bool(const double*, const int, const double, const std::vector<node_ptr>&, const std::vector<double>&, const double)> _is_valid_feat_list; //!< Function used to determine of a feature is too correlated to previously selected features within a given list
82

Thomas Purcell's avatar
Thomas Purcell committed
83
    std::shared_ptr<MPI_Interface> _mpi_comm; //!< the MPI communicator for the calculation
84

85
    const double _cross_cor_max; //!< Maximum cross-correlation used for selecting features
Thomas Purcell's avatar
Thomas Purcell committed
86
87
    const double _l_bound; //!< The lower bound for the maximum absolute value of the features
    const double _u_bound; //!< The upper bound for the maximum absolute value of the features
88

Thomas Purcell's avatar
Thomas Purcell committed
89
90
91
    int _n_rung_store; //!< The number of rungs to calculate and store the value of the features for all samples
    int _n_feat; //!< Total number of features in the feature space
    int _max_rung; //!< Maximum rung for the feature creation
92

Thomas Purcell's avatar
Thomas Purcell committed
93
    const int _n_sis_select; //!< Number of features to select during each SIS iteration
94
    const int _n_samp_train; //!< Number of samples in the training set
Thomas Purcell's avatar
Thomas Purcell committed
95
    const int _n_rung_generate; //!< Either 0 or 1, and is the number of rungs to generate on the fly during SIS
96

97
    #ifdef PARAMETERIZE
Thomas Purcell's avatar
Thomas Purcell committed
98
    int _max_param_depth; //!< The maximum depth in the binary expression tree to set non-linear optimization
99
100
    bool _reparam_residual; //!< If True then reparameterize features using the residuals of each model
    #endif
Thomas Purcell's avatar
Thomas Purcell committed
101
public:
Thomas Purcell's avatar
Thomas Purcell committed
102

103
    // DocString: feat_space_init
104
    /**
105
     * @brief Construct a FeatureSpace using an InputParser object
106
     *
107
     * @param inputs InputParser object used to build the FeatureSpace
108
     */
109
    FeatureSpace(InputParser inputs);
110

111
    /**
Thomas Purcell's avatar
Thomas Purcell committed
112
     * @brief Populate the operator lists using _allowed_ops and _allowed_param_ops
113
114
115
116
     */
    void set_op_lists();

    /**
Thomas Purcell's avatar
Thomas Purcell committed
117
     * @brief Create SIS output files and write their headers
118
     */
119
    void initialize_fs_output_files() const;
Thomas Purcell's avatar
Thomas Purcell committed
120

121
    /**
Thomas Purcell's avatar
Thomas Purcell committed
122
     * @brief Populate _phi using _phi_0 and the allowed operators up to (_max_rung - _n_rung_generate)^th rung
123
     */
Thomas Purcell's avatar
Thomas Purcell committed
124
125
126
127
128
129
    void generate_feature_space(
        std::vector<node_ptr>& feat_set,
        std::vector<int>& start_rung,
        const std::vector<double>& prop,
        bool reparam = false
    );
Thomas Purcell's avatar
Thomas Purcell committed
130

131
    /**
Thomas Purcell's avatar
Thomas Purcell committed
132
     * @brief A vector containing all of the selected features
133
     */
134
    inline std::vector<node_ptr> phi_selected() const {return _phi_selected;};
135
136

    /**
Thomas Purcell's avatar
Thomas Purcell committed
137
     * @brief A vector containing all features generated (Not including those created on the Fly during SIS)
138
     */
139
    inline std::vector<node_ptr> phi() const {return _phi;};
140
141

    /**
Thomas Purcell's avatar
Thomas Purcell committed
142
     * @brief A vector containing all of the Primary features
143
     */
144
    inline std::vector<node_ptr> phi0() const {return _phi_0;};
145
146

    /**
Thomas Purcell's avatar
Thomas Purcell committed
147
     * @brief The projection scores for each feature in _phi
148
     */
149
    inline std::vector<double> scores() const {return _scores;}
150

151
    /**
152
     * @brief The MPI Communicator
153
     */
154
    inline std::shared_ptr<MPI_Interface> mpi_comm() const {return _mpi_comm;}
155

156
    /**
Thomas Purcell's avatar
Thomas Purcell committed
157
     * @brief Number of training samples per task
158
     */
159
    inline std::vector<int> task_sizes_train() const {return _task_sizes_train;}
160

161
    // DocString: feat_space_feature_space_file
162
    /**
Thomas Purcell's avatar
Thomas Purcell committed
163
     * @brief Filename of the file to output the computer readable representation of the selected features to
164
     */
165
    inline std::string feature_space_file() const {return _feature_space_file;}
166

Thomas Purcell's avatar
Thomas Purcell committed
167
168
169
170
171
172
    // DocString: feat_space_feature_space_file
    /**
     * @brief Filename of the file to output the human readable representation of the selected features to
     */
    inline std::string feature_space_summary_file() const {return _feature_space_summary_file;}

173
    // DocString: feat_space_l_bound
174
    /**
Thomas Purcell's avatar
Thomas Purcell committed
175
     * @brief The mlower bound for the maximum absolute value of the features
176
     */
177
    inline double l_bound() const {return _l_bound;}
178

179
    // DocString: feat_space_u_bound
180
    /**
Thomas Purcell's avatar
Thomas Purcell committed
181
     * @brief The upper bound for the maximum absolute value of the features
182
     */
183
    inline double u_bound() const {return _u_bound;}
184

Thomas Purcell's avatar
Thomas Purcell committed
185
    // DocString: feat_space_max_rung
186
    /**
Thomas Purcell's avatar
Thomas Purcell committed
187
     * @brief The maximum rung for the feature creation
188
     */
Thomas Purcell's avatar
Thomas Purcell committed
189
    inline int max_rung() const {return _max_rung;}
190

191
    // DocString: feat_space_n_sis_select
192
    /**
Thomas Purcell's avatar
Thomas Purcell committed
193
     * @brief The number of features to select during each SIS iteration
194
     */
195
    inline int n_sis_select() const {return _n_sis_select;}
196

197
    // DocString: feat_space_n_samp_train
198
    /**
Thomas Purcell's avatar
Thomas Purcell committed
199
     * @brief The nuumber of samples in the training set
200
     */
201
    inline int n_samp_train() const {return _n_samp_train;}
202

203
    // DocString: feat_space_n_feat
204
    /**
Thomas Purcell's avatar
Thomas Purcell committed
205
     * @brief The total number of features in the feature space
206
     */
207
    inline int n_feat() const {return _n_feat;}
208

209
    // DocString: feat_space_n_rung_store
210
    /**
Thomas Purcell's avatar
Thomas Purcell committed
211
     * @brief The number of rungs to calculate and store the value of the features for all samples
212
     */
213
    inline int n_rung_store() const {return _n_rung_store;}
214

215
    // DocString: feat_space_n_rung_generate
216
    /**
217
     * @brief Either 0 or 1, and is the number of rungs to generate on the fly during SIS
218
     */
219
    inline int n_rung_generate() const {return _n_rung_generate;}
220

Thomas Purcell's avatar
Thomas Purcell committed
221
222
    /**
     * @brief Generate a new set of non-parameterized features from a single feature
Thomas Purcell's avatar
Thomas Purcell committed
223
     * @details Perform all valid algebraic operations on the passed feature and all features that appear before it in _phi.
Thomas Purcell's avatar
Thomas Purcell committed
224
225
     *
     * @param feat The feature to spawn new features from
Thomas Purcell's avatar
Thomas Purcell committed
226
227
     * @param feat_set The feature set to pull features from for binary operations
     * @param start The point in feat_set to begin pulling features from for binary operations
Thomas Purcell's avatar
Thomas Purcell committed
228
     * @param feat_ind starting index for the next feature generated
Thomas Purcell's avatar
Thomas Purcell committed
229
230
     * @param l_bound lower bound for the maximum absolute value of the feature
     * @param u_bound upper bound for the maximum abosulte value of the feature
Thomas Purcell's avatar
Thomas Purcell committed
231
232
233
234
     */
    void generate_non_param_feats(
        std::vector<node_ptr>::iterator& feat,
        std::vector<node_ptr>& feat_set,
235
        const std::vector<node_ptr>::iterator& start,
Thomas Purcell's avatar
Thomas Purcell committed
236
237
238
239
240
        unsigned long int& feat_ind,
        const double l_bound=1e-50,
        const double u_bound=1e50
    );

241
#ifdef PARAMETERIZE
242
    /**
Thomas Purcell's avatar
Thomas Purcell committed
243
     * @brief Generate a new set of parameterized features from a single feature
Thomas Purcell's avatar
Thomas Purcell committed
244
     * @details Perform all valid algebraic operations on the passed feature and all features that appear before it in _phi.
245
246
     *
     * @param feat The feature to spawn new features from
Thomas Purcell's avatar
Thomas Purcell committed
247
248
     * @param feat_set The feature set to pull features from for binary operations
     * @param start The point in feat_set to begin pulling features from for binary operations
249
250
     * @param feat_ind starting index for the next feature generated
     * @param optimizer The object used to optimize the parameterized features
Thomas Purcell's avatar
Thomas Purcell committed
251
252
     * @param l_bound lower bound for the maximum absolute value of the feature
     * @param u_bound upper bound for the maximum abosulte value of the feature
253
     */
Thomas Purcell's avatar
Thomas Purcell committed
254
    void generate_param_feats(
255
256
        std::vector<node_ptr>::iterator& feat,
        std::vector<node_ptr>& feat_set,
257
        const std::vector<node_ptr>::iterator& start,
258
259
        unsigned long int& feat_ind,
        std::shared_ptr<NLOptimizer> optimizer,
260
261
        const double l_bound=1e-50,
        const double u_bound=1e50
262
    );
Thomas Purcell's avatar
Thomas Purcell committed
263

264
    /**
Thomas Purcell's avatar
Thomas Purcell committed
265
     * @brief Generate a new set of parameterized features for the residuals
266
267
     *
     * @param feat The feature to spawn new features from
Thomas Purcell's avatar
Thomas Purcell committed
268
     * @param feat_set The feature set to pull features from for binary operations
269
     * @param feat_ind starting index for the next feature generated
Thomas Purcell's avatar
Thomas Purcell committed
270
     * @param optimizer The object used to optimize the parameterized features
Thomas Purcell's avatar
Thomas Purcell committed
271
272
     * @param l_bound lower bound for the maximum absolute value of the feature
     * @param u_bound upper bound for the maximum abosulte value of the feature
273
     */
Thomas Purcell's avatar
Thomas Purcell committed
274
    void generate_reparam_feats(
275
276
277
        std::vector<node_ptr>::iterator& feat,
        std::vector<node_ptr>& feat_set,
        unsigned long int& feat_ind,
Thomas Purcell's avatar
Thomas Purcell committed
278
        std::shared_ptr<NLOptimizer> optimizer,
279
280
        const double l_bound=1e-50,
        const double u_bound=1e50
281
    );
282
#endif
283

284
    /**
Thomas Purcell's avatar
Thomas Purcell committed
285
     * @brief Generate the final rung of features on the fly and calculate their projection scores for SISat can be selected by SIS.
286
     *
Thomas Purcell's avatar
Thomas Purcell committed
287
288
289
     * @param loss The LossFunction used to project over all of the features
     * @param phi_selected The set of features that would be selected excluding the final rung
     * @param scores_selected The projection scores of all features in phi_selected
290
     */
Thomas Purcell's avatar
Thomas Purcell committed
291
    void generate_and_project(std::shared_ptr<LossFunction> loss, std::vector<node_ptr>& phi_selected, std::vector<double>& scores_selected);
292

293
    /**
294
     * @brief Perform Sure-Independence Screening over the FeatureSpace. The features are ranked using a projection operator constructed using _project_type and the Property vector
295
     *
296
     * @param prop Vector containing the property vector (training data only)
297
     */
298
    void sis(const std::vector<double>& prop);
299

Thomas Purcell's avatar
Thomas Purcell committed
300
    /**
301
     * @brief Perform Sure-Independence Screening over the FeatureSpace. The features are ranked using a projection operator defined in loss
Thomas Purcell's avatar
Thomas Purcell committed
302
     *
303
     * @param loss The LossFunction used to project over all of the features
Thomas Purcell's avatar
Thomas Purcell committed
304
305
306
     */
    void sis(std::shared_ptr<LossFunction> loss);

307
    // DocString: feat_space_feat_in_phi
308
309
310
    /**
     * @brief Is a feature in this process' _phi?
     *
311
     * @param ind (int) The index of the feature
Thomas Purcell's avatar
Thomas Purcell committed
312
     *
313
     * @return True if feature is in this rank's _phi
314
     */
315
    inline bool feat_in_phi(int ind) const {return (ind >= _phi[0]->feat_ind()) && (ind <= _phi.back()->feat_ind());}
316

317
318
319
320
    // DocString: feat_space_remove_feature
    /**
     * @brief Remove a feature from phi
     *
Thomas Purcell's avatar
Thomas Purcell committed
321
     * @param ind (int) index of feature to remove
322
     */
323
    void remove_feature(const int ind);
324

325
326
    // Python Interface Functions
    #ifdef PY_BINDINGS
Thomas Purcell's avatar
Thomas Purcell committed
327

328
    // DocString: feat_space_init_file_np_array
329
    /**
330
     * @brief FeatureSpace constructor that uses a file containing postfix feature expressions to describe all features in Phi, and a primary feature setn <python/feature_creation/FeatureSpace.cpp>)
331
     *
332
333
334
     * @param feature_file (str) The file containing the postfix expressions of all features in the FeatureSpace
     * @param phi_0 (list) The set of primary features
     * @param prop (np.ndarray) List containing the property vector (training data only)
335
     * @param task_sizes_train (list) The number of samples in the training data per task
336
337
338
     * @param project_type (str) The type of loss function/projection operator to use
     * @param n_sis_select (int) The number of features to select during each SIS step
     * @param cross_corr_max (double) The maximum allowed cross-correlation value between selected features
339
340
341
342
343
     */
    FeatureSpace(
        std::string feature_file,
        py::list phi_0,
        np::ndarray prop,
344
        py::list task_sizes_train,
Thomas Purcell's avatar
Thomas Purcell committed
345
        std::string project_type="regression",
346
347
348
349
        int n_sis_select=1,
        double cross_corr_max=1.0
    );

350
    // DocString: feat_space_init_file_py_list
351
    /**
352
     * @brief FeatureSpace constructor that uses a file containing postfix feature expressions to describe all features in Phi, and a primary feature setn <python/feature_creation/FeatureSpace.cpp>)
353
     *
354
355
356
     * @param feature_file (str) The file containing the postfix expressions of all features in the FeatureSpace
     * @param phi_0 (list) The set of primary features
     * @param prop (list) List containing the property vector (training data only)
357
     * @param task_sizes_train (list) The number of samples in the training data per task
358
359
360
     * @param project_type (str) The type of loss function/projection operator to use
     * @param n_sis_select (int) The number of features to select during each SIS step
     * @param cross_corr_max (double) The maximum allowed cross-correlation value between selected features
361
362
363
364
365
     */
    FeatureSpace(
        std::string feature_file,
        py::list phi_0,
        py::list prop,
366
        py::list task_sizes_train,
Thomas Purcell's avatar
Thomas Purcell committed
367
        std::string project_type="regression",
368
369
370
371
372
373
        int n_sis_select=1,
        double cross_corr_max=1.0
    );

    // DocString: feat_space_sis_arr
    /**
374
     * @brief Perform Sure-Independence Screening over the FeatureSpace. The features are ranked using a projection operator constructed using _project_type and the Property vector
375
     *
376
     * @param prop (np.ndarray) Array containing the property vector (training data only)
377
378
379
380
381
382
383
384
385
     */
    inline void sis(np::ndarray prop)
    {
        std::vector<double> prop_vec = python_conv_utils::from_ndarray<double>(prop);
        sis(prop_vec);
    }

    // DocString: feat_space_sis_list
    /**
386
     * @brief Perform Sure-Independence Screening over the FeatureSpace. The features are ranked using a projection operator constructed using _project_type and the Property vector
387
     *
388
     * @param prop (list) List containing the property vector (training data only)
389
390
391
392
393
394
395
396
397
     */
    inline void sis(py::list prop)
    {
        std::vector<double> prop_vec = python_conv_utils::from_list<double>(prop);
        sis(prop_vec);
    }

    // DocString: feat_space_phi_selected_py
    /**
Thomas Purcell's avatar
Thomas Purcell committed
398
     * @brief A list containing all of the selected features
399
400
401
402
403
     */
    py::list phi_selected_py();

    // DocString: feat_space_phi0_py
    /**
Thomas Purcell's avatar
Thomas Purcell committed
404
     * @brief A list containing all features generated (Not including those created on the Fly during SIS)
405
     */
Thomas Purcell's avatar
Thomas Purcell committed
406
    py::list phi_py();
407
408
409

    // DocString: feat_space_phi_py
    /**
Thomas Purcell's avatar
Thomas Purcell committed
410
     * @brief A list containing all of the Primary features
411
     */
Thomas Purcell's avatar
Thomas Purcell committed
412
    py::list phi0_py();
413
414
415

    // DocString: feat_space_scores_py
    /**
416
     * @brief An array of all stored projection scores from SIS
417
418
419
     */
    inline np::ndarray scores_py(){return python_conv_utils::to_ndarray<double>(_scores);};

420
    // DocString: feat_space_task_sizes_train_py
421
    /**
422
     * @brief A list of the number of samples in each task for the training data
423
     */
424
    inline py::list task_sizes_train_py(){return python_conv_utils::to_list<int>(_task_sizes_train);};
425
426
427

    // DocString: feat_space_allowed_ops_py
    /**
428
     * @brief The list of allowed operators
429
430
431
     */
    inline py::list allowed_ops_py(){return python_conv_utils::to_list<std::string>(_allowed_ops);}

432
433
434
435
436
437
438
439
440
441
442
443
444
    #ifdef PARAMETERIZE
    // DocString: feat_space_allowed_ops_py
    /**
     * @brief The list of allowed operators
     */
    inline py::list allowed_param_ops_py(){return python_conv_utils::to_list<std::string>(_allowed_param_ops);}
    #else
    // DocString: feat_space_allowed_ops_py
    /**
     * @brief The list of allowed operators
     */
    inline py::list allowed_param_ops_py(){return python_conv_utils::to_list<std::string>({});}
    #endif
Thomas Purcell's avatar
Thomas Purcell committed
445
    // DocString: feat_space_start_rung_py
446
    /**
447
     * @brief A list containing the index of the first feature of each rung in the feature space.
448
     */
Thomas Purcell's avatar
Thomas Purcell committed
449
    inline py::list start_rung_py(){return python_conv_utils::to_list<int>(_start_rung);}
450
451
452

    // DocString: feat_space_get_feature
    /**
453
     * @brief Access the feature in _phi with an index ind
454
     *
455
     * @param ind (int) The index of the feature to get
456
457
     * @return A ModelNode of the feature at index ind
     */
458
    inline ModelNode get_feature(const int ind) const {return ModelNode(_phi[ind]);}
459
    #endif
Thomas Purcell's avatar
Thomas Purcell committed
460
461
};

462
#endif