Codebase list ibutils / d9ac677e-b280-4520-93af-f6b8ef650d18/main ibdm / ibdm / Bipartite.cc
d9ac677e-b280-4520-93af-f6b8ef650d18/main

Tree @d9ac677e-b280-4520-93af-f6b8ef650d18/main (Download .tar.gz)

Bipartite.cc @d9ac677e-b280-4520-93af-f6b8ef650d18/mainraw · history · blame

  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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/*
 * Copyright (c) 2004-2010 Mellanox Technologies LTD. All rights reserved.
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL) Version 2, available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * 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 "Bipartite.h"

//CLASS edge///////////////////////////////////

bool edge::isMatched() {
  vertex* ver1 = (vertex*)v1;
  vertex* ver2 = (vertex*)v2;

  if (((this == ver1->getPartner()) && (this != ver2->getPartner())) || ((this == ver2->getPartner()) && (this != ver1->getPartner())))
    cout << "-E- Error in edge matching" << endl;

  return (this == ver1->getPartner()) && (this == ver2->getPartner());
}

//CLASS vertex/////////////////////////////////

vertex::vertex(int n, side sd, int rad):id(n),s(sd),radix(rad)
{
  connections = new edge*[radix];
  pred = new edge*[radix];
  succ = new edge*[radix];

  partner = NULL;
  for (int i=0; i<radix; i++)
    connections[i] = pred[i] = succ[i] = NULL;

  predCount = succCount = 0;
  maxUsed = -1;
}

vertex::~vertex()
{
  delete[] connections;
  delete[] pred;
  delete[] succ;
}

int vertex::getID() const
{
  return id;
}

side vertex::getSide() const
{
  return s;
}

void vertex::delConnection(edge* e)
{
  int my_idx, other_idx;
  vertex* v;

  // Find the side we are connected at and edge index
  if (e->v1 == this) {
    my_idx = e->idx1;
    other_idx = e->idx2;
    v = (vertex*)(e->v2);
  }
  else if (e->v2 == this) {
    my_idx = e->idx2;
    other_idx = e->idx1;
    v = (vertex*)(e->v1);
  }
  else {
    cout << "-E- Edge not connected to current vertex" << endl;
    return;
  }

  if (my_idx >= radix || other_idx >= radix) {
    cout << "-E- Edge index illegal" << endl;
    return;
  }

  // Now disconnect
  connections[my_idx] = NULL;
  maxUsed--;
  v->connections[other_idx] = NULL;
  v->maxUsed--;
}

void vertex::pushConnection(edge* e)
{
  maxUsed++;
  if (maxUsed == radix) {
    cout << "-E- Can't push connection to vertex: " << id << ", exceeding radix!" << endl;
    return;
  }
  // Mark our side
  if (e->v1 == NULL) {
    e->v1 = this;
    e->idx1 = maxUsed;
  }
  else if (e->v2 == NULL) {
    e->v2 = this;
    e->idx2 = maxUsed;
  }
  else {
    cout << "-E- Can't push connection both edges are already filled" << endl;
    return;
  }

  if (maxUsed >= radix) {
    cout << "-E- maxUsed illegal" << endl;
    return;
  }

  // Now connect
  connections[maxUsed] = e;
}

edge* vertex::popConnection()
{
  // Look for a connection
  int i=0;
  while ((i<radix) && !connections[i])
    i++;
  // No real connection found
  if (i == radix)
    return NULL;

  edge* tmp = connections[i];

  // Disconnect chosen edge
  connections[i] = NULL;
  if (tmp->v1 == this) {
    vertex* v = (vertex*)(tmp->v2);
    v->connections[tmp->idx2] = NULL;
  }
  else if (tmp->v2 == this) {
    vertex* v = (vertex*)(tmp->v1);
    v->connections[tmp->idx1] = NULL;
  }
  else {
    cout << "-E- Edge not connected to current vertex" << endl;
    return NULL;
  }

  if (tmp->idx1 >= radix || tmp->idx2 >= radix) {
    cout << "-E- Edge index illegal" << endl;
    return NULL;
  }

  return tmp;
}

// For unmacthed vertex, find an unmatched neighbor and match the pair
bool vertex::match()
{
  // Already matched
  if (partner)
    return false;
  // Look for neighbor
  for (int i=0; i<radix; i++) {
    if (connections[i]) {
      vertex* v = (vertex*)(connections[i]->otherSide(this));
      if (!v->partner) {
        // Match
	partner = connections[i];
	v->partner = connections[i];
	return true;
      }
    }
  }
  return false;
}

edge* vertex::getPartner() const
{
  return partner;
}

bool vertex::getInLayers() const
{
  return inLayers;
}

void vertex::setInLayers(bool b)
{
  inLayers = b;
}

void vertex::resetLayersInfo()
{
  inLayers = false;
  succCount = predCount = 0;
  for (int i=0; i<radix; i++)
    succ[i] = pred[i] = NULL;
}

void vertex::addPartnerLayers(list<vertex*>& l)
{
  // No partner
  if (!partner)
    return;
  vertex* p = (vertex*)(partner->otherSide(this));
  // Partner already in one of the layers
  if (p->inLayers)
    return;
  // Add partner to the layer
  l.push_front(p);
  p->inLayers = true;
  // Update pred/succ relations
  if (succCount >= radix) {
    cout << "-E- More successors than radix" << endl;
    return;
  }
  succ[succCount] = partner;
  succCount++;

  if (p->predCount >= radix) {
    cout << "-E- More predecessors than radix" << endl;
    return;
  }
  p->pred[p->predCount] = partner;
  p->predCount++;
}

bool vertex::addNonPartnersLayers(list<vertex*>& l)
{
  vertex* prtn = NULL;
  bool res = false;

  if (partner)
    prtn = (vertex*)(partner->otherSide(this));

  for (int i=0; i<radix; i++) {
    vertex* v = (vertex*)(connections[i]->otherSide(this));
    if ((v != prtn) && (!v->inLayers)) {
      // free vertex found
      if (!v->partner)
	res = true;
      // Add vertex to the layer
      l.push_front(v);
      v->inLayers = true;
      // Update pred/succ relations
      if (succCount >= radix) {
	cout << "-E- More successors than radix" << endl;
	return false;
      }
      succ[succCount] = connections[i];
      succCount++;

      if (v->predCount >= radix) {
	cout << "-E- More predecessors than radix" << endl;
	return false;
      }
      v->pred[v->predCount] = connections[i];
      v->predCount++;
    }
  }
  return res;
}

vertex* vertex::getPredecessor() const
{
  vertex* v = NULL;
  // Find a valid predecessor still in layers
  for (int i=0; i<radix; i++) {
    if (pred[i]) {
      vertex* v2 = (vertex*)(pred[i]->otherSide(this));
      if (v2->inLayers) {
	v = v2;
	break;
      }
    }
  }
  return v;
}

// Flip edge status on augmenting path
void vertex::flipPredEdge(int idx)
{
  int i=0;
  // Find an edge to a predecessor
  for (i=0; i<radix; i++)
    if (pred[i]) {
      vertex* v1 = (vertex*)pred[i]->v1;
      vertex* v2 = (vertex*)pred[i]->v2;
      if (v1->getInLayers() && v2->getInLayers())
	break;
    }

  if (i == radix) {
    cout << "-E- Could find predecessor for flip" << endl;
    return;
  }
  // The predecessor vertex
  vertex* v = (vertex*) pred[i]->otherSide(this);

  // Unmatch edge
  if (idx)
	v->partner = NULL;
  // Match edge
  else {
    partner = pred[i];
    v->partner = pred[i];
  }
}

// Removing vertex from layers and updating successors/predecessors
void vertex::unLink(list<vertex*>& l)
{
  inLayers = false;
  for (int i=0; i<radix; i++) {
    if (succ[i]) {
      vertex* v = (vertex*)succ[i]->otherSide(this);
      if (v->inLayers) {
	v->predCount--;
	// v has no more predecessors, schedule for removal from layers...
	if (!v->predCount)
	  l.push_back(v);
	succ[i] = NULL;
      }
    }
  }
  succCount = 0;
}

//CLASS Bipartite

// C'tor

Bipartite::Bipartite(int s, int r):size(s),radix(r)
{
  leftSide = new vertex*[size];
  rightSide = new vertex*[size];

  for (int i=0; i<size; i++) {
    leftSide[i] = new vertex(i,LEFT,radix);
    rightSide[i] = new vertex(i,RIGHT,radix);
  }
}

///////////////////////////////////////////////////////////

// D'tor

Bipartite::~Bipartite()
{
  // Free vertices
  for (int i=0; i<size; i++) {
    delete leftSide[i];
    delete rightSide[i];
  }
  delete[] leftSide;
  delete[] rightSide;

  // Free edges
  while (List.size()) {
    edge* e = (edge*)(List.front());
    List.pop_front();
    delete e;
  }
}

////////////////////////////////////////////////////////////

// Get radix

int Bipartite::getRadix() const
{
  return radix;
}

////////////////////////////////////////////////////////////

// Set edges listt iterator to first

bool Bipartite::setIterFirst()
{
  it = List.begin();
  if (it == List.end())
    return false;
  return true;
}

///////////////////////////////////////////////////////////

// Set edges list iterator to next

bool Bipartite::setIterNext()
{
  if (it == List.end())
    return false;
  it++;
  if (it == List.end())
    return false;
  return true;
}

////////////////////////////////////////////////////////////

// Get current edge's request data

inputData Bipartite::getReqDat()
{
  if (it == List.end()) {
    cout << "-E- Iterator points to list end" << endl;
  }
  return ((edge*)(*it))->reqDat;
}

/////////////////////////////////////////////////////////////

// Add connection between the nodes to the graph

void Bipartite::connectNodes(int n1, int n2, inputData reqDat)
{
  if ((n1 >= size) || (n2 >= size)) {
    cout << "-E- Node index exceeds size" << endl;
    return;
  }
  // Create new edge
  edge* newEdge = new edge;

  // Init edge fields and add to it the edges list
  newEdge->it = List.insert(List.end(), newEdge);
  newEdge->reqDat = reqDat;
  newEdge->v1 = newEdge->v2 = NULL;

  // Connect the vertices
  leftSide[n1]->pushConnection(newEdge);
  rightSide[n2]->pushConnection(newEdge);
}

////////////////////////////////////////////////////////////////

// Find maximal matching

void Bipartite::maximalMatch()
{
  // Invoke match on left-side vertices
  for (int i=0; i<size; i++)
    leftSide[i]->match();
}

////////////////////////////////////////////////////////////////

// Find maximum matching

// Hopcroft-Karp algorithm
Bipartite* Bipartite::maximumMatch()
{
  // First find a maximal match
  maximalMatch();

  list<void*>::iterator it2 = List.begin();
  list<vertex*> l1, l2;
  list<vertex*>::iterator it;

  // Loop on algorithm phases
  while (1) {
    bool hardStop = false;
    // First reset layers info
    for (int i=0; i<size; i++) {
      leftSide[i]->resetLayersInfo();
      rightSide[i]->resetLayersInfo();
    }
    // Add free left-side vertices to l1 (building layer 0)
    l1.clear();
    for (int i=0; i<size; i++) {
      if (!leftSide[i]->getPartner()) {
	l1.push_front(leftSide[i]);
	leftSide[i]->setInLayers(true);
      }
    }
    // This is our termination condition
    // Maximum matching achieved
    if (l1.empty())
      break;
    // Loop on building layers
    while (1) {
      bool stop = false;
      l2.clear();
      // Add all non-partners of vertices in l1 to layers (l2)
      // We signal to stop if a free (right-side) vertex is entering l2
      for (it = l1.begin(); it != l1.end(); it++)
	if ((*it)->addNonPartnersLayers(l2))
	  stop = true;
      // Found free vertex among right-side vertices
      if (stop) {
	// There are augmenting paths, apply them
	augment(l2);
	break;
      }
      // This is a terminal condition
      if (l2.empty()) {
	hardStop = true;
	break;
      }
      // Add partners of vertices in l2 to layers (l1)
      l1.clear();
      for (it = l2.begin(); it!= l2.end(); it++)
	(*it)->addPartnerLayers(l1);
      // This is a terminal condition
      if (l1.empty()) {
	hardStop = true;
	break;
      }
    }
    // Maximum matching achieved
    if (hardStop)
      break;
  }
  // Build the matching graph
  Bipartite* M = new Bipartite(size, 1);
  // Go over all edges and move matched one to the new graph
  it2 = List.begin();
  while (it2 != List.end()) {
    edge* e = (edge*)(*it2);
    if (e->isMatched()) {
      vertex* v1 = (vertex*)(e->v1);
      vertex* v2 = (vertex*)(e->v2);
      // Unlink vertices
      ((vertex*)(e->v1))->delConnection(e);
      // Update edges list
      it2 = List.erase(it2);
      // Add link to the new graph
      if (v1->getSide() == LEFT)
	M->connectNodes(v1->getID(), v2->getID(), e->reqDat);
      else
	M->connectNodes(v2->getID(), v1->getID(), e->reqDat);
      // Free memory
      delete e;
    }
    else
      it2++;
  }
  return M;
}

//////////////////////////////////////////////////////////////////////

// Apply augmenting paths on the matching

void Bipartite::augment(list<vertex*>& l)
{
  // Use delQ to store vertex scheduled for the removal from layers
  list<vertex*> delQ;
  // Remove non-free vertices
  list<vertex*>::iterator it = l.begin();
  while (it != l.end()) {
    if ((*it)->getPartner()) {
      delQ.push_front((*it));
      it = l.erase(it);
    }
    else
      it++;
  }
  // Get rid of non-free vertices
  while (!delQ.empty()) {
    vertex* fr = delQ.front();
    delQ.pop_front();
    fr->unLink(delQ);
  }

  if (l.empty()) {
    cout << "-E- No free vertices left!" << endl;
    return;
  }
  // Augment and reset pred/succ relations
  while (!l.empty()) {
    vertex* curr = l.front();
    l.pop_front();
    int idx = 0;
    // Backtrace the path and augment
    int length=0;
    while (1) {
      delQ.push_front(curr);
      // Its either the end of a path or an error
      if (!curr->getPredecessor()) {
	if (!idx && length) {
	  cout << "-E- This vertex must have predecessor" << endl;
	  return;
	}
	break;
      }
      // Flip edge status
      curr->flipPredEdge(idx);
      // Move back
      curr = curr->getPredecessor();
      idx = (idx+1)%2;
      length++;
    }
    // Now clean the delQ
    while (!delQ.empty()) {
      vertex* fr = delQ.front();
      delQ.pop_front();
      fr->unLink(delQ);
    }
  }
}

////////////////////////////////////////////////////////////////////////

// Perform Euler decomposition

void Bipartite::decompose(Bipartite** bp1, Bipartite** bp2)
{
  if (radix < 2) {
    cout << "-E- Radix value illegal: " << radix << endl;
    return;
  }

  // Create new graphs
  Bipartite* arr[2];
  arr[0] = new Bipartite(size, radix/2);
  arr[1] = new Bipartite(size, radix/2);

  // Continue as long as unassigned edges left
  while (!List.empty()) {
    int idx = 0;
    edge* e = (edge*)List.front();
    vertex* current = (vertex*)e->v1;
    e = current->popConnection();

    while (e) {
      // Connect nodes in the new graphs
      vertex* v1 = (vertex*)e->v1;
      vertex* v2 = (vertex*)e->v2;
      if (v1->getSide() == LEFT)
	arr[idx]->connectNodes(v1->getID(), v2->getID(), e->reqDat);
      else
	arr[idx]->connectNodes(v2->getID(), v1->getID(), e->reqDat);
      idx = (idx+1)%2;
      // Remove edge from list
      List.erase(e->it);
      // Pick next vertex
      current = (vertex*) e->otherSide(current);
      // Free memory
      delete e;
      // Pick next edge
      e = current->popConnection();
    }
  }
  *bp1 = arr[0];
  *bp2 = arr[1];
}