source: tspsg/src/tspsolver.cpp @ 5d401f2c50

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 5d401f2c50 was 5d401f2c50, checked in by Oleksii Serdiuk, 14 years ago

+ Added ChangeLog?, Installation Guide and License pages to doxygen generated documentation.

  • Added city and separator parameters to CTSPSolver::getSortedPath() method to make path generation more flexible.
  • Fixed a bug when the solution graph wasn't drwan correctly in some situations.
  • Property mode set to 100644
File size: 11.3 KB
RevLine 
[67e53c96d7]1/*
[430bd7f7e9]2 *  TSPSG: TSP Solver and Generator
[1757eb594b]3 *  Copyright (C) 2007-2010 Lёppa <contacts[at]oleksii[dot]name>
[67e53c96d7]4 *
5 *  $Id$
6 *  $URL$
7 *
8 *  This file is part of TSPSG.
9 *
10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
14 *
15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24#include "tspsolver.h"
25
[394216e468]26//! \internal \brief A short for maximum double, used internally in the solution algorithm.
27#define MAX_DOUBLE std::numeric_limits<double>::max()
28
[9cda6e0f5d]29namespace TSPSolver {
30
[394216e468]31/*!
32 * \brief Returns CTSPSolver's version ID.
33 * \return A string: <b>\$Id$</b>.
34 */
35QString CTSPSolver::getVersionId()
36{
37        return QString("$Id$");
38}
39
40/*!
41 * \brief Constructs CTSPSolver object.
42 * \param parent A parent object.
43 */
44CTSPSolver::CTSPSolver(QObject *parent)
[9cda6e0f5d]45        : QObject(parent), nCities(0), total(0), root(NULL) {}
[394216e468]46
47/*!
48 * \brief Cleans up the object and frees up memory used by the solution tree.
[9cda6e0f5d]49 * \param processEvents If set to \c true then \link QCoreApplication::processEvents() QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents)\endlink will be called from time to time while cleaning up.
[394216e468]50 * \warning After call to this function a solution tree returned by the solve() function is no longer valid.
51 * \note It is not required to call this function manually. This function is always called by solve() at the beginning of the solution process.
52 *
53 * \sa solve()
54 */
55void CTSPSolver::cleanup(bool processEvents)
[e664262f7d]56{
[9cda6e0f5d]57#ifdef QAPPLICATION_H
[394216e468]58        if (!processEvents)
59                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[9cda6e0f5d]60#endif
[394216e468]61        route.clear();
62        mayNotBeOptimal = false;
63        if (root != NULL)
64                deleteTree(root, processEvents);
[9cda6e0f5d]65#ifdef QAPPLICATION_H
[394216e468]66        if (!processEvents)
67                QApplication::restoreOverrideCursor();
[9cda6e0f5d]68#endif
[e664262f7d]69}
[67e53c96d7]70
[e0fcac5f2c]71/*!
72 * \brief Returns the sorted optimal path, starting from City 1.
[5d401f2c50]73 * \param city A string that represents city elements in the path.
74 * \param separator A string that represents separators between cities in the path.
[e0fcac5f2c]75 * \return A string, containing sorted optimal path.
[5d401f2c50]76 *
77 *  The resulting path will be in the form \a city+\a separator+\a city+...+\a separator+\a city.
78 *  \c \%1 in \a city will be replaced by the city number.
[e0fcac5f2c]79 */
[5d401f2c50]80QString CTSPSolver::getSortedPath(const QString &city, const QString &separator) const
[430bd7f7e9]81{
[e0fcac5f2c]82        if (!root || route.isEmpty() || (route.size() != nCities))
83                return QString();
[430bd7f7e9]84
[e0fcac5f2c]85int i = 0; // We start from City 1
[5d401f2c50]86QStringList path;
87        path << city.arg(1);
[e0fcac5f2c]88        while ((i = route[i]) != 0) {
[5d401f2c50]89                path << city.arg(i + 1);
[430bd7f7e9]90        }
[e0fcac5f2c]91        // And finish in City 1, too
[5d401f2c50]92        path << city.arg(1);
[e0fcac5f2c]93
[5d401f2c50]94        return path.join(separator);
[430bd7f7e9]95}
96
[e0fcac5f2c]97/*!
[9cda6e0f5d]98 * \brief Returns a total number of steps in the current solution.
99 * \return A total number of steps or \c 0 if no solution.
100 * \note This is not always the same as the number of cities.
101 */
102int CTSPSolver::getTotalSteps() const
103{
104        return total;
105}
106
107/*!
[394216e468]108 * \brief Indicates whether or not the solution is definitely optimal.
109 * \return \c true if the solution is definitely optimal, otherwise \c false.
[e0fcac5f2c]110 *
[394216e468]111 *  The solution may need some further iterations to determine whether or not it is optimal.
[e0fcac5f2c]112 *  In such cases this function returns \c false.
113 */
114bool CTSPSolver::isOptimal() const
[430bd7f7e9]115{
[e0fcac5f2c]116        return !mayNotBeOptimal;
[430bd7f7e9]117}
118
[caef58b531]119/*!
120 * \brief Solves the given task.
121 * \param numCities Number of cities in the task.
122 * \param task The matrix of city-to-city travel costs.
[85ad815b0b]123 * \return Pointer to the root of the solution tree.
[caef58b531]124 *
125 * \todo TODO: Comment the algorithm.
126 */
[394216e468]127SStep *CTSPSolver::solve(int numCities, const TMatrix &task)
[67e53c96d7]128{
[9cda6e0f5d]129        if (numCities < 3)
[67e53c96d7]130                return NULL;
[394216e468]131
132QMutexLocker locker(&mutex);
[430bd7f7e9]133        cleanup();
[394216e468]134        canceled = false;
135        locker.unlock();
136
[e664262f7d]137        nCities = numCities;
[430bd7f7e9]138
[f0464480db]139SStep *step = new SStep();
[e664262f7d]140        step->matrix = task;
[394216e468]141        // We need to distinguish the values forbidden by the user
142        // from the values forbidden by the algorithm.
143        // So we replace user's infinities by the maximum available double value.
144        normalize(step->matrix);
145#ifdef DEBUG
146        qDebug() << step->matrix;
147#endif // DEBUG
[9cf98b9bd6]148        step->price = align(step->matrix);
[e664262f7d]149        root = step;
[67e53c96d7]150
[f0464480db]151SStep *left, *right;
[430bd7f7e9]152int nRow, nCol;
[9cf98b9bd6]153bool firstStep = true;
[6beb157497]154double check = INFINITY;
[9cda6e0f5d]155        total = 0;
156        while (route.size() < nCities) {
[9cf98b9bd6]157                step->alts = findCandidate(step->matrix,nRow,nCol);
[394216e468]158
[430bd7f7e9]159                while (hasSubCycles(nRow,nCol)) {
[394216e468]160#ifdef DEBUG
161                        qDebug() << "Forbidden: (" << nRow << ";" << nCol << ")";
162#endif // DEBUG
[430bd7f7e9]163                        step->matrix[nRow][nCol] = INFINITY;
164                        step->price += align(step->matrix);
[9cf98b9bd6]165                        step->alts = findCandidate(step->matrix,nRow,nCol);
[430bd7f7e9]166                }
[394216e468]167
168#ifdef DEBUG
169                qDebug() /*<< step->matrix*/ << "Selected: (" << nRow << ";" << nCol << ")";
170                qDebug() << "Alternate:" << step->alts;
171                qDebug() << "Step price:" << step->price << endl;
172#endif // DEBUG
173
174                locker.relock();
175                if ((nRow == -1) || (nCol == -1) || canceled) {
[f0464480db]176                        cleanup();
[394216e468]177                        return NULL;
[430bd7f7e9]178                }
[394216e468]179                locker.unlock();
[430bd7f7e9]180
181                // Route with (nRow,nCol) path
[f0464480db]182                right = new SStep();
[3e46075789]183                right->pNode = step;
[430bd7f7e9]184                right->matrix = step->matrix;
185                for (int k = 0; k < nCities; k++) {
186                        if (k != nCol)
187                                right->matrix[nRow][k] = INFINITY;
188                        if (k != nRow)
189                                right->matrix[k][nCol] = INFINITY;
190                }
191                right->price = step->price + align(right->matrix);
[394216e468]192                // Forbid the selected route to exclude its reuse in next steps.
[430bd7f7e9]193                right->matrix[nCol][nRow] = INFINITY;
194                right->matrix[nRow][nCol] = INFINITY;
195
196                // Route without (nRow,nCol) path
[f0464480db]197                left = new SStep();
[3e46075789]198                left->pNode = step;
[430bd7f7e9]199                left->matrix = step->matrix;
200                left->matrix[nRow][nCol] = INFINITY;
[6beb157497]201                left->price = step->price + align(left->matrix);
[430bd7f7e9]202
203                step->candidate.nRow = nRow;
204                step->candidate.nCol = nCol;
205                step->plNode = left;
206                step->prNode = right;
207
[394216e468]208                // This matrix is not used anymore. Restoring infinities back.
209                denormalize(step->matrix);
210
[430bd7f7e9]211                if (right->price <= left->price) {
212                        // Route with (nRow,nCol) path is cheaper
[9cda6e0f5d]213                        step->next = SStep::RightBranch;
[430bd7f7e9]214                        step = right;
[9cda6e0f5d]215                        route[nRow] = nCol;
216                        emit routePartFound(route.size());
[9cf98b9bd6]217                        if (firstStep) {
218                                check = left->price;
219                                firstStep = false;
220                        }
[430bd7f7e9]221                } else {
222                        // Route without (nRow,nCol) path is cheaper
[9cda6e0f5d]223                        step->next = SStep::LeftBranch;
[430bd7f7e9]224                        step = left;
[9cda6e0f5d]225                        QCoreApplication::processEvents();
[9cf98b9bd6]226                        if (firstStep) {
227                                check = right->price;
228                                firstStep = false;
229                        }
[430bd7f7e9]230                }
[9cda6e0f5d]231                total++;
[430bd7f7e9]232        }
233
[394216e468]234        mayNotBeOptimal = (check < step->price);
[aaf2113307]235
[430bd7f7e9]236        return root;
[67e53c96d7]237}
[9cf98b9bd6]238
[394216e468]239/*!
240 * \brief Indicates whether or not the solution process was canceled.
241 * \return \c true if the solution process was canceled, otherwise \c false.
242 */
243bool CTSPSolver::wasCanceled() const
244{
245QMutexLocker locker(&mutex);
246        return canceled;
247}
248
249/*!
250 * \brief Cancels the solution process.
251 */
252void CTSPSolver::cancel()
253{
254QMutexLocker locker(&mutex);
255        canceled = true;
256}
257
[f0464480db]258CTSPSolver::~CTSPSolver()
259{
260        if (root != NULL)
[3e46075789]261                deleteTree(root);
[f0464480db]262}
263
[e0fcac5f2c]264/* Privates **********************************************************/
[9cf98b9bd6]265
[e4ae9e95f7]266double CTSPSolver::align(TMatrix &matrix)
[e0fcac5f2c]267{
[e4ae9e95f7]268double r = 0;
269double min;
[e0fcac5f2c]270        for (int k = 0; k < nCities; k++) {
271                min = findMinInRow(k,matrix);
272                if (min > 0) {
273                        r += min;
[394216e468]274                        if (min < MAX_DOUBLE)
275                                subRow(matrix,k,min);
[e0fcac5f2c]276                }
[9cf98b9bd6]277        }
[e0fcac5f2c]278        for (int k = 0; k < nCities; k++) {
279                min = findMinInCol(k,matrix);
280                if (min > 0) {
281                        r += min;
[394216e468]282                        if (min < MAX_DOUBLE)
283                                subCol(matrix,k,min);
[e0fcac5f2c]284                }
285        }
[9cda6e0f5d]286        return (r != MAX_DOUBLE) ? r : INFINITY;
[e0fcac5f2c]287}
[9cf98b9bd6]288
[394216e468]289void CTSPSolver::deleteTree(SStep *&root, bool processEvents)
[f0464480db]290{
[3e46075789]291        if (root == NULL)
292                return;
293SStep *step = root;
294SStep *parent;
295        forever {
[394216e468]296                if (processEvents)
[9cda6e0f5d]297                        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[3e46075789]298                if (step->plNode != NULL) {
299                        // We have left child node - going inside it
300                        step = step->plNode;
301                        step->pNode->plNode = NULL;
302                        continue;
303                } else if (step->prNode != NULL) {
304                        // We have right child node - going inside it
305                        step = step->prNode;
306                        step->pNode->prNode = NULL;
307                        continue;
308                } else {
[9cda6e0f5d]309                        // We have no child nodes. Deleting the current one.
[3e46075789]310                        parent = step->pNode;
311                        delete step;
312                        if (parent != NULL) {
313                                // Going back to the parent node.
314                                step = parent;
315                        } else {
316                                // We came back to the root node. Finishing.
317                                root = NULL;
318                                break;
319                        }
320                }
321        }
[9cf98b9bd6]322}
323
[394216e468]324void CTSPSolver::denormalize(TMatrix &matrix) const
325{
326        for (int r = 0; r < nCities; r++)
327                for (int c = 0; c < nCities; c++)
328                        if ((r != c) && (matrix.at(r).at(c) == MAX_DOUBLE))
329                                matrix[r][c] = INFINITY;
330}
331
[9cda6e0f5d]332QList<SStep::SCandidate> CTSPSolver::findCandidate(const TMatrix &matrix, int &nRow, int &nCol) const
[55c4b858e9]333{
[e0fcac5f2c]334        nRow = -1;
335        nCol = -1;
[9cda6e0f5d]336QList<SStep::SCandidate> alts;
337SStep::SCandidate cand;
[e4ae9e95f7]338double h = -1;
339double sum;
[e0fcac5f2c]340        for (int r = 0; r < nCities; r++)
341                for (int c = 0; c < nCities; c++)
342                        if (matrix.at(r).at(c) == 0) {
343                                sum = findMinInRow(r,matrix,c) + findMinInCol(c,matrix,r);
344                                if (sum > h) {
345                                        h = sum;
346                                        nRow = r;
347                                        nCol = c;
[f0464480db]348                                        alts.clear();
349                                } else if ((sum == h) && !hasSubCycles(r,c)) {
350                                        cand.nRow = r;
351                                        cand.nCol = c;
352                                        alts.append(cand);
353                                }
[e0fcac5f2c]354                        }
355        return alts;
[55c4b858e9]356}
357
[e4ae9e95f7]358double CTSPSolver::findMinInCol(int nCol, const TMatrix &matrix, int exr) const
[9cf98b9bd6]359{
[e4ae9e95f7]360double min = INFINITY;
[e0fcac5f2c]361        for (int k = 0; k < nCities; k++)
362                if ((k != exr) && (min > matrix.at(k).at(nCol)))
363                        min = matrix.at(k).at(nCol);
[394216e468]364        return (min == INFINITY) ? 0 : min;
[e0fcac5f2c]365}
366
[e4ae9e95f7]367double CTSPSolver::findMinInRow(int nRow, const TMatrix &matrix, int exc) const
[e0fcac5f2c]368{
[e4ae9e95f7]369double min = INFINITY;
[394216e468]370        for (int k = 0; k < nCities; k++) {
[e0fcac5f2c]371                if (((k != exc)) && (min > matrix.at(nRow).at(k)))
372                        min = matrix.at(nRow).at(k);
[394216e468]373        }
374        return (min == INFINITY) ? 0 : min;
[e0fcac5f2c]375}
376
[0ac9690913]377bool CTSPSolver::hasSubCycles(int nRow, int nCol) const
[e0fcac5f2c]378{
379        if ((nRow < 0) || (nCol < 0) || route.isEmpty() || !(route.size() < nCities - 1) || !route.contains(nCol))
380                return false;
381int i = nCol;
[9cda6e0f5d]382        forever {
383                if ((i = route.value(i)) == nRow)
[e0fcac5f2c]384                        return true;
385                if (!route.contains(i))
386                        return false;
387        }
388        return false;
389}
390
[394216e468]391void CTSPSolver::normalize(TMatrix &matrix) const
392{
393        for (int r = 0; r < nCities; r++)
394                for (int c = 0; c < nCities; c++)
395                        if ((r != c) && (matrix.at(r).at(c) == INFINITY))
396                                matrix[r][c] = MAX_DOUBLE;
397}
398
[e4ae9e95f7]399void CTSPSolver::subCol(TMatrix &matrix, int nCol, double val)
[e0fcac5f2c]400{
401        for (int k = 0; k < nCities; k++)
402                if (k != nCol)
403                        matrix[k][nCol] -= val;
404}
405
[e4ae9e95f7]406void CTSPSolver::subRow(TMatrix &matrix, int nRow, double val)
[e0fcac5f2c]407{
408        for (int k = 0; k < nCities; k++)
409                if (k != nRow)
410                        matrix[nRow][k] -= val;
[9cf98b9bd6]411}
[e2abfd326f]412
[9cda6e0f5d]413}
414
[394216e468]415#ifdef DEBUG
[9cda6e0f5d]416QDebug operator<<(QDebug dbg, const TSPSolver::TMatrix &matrix)
[e2abfd326f]417{
418        for (int r = 0; r < matrix.count(); r++) {
419                for (int c = 0; c < matrix.at(r).count(); c++)
[394216e468]420                        dbg.space() << QString::number(matrix.at(r).at(c)).leftJustified(5);
[e2abfd326f]421                dbg << endl;
422        }
423        return dbg;
424}
[394216e468]425
[9cda6e0f5d]426QDebug operator<<(QDebug dbg, const TSPSolver::SStep::SCandidate &cand)
[394216e468]427{
428        dbg.nospace() << "(" << cand.nRow << ";" << cand.nCol << ")";
429        return dbg;
430}
431#endif // DEBUG
Note: See TracBrowser for help on using the repository browser.