00001 // 00002 // C++ Interface: LoggingFunction.h 00003 // 00004 // Description: 00005 // 00006 // 00007 // Author: Roman Geus <roman.geus@psi.ch>, (C) 2005 00008 // 00009 // Copyright: See COPYING file that comes with this distribution 00010 // 00011 // 00012 00013 #ifndef LoggingFunction_h 00014 #define LoggingFunction_h 00015 00021 template <typename FunctionType, typename ScalarType> 00022 class LoggingFunction { 00023 public: 00028 LoggingFunction(FunctionType f) 00029 : function_(f), 00030 plot_enabled_(false) 00031 { 00032 // Initialise member variables 00033 reset(); 00034 } 00038 ~LoggingFunction() { 00039 // Call reset() to close file 00040 reset(); 00041 } 00047 ScalarType operator() (ScalarType x) { 00048 ScalarType y = function_(x); 00049 ++ num_eval_; 00050 if (y < y_min_) 00051 y_min_ = y; 00052 if (y > y_max_) 00053 y_max_ = y; 00054 if (plot_enabled_) 00055 of_ << x << " " << y << std::endl; 00056 return y; 00057 } 00061 void reset() { 00062 y_min_ = std::numeric_limits<ScalarType>::max(); 00063 y_max_ = -y_min_; 00064 num_eval_ = 0; 00065 if (plot_enabled_) 00066 of_.close(); 00067 plot_enabled_ = false; 00068 } 00073 void enable_plot(std::string filename) { 00074 if (plot_enabled_) 00075 of_.close(); 00076 of_.open(filename.c_str()); 00077 plot_enabled_ = true; 00078 } 00083 ScalarType get_y_min() const { 00084 return y_min_; 00085 } 00090 ScalarType get_y_max() const { 00091 return y_max_; 00092 } 00097 int get_num_eval() const { 00098 return num_eval_; 00099 } 00100 private: 00101 ScalarType y_min_; 00102 ScalarType y_max_; 00103 int num_eval_; 00104 FunctionType function_; 00105 bool plot_enabled_; 00106 std::ofstream of_; 00107 }; 00108 00109 #endif