orange / source / orangeom / pathfinder.cpp

  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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
 * Pathfinder algorithm for Orange
 *
 * @author:  Anze Vavpetic <anze.vavpetic@gmail.com>
 * @summary: Implementation of the binary pathfinder algorithm and an improvement for sparse networks
 */

#include "ppp/pathfinder.ppp"
#include "pq.cpp"

template <class Key>
SPFNode<Key>::SPFNode(const int &v, const double &d, const short int &state)
  : PQNode<Key>(-1, d),
    m_v(v),
    m_state(state)
{
}

BFSNode::BFSNode(const int &idx, const double &d, const int &len)
  : m_idx(idx),
    m_d(d),
    m_len(len)
{
}

TPathfinder::TPathfinder()
  : progressCallback(NULL)
{
}

TPathfinder::~TPathfinder() 
{
}

void TPathfinder::toPFNET(int r, int q, TGraph *g, const string &method)
{
  // Set the parameters
  m_r = r;
  m_q = q;

  // Needed for the progress callback
  m_done = 0;
  m_nodes = g->nVertices;

  if (method == "sparse") {
    toPFNET_sparse(g);
  } else if (method == "dense") {
    toPFNET_binary(g);
  }
}

void TPathfinder::toPFNET_binary(TGraph *g)
{
  int n = g->nVertices;
  int i = 1, nq = 0;
  
  // Define two nxn matrices
  Matrix D  (n, Vector(n, INFINITY));
  Matrix Dq (n, Vector(n, INFINITY));
  
  // Init the first distance matrix to the graph's weight matrix
  for (int j=0; j<n; j++) {
    for (int k=0; k<n; k++) 
    {
      double *w = g->getEdge(j,k);
      
      if (w != NULL) 
        D[j][k] = *w;
      
      // This is just precautionary - we must assume the distance of a node to itself is 0
      if (j == k)
        D[j][k] = 0;
    }
  }
  
  if (m_q % 2 == 1) {
    op(Dq, D, Dq);
    nq = 1;
  }
  
  while (i*2 <= m_q) {
    
    // Get D^(i*2) from D^i and D^i
    op(D, D, D);
    if ((m_q - nq) % (i*4) > 0) {
      op(Dq, D, Dq);
      nq = nq + i*2;
    }    
    i = i * 2;
  }
  
  // Comparing elements of D^q and W^2, wherever dij = wij, mark eij as a link in the PFNET
  for (int j=0; j<n; j++) {
    for (int k=0; k<n; k++) 
    {  
      double *w = g->getEdge(j,k);
      
      if (w != NULL && (Dq[j][k] != *w ))
        g->removeEdge(j,k);
    }
  }
}

void TPathfinder::op(const Matrix &A, const Matrix &B, Matrix &result) const
{ 
  int n = A.size();
  Matrix C (n, Vector(n));
  
  for (int j=0; j<n; j++) {
    for (int k=0; k<n; k++) 
    {    
      Vector candidates, col;
      getCol(B, k, col);
      
      distances(A[j], col, candidates);
      candidates.push_back( A[j][k] );
      candidates.push_back( B[j][k] );
      
      // The resulting new 'distance' is the smallest element of the candidates list
      C[j][k] = *min_element(candidates.begin(), candidates.end());
    }
  }
  
  result.swap(C);
}

void TPathfinder::distances(const Vector &a, const Vector &b, Vector &result) const
{
  int n = a.size();
  Vector d;
  
  for (int i=0; i<n; i++) {
    d.push_back( distance(a[i], b[i]) );
  }
  
  result.swap(d);
}

double TPathfinder::distance(const double &a, const double &b) const
{
    // Check for infinity constant
    if (m_r >= 1 && m_r < INFINITY) 
    {
      return pow( pow(a, m_r) + pow(b, m_r), 1.0 / (double)m_r );
    }
    
    // r -> Infinity
    return max(a, b);
}

void TPathfinder::getCol(const Matrix &m, int i, Vector &col) const
{
  int n = m.size();
  Vector result (n);
  
  for (int j=0; j<n; j++) {
    result[j] = m[j][i];
  }
  
  col.swap(result);
}

void TPathfinder::toPFNET_sparse(TGraph *g)
{
  int n = g->nVertices;
  if (m_q < n-1) {
    BFS(g);
    return;
  }

  int neighIdx;
  vector<int> T;                        // Source node's neighbours
  vector<int> neighbours;
  vector<int> dirty;                    // Which nodes to reset after an iteration
  vector<SparseNode*> nodes(n);         // Node storage
  PQHeap<double> pq(n);                 // Priority queue, sorted by distance from the source vertex

  SparseNode *v, *u, *t;

  // Some statistics
  int nodesChecked = 0;

  // Prepare initial node values
  for (int i=0; i<n; i++)
  {
    nodes[i] = new SparseNode(i, INFINITY, OUTER);
  }
  
  for (int i=0; i<n; i++)
  {
    // Select a new source node
    v = nodes[i];
    v->setKey(0);
    //v->m_len = 0;
    g->getNeighboursFrom(v->m_v, T);

    // Reset the needed data structures
    dirty.clear();
    pq.makenull();

    pq.insert(v);
    v->m_state = ACTIVE;
    dirty.push_back(v->m_v);

    while (!T.empty())
    {
      u = static_cast<SparseNode*>(pq.deleteMin());
      u->m_state = COMPLETED;
      
      neighIdx = -1;
      // Is u a neighbour of v?
      for (int j=0; j<T.size(); j++) {
        if (T[j] == u->m_v) {
          neighIdx = j;
          break;
        }
      }
      
      if(neighIdx >= 0)
      {
        // The shortest distance to u is calculated, delete it from T
        T.erase(T.begin() + neighIdx);

        // Remove the edge if it isn't the shortest path between the vertices
        if (u->getKey() != *g->getEdge(v->m_v, u->m_v))
          g->removeEdge(v->m_v, u->m_v);
      }

      //if (u->m_len >= m_q) continue;
      
      g->getNeighboursFrom(u->m_v, neighbours);
      for (int j=0; j<neighbours.size(); j++)
      {
        t = nodes[neighbours[j]];

#ifdef STATISTICS
        nodesChecked++;
#endif
        if (t->m_state != COMPLETED) 
        {
          double newDist = distance(u->getKey(), *g->getEdge(u->m_v, t->m_v));
          //int newLen = u->m_len + 1;
          
          if (t->m_state == OUTER)
          {
            t->setKey(newDist);
            //t->m_len = newLen;
            t->m_state = ACTIVE;
            dirty.push_back(t->m_v);
            pq.insert(t);
          }
          else if (t->getKey() > newDist)
          {
            //t->m_len = newLen;
            pq.decreaseKey(t, newDist);
          }
        }
      }
    } // End while
    for (int j=0; j<dirty.size(); j++)
    {
      nodes[dirty[j]]->m_state = OUTER;
    }

    // We've finished one node
    updateProgress();
  }

#ifdef STATISTICS
  cout << "Sparse PF: " << nodesChecked << " nodes checked" << endl;
#endif
}

void TPathfinder::BFS(TGraph *g)
{
  int n = g->nVertices;
  queue<BFSNode*> q;
  vector<double> dist(n);
  vector<int> neighbours;
  vector<int>::iterator it;
  Matrix Dq (n, Vector(n, INFINITY));   // Resulting shortest distances

  for (int i=0; i<n; i++)
  {
    for (int j=0; j<n; j++) {
      dist[j] = INFINITY;
    }
    
    double dMax = 0;
    g->getNeighboursFrom(i, neighbours);

    for (it=neighbours.begin(); it<neighbours.end(); it++) {
      double w = *g->getEdge(i, *it);
      if (w > dMax) 
        dMax = w;
    }

    q.push(new BFSNode(i,0,0));
    dist[i] = 0;

    while(!q.empty())
    {
      BFSNode *u = q.front();
      q.pop();
      int newLen = u->m_len + 1;

      // This limits the search depth
      if (newLen <= m_q) 
      {
        g->getNeighboursFrom(u->m_idx, neighbours);
        for (it=neighbours.begin(); it<neighbours.end(); it++) 
        {
          int t = *it;
          double dNew = distance(u->m_d, *g->getEdge(u->m_idx, t));
          if (dNew <= dMax && dNew < dist[t]) {
            dist[t] = dNew;
            q.push(new BFSNode(t, dNew, newLen));
          }
        }
      }
    }
    
    // Save all the calculated distances into the target matrix Dq
    for (int j=0; j<n; j++)
      Dq[i][j] = dist[j];

    // We've finished one node
    updateProgress();
  }

  for (int i=0; i<n; i++) {
    for (int j=0; j<n; j++) 
    {  
      double *w = g->getEdge(i,j);
      
      if (w != NULL && (Dq[i][j] != *w))
        g->removeEdge(i,j);
    }
  }
}

void TPathfinder::updateProgress()
{
  if (!progressCallback) 
    return;

  double complete = ++m_done / (double) m_nodes;
  PyObject *arglist;
  /* Time to call the callback */
  arglist = Py_BuildValue("(d)", complete);
  PyObject_CallObject(progressCallback, arglist);
  Py_DECREF(arglist);
}

/*     ----------       Python interface     ---------       */

#include "externs.px"
#include "orange_api.hpp"
WRAPPER(Orange);
PyObject *Pathfinder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) BASED_ON (Orange, "()")
{
  PyTRY
  
    return WrapNewOrange(mlnew TPathfinder(), type);

  PyCATCH;
}

PyObject *Pathfinder_setProgressCallback(PyObject *self, PyObject *args) PYARGS(METH_VARARGS, "(function) -> None")
{
  PyTRY
    CAST_TO(TPathfinder, pf);
    
    PyObject *cb;
    if (PyArg_ParseTuple(args, "O:setProgressCallback", &cb)) {
        if (!PyCallable_Check(cb)) {
            PyErr_SetString(PyExc_TypeError, "parameter must be callable");
            return NULL;
        }
        Py_XINCREF(cb);                    /* Add a reference to new callback */
        Py_XDECREF(pf->progressCallback);  /* Dispose of previous callback */
        pf->setProgressCallback(cb);       /* Remember new callback */
    }
    
    RETURN_NONE;
  PyCATCH;
}

PyObject *Pathfinder_simplify(PyObject *self, PyObject *args) PYARGS(METH_VARARGS, "(r, q, graph) -> None")
{
  PyTRY
    CAST_TO(TPathfinder, pf);
    
    PyObject *pyGraph;
    TGraph *g;
    int r, q;
    
    if (!PyArg_ParseTuple(args, "iiO|s:simplify", &r, &q, &pyGraph))
      return PYNULL;

    g = PyOrange_AsGraph(pyGraph).getUnwrappedPtr();
    pf->toPFNET(r, q, g, "sparse");
  
    RETURN_NONE;
  PyCATCH;
}

#include "px/pathfinder.px"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.