File: spacenode.cpp

package info (click to toggle)
gecode-snapshot 6.2.0%2Bgit20240207-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 35,308 kB
  • sloc: cpp: 475,516; perl: 2,077; makefile: 1,816; sh: 198
file content (380 lines) | stat: -rw-r--r-- 11,793 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Guido Tack <tack@gecode.org>
 *
 *  Copyright:
 *     Guido Tack, 2006
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <gecode/gist/spacenode.hh>
#include <gecode/gist/visualnode.hh>
#include <gecode/gist/stopbrancher.hh>
#include <gecode/search.hh>
#include <stack>

#include <QString>
#include <QVector>

namespace Gecode { namespace Gist {

  /// \brief Representation of a branch in the search tree
  class Branch {
  public:
    /// Alternative number
    int alternative;
    /// The best space known when the branch was created
    SpaceNode* ownBest;
    const Choice* choice;

    /// Constructor
    Branch(int a, const Choice* c, SpaceNode* best = nullptr)
      : alternative(a), ownBest(best) {
        choice = c;
      }
  };

  BestNode::BestNode(SpaceNode* s0) : s(s0) {}

  int
  SpaceNode::recompute(NodeAllocator& na,
                       BestNode* curBest, int c_d, int a_d) {
    int rdist = 0;

    if (copy == nullptr) {
      SpaceNode* curNode = this;
      SpaceNode* lastFixpoint = nullptr;

      lastFixpoint = curNode;

      std::stack<Branch> stck;

      int idx = getIndex(na);
      while (curNode->copy == nullptr) {
        SpaceNode* parent = curNode->getParent(na);
        int parentIdx = curNode->getParent();
        int alternative = curNode->getAlternative(na);

        SpaceNode* ownBest = na.best(idx);
        Branch b(alternative, parent->choice,
                 curBest == nullptr ? nullptr : ownBest);
        stck.push(b);

        curNode = parent;
        idx = parentIdx;
        rdist++;
      }

      Space* curSpace;
      if (Support::marked(curNode->copy)) {
        curSpace = static_cast<Space*>(Support::unmark(curNode->copy));
        curNode->copy = nullptr;
        a_d = -1;
      } else {
        curSpace = curNode->copy->clone();
        curNode->setDistance(0);
      }

      SpaceNode* lastBest = nullptr;
      SpaceNode* middleNode = curNode;
      int curDist = 0;

      while (!stck.empty()) {
        if (a_d >= 0 &&
            curDist > a_d &&
            curDist == rdist / 2) {
            if (curSpace->status() == SS_FAILED) {
              copy = static_cast<Space*>(Support::mark(curSpace));
              return rdist;
            } else {
              middleNode->copy = curSpace->clone();
            }
        }
        Branch b = stck.top(); stck.pop();

        if(middleNode == lastFixpoint) {
          curSpace->status();
        }

        curSpace->commit(*b.choice, b.alternative);

        if (b.ownBest != nullptr && b.ownBest != lastBest) {
          b.ownBest->acquireSpace(na,curBest, c_d, a_d);
          Space* ownBestSpace =
            static_cast<Space*>(Support::funmark(b.ownBest->copy));
          if (ownBestSpace->status() != SS_SOLVED) {
            // in the presence of weakly monotonic propagators, we may have to
            // use search to find the solution here
            ownBestSpace = Gecode::dfs(ownBestSpace);
            if (Support::marked(b.ownBest->copy)) {
              delete static_cast<Space*>(Support::unmark(b.ownBest->copy));
              b.ownBest->copy =
                static_cast<Space*>(Support::mark(ownBestSpace));
            } else {
              delete b.ownBest->copy;
              b.ownBest->copy = ownBestSpace;
            }
          }
          curSpace->constrain(*ownBestSpace);
          lastBest = b.ownBest;
        }
        curDist++;
        middleNode = middleNode->getChild(na,b.alternative);
        middleNode->setDistance(curDist);
      }
      copy = static_cast<Space*>(Support::mark(curSpace));

    }
    return rdist;
  }

  void
  SpaceNode::acquireSpace(NodeAllocator& na,
                          BestNode* curBest, int c_d, int a_d) {
    SpaceNode* p = getParent(na);
    int parentIdx = getParent();
    int idx = getIndex(na);

    if (getStatus() == UNDETERMINED && curBest != nullptr &&
        na.best(idx) == nullptr &&
        p != nullptr && curBest->s != na.best(parentIdx)) {
      na.setBest(idx, curBest->s->getIndex(na));
    }
    SpaceNode* ownBest = na.best(idx);

    if (copy == nullptr && p != nullptr && p->copy != nullptr &&
        Support::marked(p->copy)) {
      // If parent has a working space, steal it
      copy = p->copy;
      p->copy = nullptr;
      if (p->choice != nullptr)
        static_cast<Space*>(Support::unmark(copy))->
          commit(*p->choice, getAlternative(na));

      if (ownBest != nullptr) {
        ownBest->acquireSpace(na,curBest, c_d, a_d);
        Space* ownBestSpace =
          static_cast<Space*>(Support::funmark(ownBest->copy));
        if (ownBestSpace->status() != SS_SOLVED) {
          // in the presence of weakly monotonic propagators, we may have to
          // use search to find the solution here

          ownBestSpace = Gecode::dfs(ownBestSpace);
          if (Support::marked(ownBest->copy)) {
            delete static_cast<Space*>(Support::unmark(ownBest->copy));
            ownBest->copy =
              static_cast<Space*>(Support::mark(ownBestSpace));
          } else {
            delete ownBest->copy;
            ownBest->copy = ownBestSpace;
          }
        }
        static_cast<Space*>(Support::unmark(copy))->constrain(*ownBestSpace);
      }
      int d = p->getDistance()+1;
      if (d > c_d && c_d >= 0 &&
          static_cast<Space*>(Support::unmark(copy))->status() == SS_BRANCH) {
        copy = static_cast<Space*>(Support::unmark(copy));
        d = 0;
      }
      setDistance(d);
    }

    if (copy == nullptr) {
      if (recompute(na, curBest, c_d, a_d) > c_d && c_d >= 0 &&
          static_cast<Space*>(Support::unmark(copy))->status() == SS_BRANCH) {
        copy = static_cast<Space*>(Support::unmark(copy));
        setDistance(0);
      }
    }

    // always return a fixpoint
    static_cast<Space*>(Support::funmark(copy))->status();
    if (Support::marked(copy) && p != nullptr && isOpen() &&
        p->copy != nullptr && p->getNoOfOpenChildren(na) == 1 &&
        !p->isRoot()) {
      // last alternative optimization

      copy = static_cast<Space*>(Support::unmark(copy));
      delete static_cast<Space*>(Support::funmark(p->copy));
      p->copy = nullptr;
      setDistance(0);
      p->setDistance(p->getParent(na)->getDistance()+1);
    }
  }

  void
  SpaceNode::closeChild(const NodeAllocator& na,
                        bool hadFailures, bool hadSolutions) {
    setHasFailedChildren(hasFailedChildren() || hadFailures);
    setHasSolvedChildren(hasSolvedChildren() || hadSolutions);

    bool allClosed = true;
    for (int i=getNumberOfChildren(); i--;) {
      if (getChild(na,i)->isOpen()) {
        allClosed = false;
        break;
      }
    }

    if (allClosed) {
      setHasOpenChildren(false);
      for (unsigned int i=0; i<getNumberOfChildren(); i++)
        setHasSolvedChildren(hasSolvedChildren() ||
          getChild(na,i)->hasSolvedChildren());
      SpaceNode* p = getParent(na);
      if (p != nullptr) {
        delete static_cast<Space*>(Support::funmark(copy));
        copy = nullptr;
        p->closeChild(na, hasFailedChildren(), hasSolvedChildren());
      }
    } else {

      if (hadSolutions) {
        setHasSolvedChildren(true);
        SpaceNode* p = getParent(na);
        while (p != nullptr && !p->hasSolvedChildren()) {
          p->setHasSolvedChildren(true);
          p = p->getParent(na);
        }
      }
      if (hadFailures) {
        SpaceNode* p = getParent(na);
        while (p != nullptr && !p->hasFailedChildren()) {
          p->setHasFailedChildren(true);
          p = p->getParent(na);
        }
      }
    }

  }

  SpaceNode::SpaceNode(Space* root)
  : Node(-1, root==nullptr),
    copy(root), choice(nullptr), nstatus(0) {
    if (root == nullptr) {
      setStatus(FAILED);
      setHasSolvedChildren(false);
      setHasFailedChildren(true);
    } else {
      setStatus(UNDETERMINED);
      setHasSolvedChildren(false);
      setHasFailedChildren(false);
    }
  }

  void
  SpaceNode::dispose(void) {
    delete choice;
    delete static_cast<Space*>(Support::funmark(copy));
  }


  int
  SpaceNode::getNumberOfChildNodes(NodeAllocator& na,
                                   BestNode* curBest, Statistics& stats,
                                   int c_d, int a_d) {
    int kids = 0;
    if (isUndetermined()) {
      stats.undetermined--;
      acquireSpace(na, curBest, c_d, a_d);
      QVector<QString> labels;
      switch (static_cast<Space*>(Support::funmark(copy))->status(stats)) {
      case SS_FAILED:
        {
          purge(na);
          kids = 0;
          setHasOpenChildren(false);
          setHasSolvedChildren(false);
          setHasFailedChildren(true);
          setStatus(FAILED);
          stats.failures++;
          SpaceNode* p = getParent(na);
          if (p != nullptr)
            p->closeChild(na, true, false);
        }
        break;
      case SS_SOLVED:
        {
          // Deletes all pending branchers
          (void) static_cast<Space*>(Support::funmark(copy))->choice();
          kids = 0;
          setStatus(SOLVED);
          setHasOpenChildren(false);
          setHasSolvedChildren(true);
          setHasFailedChildren(false);
          stats.solutions++;
          if (curBest != nullptr) {
            curBest->s = this;
          }
          SpaceNode* p = getParent(na);
          if (p != nullptr)
            p->closeChild(na, false, true);
        }
        break;
      case SS_BRANCH:
        {
          Space* s = static_cast<Space*>(Support::funmark(copy));
          choice = s->choice();
          kids = choice->alternatives();
          setHasOpenChildren(true);
          if (dynamic_cast<const StopChoice*>(choice)) {
            setStatus(STOP);
          } else {
            setStatus(BRANCH);
            stats.choices++;
          }
          stats.undetermined += kids;
          for (int i=0; i<kids; i++) {
            std::ostringstream oss;
            s->print(*choice,i,oss);
            labels.push_back(QString(oss.str().c_str()));
          }
        }
        break;
      }
      static_cast<VisualNode*>(this)->changedStatus(na);
      setNumberOfChildren(kids, na);
    } else {
      kids = getNumberOfChildren();
    }
    return kids;
  }

  int
  SpaceNode::getNoOfOpenChildren(const NodeAllocator& na) {
    if (!hasOpenChildren())
      return 0;
    int noOfOpenChildren = 0;
    for (int i=getNumberOfChildren(); i--;)
      noOfOpenChildren += (getChild(na,i)->isOpen());
    return noOfOpenChildren;
  }

}}

// STATISTICS: gist-any