MultiAgentDecisionProcess  Release 0.2.1
SimulationResult.cpp
Go to the documentation of this file.
1 
28 #include "SimulationResult.h"
29 #include <float.h>
30 #include <fstream>
31 
32 using namespace std;
33 
34 //Default constructor
36 {
37  _m_nr_stored=0;
38  _m_avg_reward=-1;
39 }
40 
46 SimulationResult::SimulationResult(int horizon,int random_seed,int nrRuns)
47 {
48  _m_horizon=horizon;
49  _m_random_seed=random_seed;
50  _m_rewards = vector<double>(nrRuns, 0.0);
51  _m_nr_stored=0;
52  _m_avg_reward=-1;
53 }
54 
55 //Destructor
57 {
58 }
59 
61 {
62  _m_nr_stored++;
63  _m_rewards[_m_nr_stored-1]=r;
64 
65  UpdateStatistics();
66 }
67 
68 vector<double> SimulationResult::GetRewards(void)
69 {
70  vector<double> rewards(_m_nr_stored);
71 
72  for(unsigned int i=0;i<_m_nr_stored;i++)
73  rewards[i]=_m_rewards[i];
74 
75  return(rewards);
76 }
77 
79 {
80  // update the average reward
81  double sum=0;
82  for(unsigned int i=0;i<_m_nr_stored;i++)
83  sum+=_m_rewards[i];
84 
85  if(_m_nr_stored>0)
86  _m_avg_reward=sum/_m_nr_stored;
87  else
88  _m_avg_reward=DBL_MAX;
89 }
90 
92 {
93  if(_m_nr_stored>_m_rewards.size())
94  cerr << "SimulationResult::Print error _m_nr_stored " << _m_nr_stored
95  << " > " << " _m_rewards.size() " << _m_rewards.size() << endl;
96 
97  cout << "SimulationResult::Print horizon " << _m_horizon << " seed "
98  << _m_random_seed << " entries " << _m_nr_stored << endl;
99  cout << "SimulationResult::Print Rewards: ";
100  for(unsigned int i=0;i<_m_nr_stored;i++)
101  cout << _m_rewards[i] << " ";
102  cout << endl;
103  cout << "SimulationResult::Print Average reward " << _m_avg_reward << endl;
104 }
105 
107 {
108  cout << "Average reward: " << _m_avg_reward << " ("
109  << _m_nr_stored << " samples)" << endl;
110 }
111 
112 void SimulationResult::Save(string filename)
113 {
114  ofstream fp(filename.c_str());
115  if(!fp)
116  {
117  stringstream ss;
118  ss << "SimulationResult::Save failed to open file " << filename << endl;
119  throw E(ss);
120  }
121 
122  vector<double> rewards=GetRewards();
123 
124  for(unsigned i=0;i<rewards.size();i++)
125  fp << rewards[i] << endl;
126 }
127 
128 void SimulationResult::Load(string filename)
129 {
130  const int bufsize=65536;
131  char buffer[bufsize];
132 
133  double r;
134 
135  ifstream fp(filename.c_str());
136  if(!fp)
137  {
138  stringstream ss;
139  ss << "SimulationResult::Load: failed to "
140  << "open file " << filename;
141  throw E(ss);
142  }
143 
144  _m_rewards.clear();
145 
146  while(!fp.getline(buffer,bufsize).eof())
147  {
148  istringstream is(buffer);
149  is >> r;
150  _m_rewards.push_back(r);
151  }
152 
153  _m_nr_stored=_m_rewards.size();
154  UpdateStatistics();
155 }