architecture - c++ loose coupling function dependency -
as title might suggest having hard time describing architectural problem , same reason searching has been without result. writing command line application aims take in two-dimensional data physics model can fitted means of least squares fitting. have implemented nelder-mead , levenberg-marquardt routine work properly, i.e. given set of data, model , cost function, optimize array of fitting parameters.
for purpose want write class facilitates abstract functionality of optimization, independent of actual model , cost function used.
class fit { public: fit(); ~fit(); run(); private: std::vector<std::vector<double>> m_data; std::vector<double> m_parameters; std::vector<double> m_evaluated; }
the actual optimization method run()
following:
void run() { // set initial guess parameters m_parameters = {...}; while(condition) { double cost_value; // evaluate model function current parameters (*model)(&m_evaluated, m_data, m_parameters); (*cost)(&cost_value, m_data, m_evaluated); if (cost_value < threshold_value) break; else update_parameters(&m_parameters); } }
this questions comes in. fit::run()
method needs call model
, cost
function there no knowing front these or function arguments require. arguments take in example bare minimum required arguments seen fitting procedure there might additional required arguments.
specific cost functions , model defined elsewhere have no clue how let fit
class know functions needs call. coming c
thinking function pointers have no clue how preferably done in c++
. should fit
have function pointer member m_model
has set after instantiated? spitballing here. how best approach , problem called maybe additional approaches?
edit: give better idea of trying accomplish pseudo code.
// imagine multiple available functions work differently take array of parameters // used evaluate function set of data values void model_a(std::vector<double>* y, std::vector<std::vector<double>> data, std::vector<double> p) { (int i; < data[0].size(); ++i) (*y)[i] = parameters[0] + parameters[1]*data[0][i]; }; void model_b(std::vector<double>* y, std::vector<std::vector<double>> data, std::vector<double> p) { (int i; < data[0].size(); ++i) (*y)[i] = parameters[0] - pow(data[0][i], parameters[1]); }; // assume have data std::vector<std::vector<double>> data = {}; fit fit = fit(); fit->set_data(data) fit->set_model(model_a); // question fit->run(); // can extract , display optimized parameter array std::vector<double> p = fit.parameters(); (int i; < p.size(); ++i) std::cout << p[i] << std::endl;
to me, sounds either want interface class provides interface, or making class hieararchy, data stored in base-class, , derived class knows how calculate cost, etc.
there several ways can implement - if want data persist within class, pass in either @ construction or later, in instance of cost model.
unfortunately, have rush now, later check in comments, etc.
Comments
Post a Comment