51034140e5459e162a74e2ca6841989a3432c9b9
[satune.git] / src / Tuner / multituner.cc
1 #include "multituner.h"
2 #include "csolver.h"
3 #include "searchtuner.h"
4 #include <math.h>
5 #include <stdlib.h>
6 #include <float.h>
7 #include <string.h>
8 #include <iostream>
9 #include <fstream>
10
11 #define UNSETVALUE -1
12
13 Problem::Problem(const char *_problem) : problemnumber(-1), result(UNSETVALUE) {
14         uint len = strlen(_problem);
15         problem = (char *) ourmalloc(len + 1);
16         memcpy(problem, _problem, len + 1);
17 }
18
19 Problem::~Problem() {
20         ourfree(problem);
21 }
22
23 void TunerRecord::setTime(Problem *problem, long long time) {
24         timetaken.put(problem, time);
25 }
26
27 long long TunerRecord::getTime(Problem *problem) {
28         if (timetaken.contains(problem))
29                 return timetaken.get(problem);
30         else return -1;
31 }
32
33 TunerRecord *TunerRecord::changeTuner(SearchTuner *_newtuner) {
34         TunerRecord *tr = new TunerRecord(_newtuner);
35         for (uint i = 0; i < problems.getSize(); i++) {
36                 tr->problems.push(problems.get(i));
37         }
38         return tr;
39 }
40
41 MultiTuner::MultiTuner(uint _budget, uint _rounds, uint _timeout) :
42         budget(_budget), rounds(_rounds), timeout(_timeout), execnum(0) {
43 }
44
45 MultiTuner::~MultiTuner() {
46         for (uint i = 0; i < problems.getSize(); i++)
47                 ourfree(problems.get(i));
48         for (uint i = 0; i < allTuners.getSize(); i++)
49                 delete allTuners.get(i);
50 }
51
52 void MultiTuner::addProblem(const char *filename) {
53         Problem *p = new Problem(filename);
54         p->problemnumber = problems.getSize();
55         problems.push(p);
56 }
57
58 void MultiTuner::printData() {
59         model_print("*********** DATA DUMP ***********\n");
60         for (uint i = 0; i < allTuners.getSize(); i++) {
61                 TunerRecord *tuner = allTuners.get(i);
62                 SearchTuner *stun = tuner->getTuner();
63                 model_print("Tuner %u\n", i);
64                 stun->print();
65                 model_print("----------------------------------\n\n\n");
66                 for (uint j = 0; j < tuner->problems.getSize(); j++) {
67                         Problem *problem = tuner->problems.get(j);
68                         model_print("Problem %s\n", problem->getProblem());
69                         model_print("Time = %lld\n", tuner->getTime(problem));
70                 }
71         }
72 }
73
74 void MultiTuner::addTuner(SearchTuner *tuner) {
75         TunerRecord *t = new TunerRecord(tuner);
76         tuners.push(t);
77         t->tunernumber = allTuners.getSize();
78         allTuners.push(t);
79 }
80
81
82 void MultiTuner::readData(uint numRuns) {
83         for (uint i = 0; i < numRuns; i++) {
84                 ifstream myfile;
85                 char buffer[512];
86                 uint tunernumber;
87                 snprintf(buffer, sizeof(buffer), "tunernum%u", i);
88                 myfile.open (buffer, ios::in);
89                 myfile >> tunernumber;
90                 myfile.close();
91                 if (allTuners.getSize() <= tunernumber)
92                         allTuners.setSize(tunernumber + 1);
93                 if (allTuners.get(tunernumber) == NULL) {
94                         snprintf(buffer, sizeof(buffer), "tuner%u", i);
95                         allTuners.set(tunernumber, new TunerRecord(new SearchTuner(buffer)));
96                 }
97                 //Add any new used records
98                 snprintf(buffer, sizeof(buffer), "tuner%uused", i);
99                 TunerRecord *tuner = allTuners.get(tunernumber);
100                 tuner->getTuner()->addUsed(buffer);
101
102                 char problemname[512];
103                 uint problemnumber;
104                 snprintf(buffer, sizeof(buffer), "problem%u", i);
105                 myfile.open(buffer, ios::in);
106                 myfile.getline(problemname, sizeof(problemname));
107                 myfile >> problemnumber;
108                 myfile.close();
109                 if (problems.getSize() <= problemnumber)
110                         problems.setSize(problemnumber + 1);
111                 if (problems.get(problemnumber) == NULL)
112                         problems.set(problemnumber, new Problem(problemname));
113                 Problem *problem = problems.get(problemnumber);
114                 long long metric = -1;
115                 int sat = IS_INDETER;
116                 //Read data in from results file
117                 snprintf(buffer, sizeof(buffer), "result%u", i);
118
119                 myfile.open (buffer, ios::in);
120
121
122                 if (myfile.is_open()) {
123                         myfile >> metric;
124                         myfile >> sat;
125                         myfile.close();
126                 }
127                 if (problem->result == UNSETVALUE && sat != IS_INDETER) {
128                         problem->result = sat;
129                 } else if (problem->result != sat && sat != IS_INDETER) {
130                         model_print("******** Result has changed ********\n");
131                 }
132
133                 if (metric != -1) {
134                         if (tuner->getTime(problem) == -1)
135                                 tuner->problems.push(problem);
136                         tuner->setTime(problem, metric);
137                 }
138
139         }
140
141 }
142
143 long long MultiTuner::evaluate(Problem *problem, TunerRecord *tuner) {
144         char buffer[512];
145         {
146                 snprintf(buffer, sizeof(buffer), "problem%u", execnum);
147
148                 ofstream myfile;
149                 myfile.open (buffer, ios::out);
150
151
152                 if (myfile.is_open()) {
153                         myfile << problem->getProblem() << endl;
154                         myfile << problem->problemnumber << endl;
155                         myfile.close();
156                 }
157         }
158
159         {
160                 snprintf(buffer, sizeof(buffer), "tunernum%u", execnum);
161
162                 ofstream myfile;
163                 myfile.open (buffer, ios::out);
164
165
166                 if (myfile.is_open()) {
167                         myfile << tuner->tunernumber << endl;
168                         myfile.close();
169                 }
170         }
171
172         //Write out the tuner
173         snprintf(buffer, sizeof(buffer), "tuner%u", execnum);
174         tuner->getTuner()->serialize(buffer);
175
176         //Do run
177         snprintf(buffer, sizeof(buffer), "./run.sh deserializerun %s %u tuner%u result%u > log%u", problem->getProblem(), timeout, execnum, execnum, execnum);
178         int status = system(buffer);
179
180         long long metric = -1;
181         int sat = IS_INDETER;
182
183         if (status == 0) {
184                 //Read data in from results file
185                 snprintf(buffer, sizeof(buffer), "result%u", execnum);
186
187                 ifstream myfile;
188                 myfile.open (buffer, ios::in);
189
190
191                 if (myfile.is_open()) {
192                         myfile >> metric;
193                         myfile >> sat;
194                         myfile.close();
195                 }
196
197                 snprintf(buffer, sizeof(buffer), "tuner%uused", execnum);
198                 tuner->getTuner()->addUsed(buffer);
199         }
200         //Increment execution count
201         execnum++;
202
203         if (problem->result == UNSETVALUE && sat != IS_INDETER) {
204                 problem->result = sat;
205         } else if (problem->result != sat && sat != IS_INDETER) {
206                 model_print("******** Result has changed ********\n");
207         }
208         return metric;
209 }
210
211 void MultiTuner::tuneComp() {
212         Vector<TunerRecord *> *tunerV = new Vector<TunerRecord *>(&tuners);
213         for (uint b = 0; b < budget; b++) {
214                 model_print("Round %u of %u\n", b, budget);
215                 uint tSize = tunerV->getSize();
216                 for (uint i = 0; i < tSize; i++) {
217                         SearchTuner *tmpTuner = mutateTuner(tunerV->get(i)->getTuner(), b);
218                         TunerRecord *tmp = new TunerRecord(tmpTuner);
219                         tmp->tunernumber = allTuners.getSize();
220                         model_print("Mutated tuner %u to generate tuner %u\n", tunerV->get(i)->tunernumber, tmp->tunernumber);
221                         allTuners.push(tmp);
222                         tunerV->push(tmp);
223                 }
224
225                 Hashtable<TunerRecord *, int, uint64_t> scores;
226                 for (uint i = 0; i < problems.getSize(); i++) {
227                         Problem *problem = problems.get(i);
228                         Vector<TunerRecord *> places;
229                         for (uint j = 0; j < tunerV->getSize(); j++) {
230                                 TunerRecord *tuner = tunerV->get(j);
231                                 long long metric = tuner->getTime(problem);
232                                 if (metric == -1) {
233                                         metric = evaluate(problem, tuner);
234                                         if (tuner->getTime(problem) == -1) {
235                                                 tuner->problems.push(problem);
236                                         }
237                                         DEBUG("%u.Problem<%s>\tTuner<%p>\tMetric<%lld>\n", i, problem->problem,tuner, metric);
238                                         DEBUG("*****************************\n");
239                                         if (metric != -1)
240                                                 tuner->setTime(problem, metric);
241                                 }
242                                 if (metric != -1) {
243                                         uint k = 0;
244                                         for (; k < places.getSize(); k++) {
245                                                 if (metric < places.get(k)->getTime(problem))
246                                                         break;
247                                         }
248                                         DEBUG("place[%u]=Tuner<%p>\n", k, tuner);
249                                         places.insertAt(k, tuner);
250                                 }
251                         }
252                         int points = 9;
253                         for (uint k = 0; k < places.getSize() && points; k++) {
254                                 TunerRecord *tuner = places.get(k);
255                                 int currScore = 0;
256                                 if (scores.contains(tuner))
257                                         currScore = scores.get(tuner);
258                                 currScore += points;
259                                 DEBUG("Problem<%s>\tTuner<%p>\tmetric<%d>\n", problem->problem, tuner, currScore);
260                                 DEBUG("**************************\n");
261                                 scores.put(tuner, currScore);
262                                 points = points / 3;
263                         }
264                 }
265                 Vector<TunerRecord *> ranking;
266                 for (uint i = 0; i < tunerV->getSize(); i++) {
267                         TunerRecord *tuner = tunerV->get(i);
268                         int score = 0;
269                         if (scores.contains(tuner))
270                                 score = scores.get(tuner);
271                         uint j = 0;
272                         for (; j < ranking.getSize(); j++) {
273                                 TunerRecord *t = ranking.get(j);
274                                 int tscore = 0;
275                                 if (scores.contains(t))
276                                         tscore = scores.get(t);
277                                 if (score < tscore)
278                                         break;
279                         }
280                         DEBUG("ranking[%u]=tuner<%p>(Score=%d)\n", j, tuner, score);
281                         DEBUG("************************\n");
282                         ranking.insertAt(j, tuner);
283                 }
284                 DEBUG("tunerSize=%u\trankingSize=%u\ttunerVSize=%u\n", tuners.getSize(), ranking.getSize(), tunerV->getSize());
285                 for (uint i = tuners.getSize(); i < ranking.getSize(); i++) {
286                         TunerRecord *tuner = ranking.get(i);
287                         model_print("Removing tuner %u\n", tuner->tunernumber);
288                         for (uint j = 0; j < tunerV->getSize(); j++) {
289                                 if (tunerV->get(j) == tuner)
290                                         tunerV->removeAt(j);
291                         }
292                 }
293         }
294         printData();
295 }
296
297 void MultiTuner::mapProblemsToTuners(Vector<TunerRecord *> *tunerV) {
298         for (uint i = 0; i < problems.getSize(); i++) {
299                 Problem *problem = problems.get(i);
300                 TunerRecord *bestTuner = NULL;
301                 long long bestscore = 0;
302                 for (uint j = 0; j < tunerV->getSize(); j++) {
303                         TunerRecord *tuner = tunerV->get(j);
304                         long long metric = tuner->getTime(problem);
305                         if (metric == -1) {
306                                 metric = evaluate(problem, tuner);
307                                 if (metric != -1)
308                                         tuner->setTime(problem, metric);
309                         }
310                         if ((bestTuner == NULL && metric != -1) ||
311                                         (metric < bestscore && metric != -1)) {
312                                 bestTuner = tuner;
313                                 bestscore = metric;
314                         }
315                 }
316                 if (bestTuner != NULL)
317                         bestTuner->problems.push(problem);
318         }
319 }
320
321 void clearVector(Vector<TunerRecord *> *tunerV) {
322         for (uint j = 0; j < tunerV->getSize(); j++) {
323                 TunerRecord *tuner = tunerV->get(j);
324                 tuner->problems.clear();
325         }
326 }
327
328 void MultiTuner::tuneK() {
329         Vector<TunerRecord *> *tunerV = new Vector<TunerRecord *>(&tuners);
330         for (uint i = 0; i < rounds; i++) {
331                 clearVector(tunerV);
332                 mapProblemsToTuners(tunerV);
333                 improveTuners(tunerV);
334         }
335         model_print("Best tuners\n");
336         for (uint j = 0; j < tunerV->getSize(); j++) {
337                 TunerRecord *tuner = tunerV->get(j);
338                 char buffer[256];
339                 sprintf(buffer, "tuner%u.conf", j);
340                 tuner->getTuner()->serialize(buffer);
341                 tuner->getTuner()->print();
342         }
343         delete tunerV;
344 }
345
346 void MultiTuner::improveTuners(Vector<TunerRecord *> *tunerV) {
347         for (uint j = 0; j < tunerV->getSize(); j++) {
348                 TunerRecord *tuner = tunerV->get(j);
349                 TunerRecord *newtuner = tune(tuner);
350                 tunerV->set(j, newtuner);
351         }
352 }
353
354 double MultiTuner::evaluateAll(TunerRecord *tuner) {
355         double product = 1;
356         for (uint i = 0; i < tuner->problems.getSize(); i++) {
357                 Problem *problem = tuner->problems.get(i);
358                 long long metric = tuner->getTime(problem);
359                 if (metric == -1) {
360                         metric = evaluate(problem, tuner);
361                         if (metric != -1)
362                                 tuner->setTime(problem, metric);
363                 }
364
365                 double score = metric;
366                 product *= score;
367         }
368         return pow(product, 1 / ((double)tuner->problems.getSize()));
369 }
370
371 SearchTuner *MultiTuner::mutateTuner(SearchTuner *oldTuner, uint k) {
372         SearchTuner *newTuner = oldTuner->copyUsed();
373         uint numSettings = oldTuner->getSize();
374         uint settingsToMutate = (uint)(AUTOTUNERFACTOR * (((double)numSettings) * (budget - k)) / (budget));
375         if (settingsToMutate < 1)
376                 settingsToMutate = 1;
377         model_print("Mutating %u settings\n", settingsToMutate);
378         while (settingsToMutate-- != 0) {
379                 newTuner->randomMutate();
380         }
381         return newTuner;
382 }
383
384 TunerRecord *MultiTuner::tune(TunerRecord *tuner) {
385         TunerRecord *bestTuner = NULL;
386         double bestScore = DBL_MAX;
387
388         TunerRecord *oldTuner = tuner;
389         double base_temperature = evaluateAll(oldTuner);
390         double oldScore = base_temperature;
391
392         for (uint i = 0; i < budget; i++) {
393                 SearchTuner *tmpTuner = mutateTuner(oldTuner->getTuner(), i);
394                 TunerRecord *newTuner = oldTuner->changeTuner(tmpTuner);
395                 newTuner->tunernumber = allTuners.getSize();
396                 allTuners.push(newTuner);
397                 double newScore = evaluateAll(newTuner);
398                 newTuner->tuner->printUsed();
399                 model_print("Received score %f\n", newScore);
400                 double scoreDiff = newScore - oldScore; //smaller is better
401                 if (newScore < bestScore) {
402                         bestScore = newScore;
403                         bestTuner = newTuner;
404                 }
405
406                 double acceptanceP;
407                 if (scoreDiff < 0) {
408                         acceptanceP = 1;
409                 } else {
410                         double currTemp = base_temperature * (((double)budget - i) / budget);
411                         acceptanceP = exp(-scoreDiff / currTemp);
412                 }
413                 double ran = ((double)random()) / RAND_MAX;
414                 if (ran <= acceptanceP) {
415                         oldScore = newScore;
416                         oldTuner = newTuner;
417                 }
418         }
419
420         return bestTuner;
421 }
422