Feature Selection Toolbox FST4
UTIA · Czech Academy of Sciences
Loading...
Searching...
No Matches
search_exhaustive.hpp
Go to the documentation of this file.
1#ifndef FSTSEARCHEXHAUSTIVE_H
2#define FSTSEARCHEXHAUSTIVE_H
3 /*
27=========================================================================
28Copyright and license:
29 * FST4 software (with the exception of any bundled or externally linked
30 third-party components) is Copyright (C) 2000-present Institute of
31 Information Theory and Automation of the Czech Academy of Sciences (UTIA).
32 * FST4 is free software: you can redistribute it and/or modify it under
33 the terms of the GNU Affero General Public License as published by the
34 Free Software Foundation, version 3. The full text of the license is in
35 the file LICENSE in the distribution root and at
36 https://www.gnu.org/licenses/agpl-3.0.html.
37 * FST4 is distributed in the hope that it will be useful, but WITHOUT ANY
38 WARRANTY; without even the implied warranty of MERCHANTABILITY or
39 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
40 License for more details.
41 * Closed-source use without the AGPL's copyleft obligations requires a
42 commercial license from UTIA; in case of interest write to
43 utia@utia.cas.cz. LICENSING.md in the distribution root explains both
44 options, the contributor license agreement that every contribution
45 requires, and the contacts (technical questions and pull requests:
46 somol@utia.cas.cz, with "FST" in the subject line).
47========================================================================== */
48
49#include <memory>
50#include <cassert>
51#include <iostream>
52#include <sstream>
53#include <ctime>
54#include "error.hpp"
55#include "global.hpp"
56#include "stopwatch.hpp"
57#include "search.hpp"
58#include "result_tracker.hpp"
61
62/*============== Template parameter type naming conventions ==============
63--------- Numeric types: -------------------------------------------------
64DATATYPE - data sample values - usually real numbers (but may be integers
65 in text processing etc.)
66REALTYPE - must be real numbers - for representing intermediate results of
67 calculations like mean, covariance etc.
68IDXTYPE - index values for enumeration of data samples - (nonnegative) integers,
69 extent depends on numbers of samples in data
70DIMTYPE - index values for enumeration of features (dimensions), or classes (not
71 class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE,
72 but be aware of expressions like _classes*_features*_features !
73 in linearized representations of feature matrices for all classes
74BINTYPE - feature selection marker type - represents ca. <10 different feature
75 states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)
76RETURNTYPE - criterion value: real value, but may be extended in future to support
77 multiple values
78--------- Class types: ---------------------------------------------------
79SUBSET - class of class type Subset
80CLASSIFIER - class implementing interface defined in abstract class Classifier
81EVALUATOR - class implementing interface defined in abstract class Sequential_Step
82DISTANCE - class implementing interface defined in abstract class Distance
83DATAACCESSOR - class implementing interface defined in abstract class Data_Accessor
84INTERVALCONTAINER - class of class type Data_Intervaller
85CONTAINER - STL container of class type Data_Interval
86========================================================================== */
87
88namespace FST {
89
106
107template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
108class Search_Exhaustive : public Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>{
109public:
110 typedef Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION> parent;
111 typedef std::shared_ptr<CRITERION> PCriterion;
112 typedef std::shared_ptr<SUBSET> PSubset;
114 typedef std::shared_ptr<EVALUATORENGINE> PEvaluatorEngine;
117 explicit Search_Exhaustive(PEvaluatorEngine engine=PEvaluatorEngine()):Search<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>(),_engine(engine) {
119 notify("Search_Exhaustive constructor.");
120 }
121 virtual ~Search_Exhaustive() {notify("Search_Exhaustive destructor.");}
122
123 // NOTE: crit is expected to be already initialize()d before use here
125 virtual bool search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream& os=std::cout) override;
126
127 virtual std::ostream& print(std::ostream& os) const override {
128 os << "Exhaustive search [";
129 if(_engine->is_threaded()) os << "Search_Exhaustive(threads="<<_engine->get_max_threads()<<")";
130 else os << "Search_Exhaustive()";
131 if(parent::result_tracker_active()) os << " with " << *parent::_tracker;
132 os<<"]"; return os;
133 }
134protected:
136};
137
138template<class RETURNTYPE, typename DIMTYPE, class SUBSET, class CRITERION>
139bool Search_Exhaustive<RETURNTYPE,DIMTYPE,SUBSET,CRITERION>::search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream& os) // returns found subset + criterion value
140{
141 StopWatch swatch;
142 notify("Search_Exhaustive::search().");
143 assert(sub);
144 assert(crit);
145 assert(_engine);
146 const DIMTYPE n=sub->get_n();
147 assert(target_d<=n);
148
149 bool track=parent::result_tracker_active(); if(track) parent::_tracker->set_output_detail(parent::get_output_detail());
150
152 msgbuf sos;
153 sos << "---------------------------------------" << std::endl;
154 sos << "Starting " << *this << std::endl;
155 sos << "with Criterion: " << *crit << std::endl;
156 if(target_d==0) sos << "Subset size to be optimized." << std::endl; else sos << "Target subset size set to: " << target_d << std::endl;
157 sos << std::endl << std::flush;
158 this->report(os,sos);
159 }
160
161 // stream all candidate subsets of each considered cardinality to the engine
162 DIMTYPE t_to=n;
163 DIMTYPE cardinality=1;
164 if(target_d>0) {cardinality=target_d; t_to=target_d;}
165 bool generate_first=true;
166 bool generator_failed=false; // set if the subset object cannot start enumerating candidates of the current cardinality at all (e.g. cardinality>n); such a run yields no result and search() returns false
167 PSubset gen_sub(new SUBSET(n));
168 typename EVALUATORENGINE::Generator generator=[&gen_sub,&cardinality,&generate_first,&generator_failed,t_to](SUBSET &cand)->bool {
169 for(;;) {
170 if(generate_first) {
171 if(cardinality>t_to) return false;
172 gen_sub->deselect_all();
173 if(!gen_sub->getFirstCandidateSubset(cardinality,false/*reverse*/)) {generator_failed=true; return false;} // no candidate subsets can be traversed for whatever reason
174 generate_first=false;
175 cand.stateless_copy(*gen_sub);
176 return true;
177 }
178 if(gen_sub->getNextCandidateSubset()) {cand.stateless_copy(*gen_sub); return true;}
179 ++cardinality; // all candidates of current cardinality generated - move on
180 generate_first=true;
181 }
182 };
183
184 typename EVALUATORENGINE::BetterPredicate better=[](const RETURNTYPE val, const PSubset&, const RETURNTYPE bestval, const PSubset&)->bool {return val>bestval;};
185
186 typename EVALUATORENGINE::BestCallback on_best;
188 StopWatch *psw=&swatch;
189 std::ostream *pos=&os;
190 // both engines fire this on the master thread in generation order (tidx==-1),
191 // so threaded output matches sequential output
192 on_best=[this,psw,pos](const int /*tidx*/, const unsigned long long /*ordinal*/, const RETURNTYPE val, const PSubset &bsub) {
193 msgbuf sos;
194 sos << "new MAXCRIT="<<val<<", " << *bsub << std::endl << *psw << std::endl << std::endl << std::flush;
195 this->report_solution(*pos,val,*bsub,sos);
196 };
197 }
198
199 bool found=_engine->evaluate_stream(generator, crit, track? parent::_tracker : typename parent::PResultTracker(), better, on_best, result, sub);
200 if(generator_failed || !found) return false;
201
203 msgbuf sos;
204 sos << "......................................." << std::endl;
205 if(_engine->is_threaded()) sos << "Search_Exhaustive_Threaded() search finished. " << swatch << std::endl;
206 else sos << "Search_Exhaustive() search finished. " << swatch << std::endl;
207 sos << "Search result: "<< std::endl << *sub << std::endl << "Criterion value: " << result << std::endl << std::endl << std::flush;
208 this->report(os,sos);
209 }
210 return true;
211}
212
213} // namespace
214#endif // FSTSEARCHEXHAUSTIVE_H ///:~
Abstract candidate-evaluation strategy: the seam through which one search algorithm body evaluates ca...
Implements sequential in-line evaluation of a criterion on a set of subset candidates.
Implements sequential in-line evaluation of a criterion on a set of subset candidates.
Definition candidate_evaluator_sequential.hpp:62
Abstract candidate-evaluation strategy (sequential-inline vs. thread-pooled).
Definition candidate_evaluator.hpp:86
std::function< bool(SUBSET &)> Generator
fills sub with the next candidate, returns false when no candidate remains (in the threaded implement...
Definition candidate_evaluator.hpp:92
std::function< bool(const RETURNTYPE, const PSubset &, const RETURNTYPE, const PSubset &)> BetterPredicate
returns true if (value,subset) is better than (best value,best subset) - encodes per-search tie-break...
Definition candidate_evaluator.hpp:99
std::function< void(const int, const unsigned long long, const RETURNTYPE, const PSubset &)> BestCallback
Definition candidate_evaluator.hpp:97
Implements exhaustive (optimal) search yielding optimal feature subset with respect to chosen criteri...
Definition search_exhaustive.hpp:108
virtual std::ostream & print(std::ostream &os) const override
writes a human-readable identification of the search and its configuration; base default writes nothi...
Definition search_exhaustive.hpp:127
PEvaluatorEngine _engine
the injected candidate-evaluation engine (defaults to sequential)
Definition search_exhaustive.hpp:135
std::shared_ptr< EVALUATORENGINE > PEvaluatorEngine
shared pointer to the evaluation engine
Definition search_exhaustive.hpp:114
std::shared_ptr< CRITERION > PCriterion
shared pointer to the criterion being optimized
Definition search_exhaustive.hpp:111
Search_Exhaustive(PEvaluatorEngine engine=PEvaluatorEngine())
Constructs the search with the given candidate-evaluation engine; a default-constructed engine falls ...
Definition search_exhaustive.hpp:117
std::shared_ptr< SUBSET > PSubset
shared pointer to a feature subset
Definition search_exhaustive.hpp:112
virtual bool search(const DIMTYPE target_d, RETURNTYPE &result, const PSubset sub, const PCriterion crit, std::ostream &os=std::cout) override
evaluates every subset of the requested size (every subset of any size from 1 to n if target_d==0) an...
Definition search_exhaustive.hpp:139
Candidate_Evaluator< RETURNTYPE, DIMTYPE, SUBSET, CRITERION > EVALUATORENGINE
the candidate-evaluation engine type (sequential or threaded)
Definition search_exhaustive.hpp:113
Search< RETURNTYPE, DIMTYPE, SUBSET, CRITERION > parent
base class: the generic search interface
Definition search_exhaustive.hpp:110
bool output_normal() const
true unless output detail is SILENT
Definition search.hpp:159
void report(std::ostream &os, const msgbuf &m) const
delivers one pre-formatted progress message: to the observer if attached, otherwise as syncout text t...
Definition search.hpp:170
bool result_tracker_active() const
true if a result tracker was assigned via enable_result_tracking() and not since disabled
Definition search.hpp:155
OutputDetail get_output_detail() const
the currently configured output detail level
Definition search.hpp:158
std::shared_ptr< Result_Tracker< RETURNTYPE, SUBSET > > PResultTracker
shared pointer to the result tracker enabled via enable_result_tracking()
Definition search.hpp:128
PResultTracker _tracker
the assigned result tracker, or null (see enable_result_tracking()/result_tracker_active())
Definition search.hpp:179
void report_solution(std::ostream &os, const RETURNTYPE value, const SUBSET &sub, const msgbuf &m) const
like report(), for sites announcing a new (sub-)solution; fires on_solution instead
Definition search.hpp:175
Simple stopwatch to measure run time of search algorithms.
Definition stopwatch.hpp:92
Message accumulator for Search::report() - collects one progress message exactly as an std::ostringst...
Definition search.hpp:87
FST4 specific error passing class.
Global definitions.
The Feature Selection Toolbox 4 library: every library component – data access, criteria and classifi...
Definition data_accessor.hpp:80
void notify(const std::string msg)
Prints msg followed by a newline via syncout::print(); a no-op unless the preprocessor macro DEBUG is...
Definition global.hpp:112
Defines interface for classes that enable collecting multiple results.
Defines interface for search method implementations.
Simple tool to measure run time.
Copyright © 2000–present ÚTIA, Institute of Information Theory and Automation of the Czech Academy of Sciences · Contacts · This site sets no cookies and uses no analytics.