Lang Hames | 3ca9a5b | 2009-08-06 23:32:48 +0000 | [diff] [blame^] | 1 | #ifndef LLVM_CODEGEN_PBQP_EXHAUSTIVESOLVER_H |
| 2 | #define LLVM_CODEGEN_PBQP_EXHAUSTIVESOLVER_H |
| 3 | |
| 4 | #include "Solver.h" |
| 5 | |
| 6 | namespace PBQP { |
| 7 | |
| 8 | class ExhaustiveSolverImpl { |
| 9 | private: |
| 10 | |
| 11 | const SimpleGraph &g; |
| 12 | |
| 13 | PBQPNum getSolutionCost(const Solution &solution) const { |
| 14 | PBQPNum cost = 0.0; |
| 15 | |
| 16 | for (SimpleGraph::ConstNodeIterator |
| 17 | nodeItr = g.nodesBegin(), nodeEnd = g.nodesEnd(); |
| 18 | nodeItr != nodeEnd; ++nodeItr) { |
| 19 | |
| 20 | unsigned nodeId = g.getNodeID(nodeItr); |
| 21 | |
| 22 | cost += g.getNodeCosts(nodeItr)[solution.getSelection(nodeId)]; |
| 23 | } |
| 24 | |
| 25 | for (SimpleGraph::ConstEdgeIterator |
| 26 | edgeItr = g.edgesBegin(), edgeEnd = g.edgesEnd(); |
| 27 | edgeItr != edgeEnd; ++edgeItr) { |
| 28 | |
| 29 | SimpleGraph::ConstNodeIterator n1 = g.getEdgeNode1Itr(edgeItr), |
| 30 | n2 = g.getEdgeNode2Itr(edgeItr); |
| 31 | unsigned sol1 = solution.getSelection(g.getNodeID(n1)), |
| 32 | sol2 = solution.getSelection(g.getNodeID(n2)); |
| 33 | |
| 34 | cost += g.getEdgeCosts(edgeItr)[sol1][sol2]; |
| 35 | } |
| 36 | |
| 37 | return cost; |
| 38 | } |
| 39 | |
| 40 | public: |
| 41 | |
| 42 | ExhaustiveSolverImpl(const SimpleGraph &g) : g(g) {} |
| 43 | |
| 44 | Solution solve() const { |
| 45 | Solution current(g.getNumNodes(), true), optimal(current); |
| 46 | |
| 47 | PBQPNum bestCost = std::numeric_limits<PBQPNum>::infinity(); |
| 48 | bool finished = false; |
| 49 | |
| 50 | while (!finished) { |
| 51 | PBQPNum currentCost = getSolutionCost(current); |
| 52 | |
| 53 | if (currentCost < bestCost) { |
| 54 | optimal = current; |
| 55 | bestCost = currentCost; |
| 56 | } |
| 57 | |
| 58 | // assume we're done. |
| 59 | finished = true; |
| 60 | |
| 61 | for (unsigned i = 0; i < g.getNumNodes(); ++i) { |
| 62 | if (current.getSelection(i) == |
| 63 | (g.getNodeCosts(g.getNodeItr(i)).getLength() - 1)) { |
| 64 | current.setSelection(i, 0); |
| 65 | } |
| 66 | else { |
| 67 | current.setSelection(i, current.getSelection(i) + 1); |
| 68 | finished = false; |
| 69 | break; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | } |
| 74 | |
| 75 | optimal.setSolutionCost(bestCost); |
| 76 | |
| 77 | return optimal; |
| 78 | } |
| 79 | |
| 80 | }; |
| 81 | |
| 82 | class ExhaustiveSolver : public Solver { |
| 83 | public: |
| 84 | ~ExhaustiveSolver() {} |
| 85 | Solution solve(const SimpleGraph &g) const { |
| 86 | ExhaustiveSolverImpl solver(g); |
| 87 | return solver.solve(); |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | } |
| 92 | |
| 93 | #endif // LLVM_CODGEN_PBQP_EXHAUSTIVESOLVER_HPP |