-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmp_c.py
More file actions
executable file
·1552 lines (1436 loc) · 72.3 KB
/
smp_c.py
File metadata and controls
executable file
·1552 lines (1436 loc) · 72.3 KB
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""[smp_c.py]
Copyright (c) 2014, Andrew Perrault
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.
"""
from __future__ import with_statement
import argparse
import cplex_py
import os
import string
resident_dict = {}
hospital_dict = {}
couple_dict = {}
NIL_HOSPITAL_UID = 999999
NIL_HOSPITAL_SYMBOL = "-1"
TREEMEM_LIM = "12000"
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i + 1, r):
indices[j] = indices[j - 1] + 1
yield tuple(pool[i] for i in indices)
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x + [y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
class UIDAllocator():
def __init__(self, first_uid=None):
self.last_uid = first_uid - 1
def allocate_uid(self):
if self.last_uid is None:
self.last_uid = 0
else:
self.last_uid = self.last_uid + 1
return self.last_uid
class PreferenceFunction():
def get_all_dispreferred(self, uid):
raise Exception('must override in subclass')
def get_all_weakly_preferred(self, uid):
raise Exception('must override in subclass')
def get_ordering(self):
raise Exception('must override in subclass')
def get_rank(self, uid):
raise Exception('must override in subclass')
class ListPreferenceFunction(PreferenceFunction):
def __init__(self, internal_list):
self.internal_list = internal_list
# list assumed in decreasing preference order,
# i.e., most preferred first
def get_all_preferred(self, uid):
preferred = []
for agent in self.internal_list:
if agent == uid:
return preferred
preferred.append(agent)
raise Exception('uid not in preference list: %r; internal_list; %r'
% (uid, self.internal_list))
def get_all_dispreferred(self, uid):
dispreferred = []
for agent in reversed(self.internal_list):
if agent == uid:
return dispreferred
dispreferred.append(agent)
raise Exception('uid not in preference list')
def get_all_weakly_preferred(self, uid):
return self.get_all_preferred(uid=uid) + [uid]
def get_ordering(self):
return self.internal_list
def get_rank(self, uid):
return self.internal_list.index(uid)
class JointPreferenceFunction():
def get_cardinality(self):
raise Exception('must override in subclass')
def get_all_dispreferred(self, assignment, indices):
raise Exception('must override in subclass')
def get_all_weakly_preferred(self, assignment, indices):
raise Exception('must override in subclass')
def get_ordering(self):
raise Exception('must override in subclass')
def get_rank(self, item):
raise Exception('must override in subclass')
class ListJointPreferenceFunction(JointPreferenceFunction):
def __init__(self, internal_list, cardinality):
# list of tuples of size of joint agent
self.internal_list = internal_list
self.cardinality = cardinality
def get_cardinality(self):
return self.cardinality
# indices are indices that must remained fixed
def _check_suitability(self, assignment, to_test, indices):
suitable = True
for i, item in enumerate(to_test):
if i in indices and to_test[i] != assignment[i]:
suitable = False
break
return suitable
def get_all_dispreferred(self, assignment, indices):
dispreferred = []
for a in reversed(self.internal_list):
if a == assignment:
return dispreferred
if self._check_suitability(assignment=assignment,
to_test=a, indices=indices):
dispreferred.append(a)
raise Exception('uid not in preference list')
def get_all_weakly_preferred(self, assignment, indices):
weakly_preferred = []
for a in self.internal_list:
if a == assignment:
weakly_preferred.append(a)
return weakly_preferred
if self._check_suitability(assignment=assignment,
to_test=a, indices=indices):
weakly_preferred.append(a)
raise Exception('uid not in preference list')
def get_ordering(self):
return self.internal_list
def get_rank(self, item):
return self.internal_list.index(item)
class Agent():
def __init__(self, uid):
self.uid = uid
assert self.uid is not None
def __hash__(self):
return self.uid
def __eq__(self, other):
return self.uid == other.uid
class SinglePreferrer(Agent):
def __init__(self, preference_function, uid):
Agent.__init__(self, uid=uid)
self.preference_function = preference_function
def get_all_preferred(self, uid):
return self.preference_function.get_all_preferred(uid=uid)
def get_all_dispreferred(self, uid):
return self.preference_function.get_all_dispreferred(uid=uid)
def get_all_weakly_preferred(self, uid):
return self.preference_function.get_all_weakly_preferred(uid=uid)
def get_ordering(self):
return self.preference_function.get_ordering()
def get_rank(self, uid):
return self.preference_function.get_rank(uid=uid)
class JointPreferrer(Agent):
def __init__(self, preference_function, uid, residents):
Agent.__init__(self, uid=uid)
self.preference_function = preference_function
assert isinstance(self.preference_function, JointPreferenceFunction)
self.residents = residents
assert (len(self.residents)
== self.preference_function.get_cardinality())
def get_all_preferred(self, assignment, indices):
assert len(indices) <= self.size
return self.preference_function.get_all_preferred(
assignment=assignment, indices=indices)
def get_all_dispreferred(self, assignment, indices):
assert len(indices) <= self.size
return self.preference_function.get_all_dispreferred(
assignment=assignment, indices=indices)
def get_all_weakly_preferred(self, assignment, indices):
assert len(indices) <= self.size
return self.preference_function.get_all_weakly_preferred(
assignment=assignment, indices=indices)
def get_ordering(self):
return self.preference_function.get_ordering()
def get_rank(self, item):
return self.preference_function.get_rank(item=item)
class Hospital(SinglePreferrer):
def __init__(self, preference_function, uid, capacity=None):
SinglePreferrer.__init__(self,
preference_function=preference_function,
uid=uid)
self.capacity = capacity
if self.capacity is not None:
assert isinstance(self.capacity, int)
hospital_dict[self.uid] = self
class NilHospital(Hospital):
def __init__(self):
Hospital.__init__(self, preference_function=None, uid=NIL_HOSPITAL_UID)
self.capacity = 10
if self.capacity is not None:
assert isinstance(self.capacity, int)
hospital_dict[self.uid] = self
def get_all_preferred(self, assignment):
return []
def get_all_weakly_preferred(self, assignment):
return []
class Resident(SinglePreferrer):
def __init__(self, uid, preference_function=None, couple=None):
SinglePreferrer.__init__(self, preference_function=preference_function,
uid=uid)
resident_dict[self.uid] = self
self.couple = couple
class Couple(JointPreferrer):
def __init__(self, preference_function, uid, residents):
JointPreferrer.__init__(self, preference_function=preference_function,
uid=uid, residents=residents)
self.residents = residents
couple_dict[uid] = self
for resident in self.residents:
resident.couple = self
r0_ranked = []
r1_ranked = []
for (h0, h1) in self.preference_function.get_ordering():
r0_ranked.append(h0)
r1_ranked.append(h1)
self.ranked_hospitals = {}
self.ranked_hospitals[self.residents[0]] = list(set(r0_ranked))
self.ranked_hospitals[self.residents[1]] = list(set(r1_ranked))
self.size = 2
def get_other_member(self, member):
assert member in self.residents
for person in self.residents:
if person != member:
return person
def get_ranked_hospitals(self, member=None):
if member is None:
return self.preference_function.get_ordering()
return self.ranked_hospitals[member]
class DIMACSConstraint():
def __init__(self, var_list):
self.var_list = var_list
assert len(self.var_list) > 0
def render(self):
raise Exception('must override in subclass')
class DIMACSClause(DIMACSConstraint):
def __init__(self, var_list):
DIMACSConstraint.__init__(self, var_list=var_list)
def render(self):
return ' '.join([str(var) for var in self.var_list]) + ' 0'
class ConstraintsBuffer():
def __init__(self, filename):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('')
self.buffer_list = []
self.buffer_size = 5000
def append(self, constraint):
if len(self.buffer_list) < self.buffer_size:
self.buffer_list.append(constraint)
else:
with open(self.filename, 'a') as f:
for item in self.buffer_list:
f.write(item.render() + '\n')
f.write(constraint.render() + '\n')
self.buffer_list = []
def flush(self, variable_registry=None):
with open(self.filename, 'a') as f:
for item in self.buffer_list:
f.write(item.render() + '\n')
if variable_registry is not None:
print ' '.join([
('-' + variable_registry[abs(var)]
if var < 0 else variable_registry[abs(var)])
for var in item.var_list])
self.buffer_list = []
NIL_HOSPITAL = NilHospital()
def load_matching_from_file(filename):
matching = {}
with open(filename, 'r') as f:
for line in f:
line = line.strip()
if len(line) == 0:
continue
if line.startswith('#'):
continue
split = line.split()
if split[0] == 'r':
if split[2] == NIL_HOSPITAL_SYMBOL:
matching[int(split[1])] = NIL_HOSPITAL_UID
else:
matching[int(split[1])] = int(split[2])
return matching
class ProblemInstance():
def __init__(self, hospitals, singles, couples):
self.hospitals = hospitals
self.singles = singles
self.couples = couples
self.matching = {}
@classmethod
def from_file(cls, filename, append_nil=False):
# does not check that all referred to programs and residents exist
# after problem is defined
# does check for duplicate residents and programs
resident_dict = {}
hospital_dict = {}
couple_dict = {}
with open(filename, 'r') as f:
hospitals = []
singles = []
couples = []
for line in f:
if (line.startswith('#') or line.startswith(' ')
or line.startswith('\n') or line.startswith('\r')):
continue
items = line.strip().split()
if line.startswith('r'):
if int(items[1]) in resident_dict:
raise Exception('duplicate resident: %d'
% int(items[1]))
rol = []
for i in xrange(2, len(items)):
rol.append(int(items[i]))
# APPENDING nil so that when loading the match in for
# comparison purposes, we have a rank spot for
# the nil hospital
if append_nil:
if rol[-1] == int(NIL_HOSPITAL_SYMBOL):
rol.pop()
if rol[-1] != NIL_HOSPITAL_UID:
rol.append(NIL_HOSPITAL_UID)
s = Resident(uid=int(items[1]),
preference_function=ListPreferenceFunction(
internal_list=rol))
singles.append(s)
elif line.startswith('p'):
if int(items[1]) in hospital_dict:
raise Exception(
'duplicate program: %d' % int(items[1]))
rol = []
for i in xrange(3, len(items)):
rol.append(int(items[i]))
h = Hospital(uid=int(items[1]),
preference_function=ListPreferenceFunction(
internal_list=rol), capacity=int(items[2]))
hospitals.append(h)
elif line.startswith('c'):
if int(items[1]) in couple_dict:
raise Exception('duplicate couple: %d' % int(items[1]))
if int(items[2]) in resident_dict:
raise Exception(
'resident in couple %d already defined: %d'
% (int(items[1]), int(items[2])))
if int(items[3]) in resident_dict:
raise Exception(
'resident in couple %d already defined: %d'
% (int(items[1]), int(items[3])))
rol = []
for i in xrange(4, len(items)):
if i % 2 != 0:
continue
rol.append((int(items[i]) if items[i]
!= NIL_HOSPITAL_SYMBOL else
NIL_HOSPITAL_UID, int(items[i + 1]) if
items[i + 1] != NIL_HOSPITAL_SYMBOL
else NIL_HOSPITAL_UID))
# APPENDING nil so that when loading the match in for
# comparison purposes, we have a rank spot for the
# nil hospital
if append_nil:
if rol[-1] != (NIL_HOSPITAL_UID, NIL_HOSPITAL_UID):
rol.append((NIL_HOSPITAL_UID, NIL_HOSPITAL_UID))
r0 = Resident(uid=int(items[2]))
r1 = Resident(uid=int(items[3]))
c = Couple(uid=int(items[1]),
preference_function=ListJointPreferenceFunction(
internal_list=rol, cardinality=2),
residents=[r0, r1])
couples.append(c)
else:
raise Exception('line not readable: %s' % line)
return cls(hospitals=hospitals, singles=singles, couples=couples)
# a matching here is just a dictionary from resident_uid -> program_uid
@staticmethod
def print_matching(matching, filename, header=None):
with open(filename, 'w') as f:
if header is not None:
f.write('# %s\n' % header)
if len(matching) == 0:
f.write('m 0\n')
return
f.write('m 1\n')
for resident_uid in matching.keys():
if matching[resident_uid] == NIL_HOSPITAL_UID:
f.write('r %d %s\n' % (resident_uid, NIL_HOSPITAL_SYMBOL))
else:
f.write('r %d %d\n' % (resident_uid,
matching[resident_uid]))
def solve_mip(self, solver, verbose=False, verify_file=None,
run_solver=True, problem_name='problem',
output_filename=None):
constraints = cplex_py.ConstraintsCollection()
binaries = []
def expand_match_var(resident, h, coeff=1.):
if resident.couple is None:
return [cplex_py.CoeffVar(coeff=coeff, var='x_%d,%d' %
(resident.uid, h.uid))]
else:
if resident.couple.residents[0] == resident:
return [cplex_py.CoeffVar(coeff=coeff,
var=('x_%d,%d,%d' % (resident.couple.uid,
h_uid_pair[0],
h_uid_pair[1])))
for h_uid_pair in filter(
lambda x: x[0] == h.uid,
resident.couple.get_ordering())]
else:
return [cplex_py.CoeffVar(coeff=coeff,
var=('x_%d,%d,%d' % (resident.couple.uid,
h_uid_pair[0],
h_uid_pair[1])))
for h_uid_pair in filter(
lambda x: x[1] == h.uid,
resident.couple.get_ordering())]
# matching constraints
for resident in self.singles:
constraints.add_constraint(cplex_py.EqualityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(var='x_%d,%d' % (resident.uid, h_uid))
for h_uid in (resident.get_ordering()
+ [NIL_HOSPITAL_UID])]),
const_side=cplex_py.CoeffVar(1.)))
binaries.extend(['x_%d,%d' % (resident.uid, h_uid) for h_uid in (
resident.get_ordering() + [NIL_HOSPITAL_UID])])
for couple in self.couples:
constraints.add_constraint(cplex_py.EqualityConstraint(
var_side=cplex_py.Expression([cplex_py.CoeffVar(
var='x_%d,%d,%d' % (couple.uid, h_uid_pair[0],
h_uid_pair[1]))
for h_uid_pair in (couple.get_ordering() + [
(NIL_HOSPITAL_UID, NIL_HOSPITAL_UID)])]),
const_side=cplex_py.CoeffVar(1.)))
binaries.extend(['x_%d,%d,%d' % (couple.uid, h_uid_pair[0],
h_uid_pair[1])
for h_uid_pair in (couple.get_ordering() + [
(NIL_HOSPITAL_UID, NIL_HOSPITAL_UID)])])
for h in self.hospitals:
var_side = []
if len(h.get_ordering()) > 0:
for resident_uid in h.get_ordering():
var_side.extend(expand_match_var(
resident_dict[resident_uid], h))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(var_side),
const_side=cplex_py.CoeffVar(h.capacity)))
# stability constraints
# singles
for r in self.singles:
ordering = r.get_ordering()
for h_uid in ordering:
h = hospital_dict[h_uid]
var_side = []
for r_prime in h.get_all_weakly_preferred(r.uid):
var_side.extend(expand_match_var(resident_dict[r_prime],
h, coeff=-1.))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(var_side + [
cplex_py.CoeffVar(coeff=-h.capacity,
var='x_%d,%d' % (r.uid, p_prime_uid))
for p_prime_uid in r.get_all_weakly_preferred(h.uid)]),
const_side=cplex_py.CoeffVar(-h.capacity)))
# one member of a couple
for couple in self.couples:
ordering = couple.get_ranked_hospitals()
r0 = couple.residents[0]
r1 = couple.residents[1]
for number in xrange(len(ordering)):
h0 = hospital_dict[ordering[number][0]]
h1 = hospital_dict[ordering[number][1]]
if not h0 == h1:
var_side = []
for r_prime in h0.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h0, coeff=-1.))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression([cplex_py.CoeffVar(
coeff=-h0.capacity,
var='x_%d,%d,%d' % (
couple.uid, h_prime_pair[0], h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred((h0.uid, h1.uid),
[])]
+ var_side + expand_match_var(r1, h1,
coeff=h0.capacity)),
const_side=cplex_py.CoeffVar(0.)))
var_side = []
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h1, coeff=-1.))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression([cplex_py.CoeffVar(
coeff=-h1.capacity,
var='x_%d,%d,%d' % (couple.uid, h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred((h0.uid, h1.uid),
[])]
+ var_side + expand_match_var(r0, h0,
coeff=h1.capacity)),
const_side=cplex_py.CoeffVar(0.)))
else:
if h0.get_rank(r0.uid) < h0.get_rank(r1.uid):
# r0 preferred to r1
var_side = []
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h1, coeff=-1.))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(
coeff=-h0.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred(
(h0.uid, h1.uid), [])]
+ var_side + expand_match_var(
r1, h1,
coeff=h0.capacity)),
const_side=cplex_py.CoeffVar(0.)))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(coeff=-h1.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred((h0.uid,
h1.uid),
[])]
+ var_side
+ expand_match_var(r0, h0,
coeff=h1.capacity)),
const_side=cplex_py.CoeffVar(0.)))
else:
var_side = []
for r_prime in h0.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h0, coeff=-1.))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(coeff=-h0.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred((h0.uid,
h1.uid),
[])]
+ var_side + expand_match_var(
r1, h1, coeff=h0.capacity)),
const_side=cplex_py.CoeffVar(0.)))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(coeff=-h1.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred((h0.uid,
h1.uid),
[])]
+ var_side
+ expand_match_var(r0, h0,
coeff=h1.capacity)),
const_side=cplex_py.CoeffVar(0.)))
# also consider switch to (nil, nil)
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(coeff=-1.,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in couple.get_ordering() +
[(NIL_HOSPITAL_UID, NIL_HOSPITAL_UID)]]
+ expand_match_var(r1, NIL_HOSPITAL, coeff=1.)),
const_side=cplex_py.CoeffVar(0.)))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
[cplex_py.CoeffVar(coeff=-1., var='x_%d,%d,%d' %
(couple.uid, h_prime_pair[0], h_prime_pair[1]))
for h_prime_pair in couple.get_ordering() +
[(NIL_HOSPITAL_UID, NIL_HOSPITAL_UID)]]
+ expand_match_var(r0, NIL_HOSPITAL, coeff=1.)),
const_side=cplex_py.CoeffVar(0.)))
# both members of a couple switch
for couple in self.couples:
ordering = couple.get_ranked_hospitals()
r0 = couple.residents[0]
r1 = couple.residents[1]
# need to find all hospitals that are ranked by the
# 2nd member of a couple
# note: could generate fewer alpha variables if intelligent
generated_alphas = {}
for (h0_uid, h1_uid) in ordering:
h0 = hospital_dict[h0_uid]
h1 = hospital_dict[h1_uid]
if (h0.capacity <= 1 or h0_uid == NIL_HOSPITAL_UID
or h1.capacity <= 1 or h1_uid == NIL_HOSPITAL_UID
or (r1.uid, h1_uid) in generated_alphas
or (r0.uid, h0_uid) in generated_alphas):
continue
else:
binaries.append('alpha_%d,%d' % (r1.uid, h1_uid))
generated_alphas[(r1.uid, h1_uid)] = True
var_side = []
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(
expand_match_var(resident_dict[r_prime], h1,
coeff=-1.))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(var_side + [
cplex_py.CoeffVar(coeff=h1.capacity,
var='alpha_%d,%d'
% (r1.uid, h1.uid))]),
const_side=cplex_py.CoeffVar(coeff=0.)))
for number in xrange(len(ordering)):
h0 = hospital_dict[ordering[number][0]]
h1 = hospital_dict[ordering[number][1]]
if h0.capacity == 0 or h1.capacity == 0:
continue
if not h0 == h1:
var_side = []
if (h1.uid != NIL_HOSPITAL_UID and h1.capacity > 1
and h0.uid != NIL_HOSPITAL_UID
and h0.capacity > 1):
for r_prime in h0.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h0, coeff=-1.))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
expand_match_var(r0, h0, -h0.capacity)
+ expand_match_var(r1, h1, -h0.capacity)
+ [cplex_py.CoeffVar(coeff=-h0.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred(
(h0.uid, h1.uid), [])]
+ var_side
+ [cplex_py.CoeffVar(coeff=-h0.capacity,
var='alpha_%d,%d' % (r1.uid, h1.uid))]),
const_side=cplex_py.CoeffVar(-h0.capacity)))
elif h1.uid == NIL_HOSPITAL_UID or h1.capacity == 1:
for r_prime in h0.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h0, coeff=-1.))
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime],
h1, coeff=-h0.capacity))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
expand_match_var(r0, h0, -h0.capacity)
+ expand_match_var(r1, h1, -h0.capacity)
+ [cplex_py.CoeffVar(coeff=-h0.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred(
(h0.uid, h1.uid), [])]
+ var_side),
const_side=cplex_py.CoeffVar(-h0.capacity)))
elif h0.uid == NIL_HOSPITAL_UID or h0.capacity == 1:
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(expand_match_var(resident_dict[
r_prime], h1, coeff=-1.))
for r_prime in h0.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(resident_dict[
r_prime], h0, coeff=-h1.capacity))
constraints.add_constraint(
cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
expand_match_var(r0, h0, -h1.capacity)
+ expand_match_var(r1, h1, -h1.capacity)
+ [cplex_py.CoeffVar(coeff=-h1.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred(
(h0.uid, h1.uid), [])]
+ var_side),
const_side=cplex_py.CoeffVar(-h1.capacity)))
else:
raise Exception('should never get here')
else:
if h0.capacity == 1:
continue
var_side = []
if h0.get_rank(r0.uid) < h0.get_rank(r1.uid):
# r0 preferred to r1
for r_prime in h1.get_all_weakly_preferred(r1.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h1, coeff=-1.))
else:
for r_prime in h1.get_all_weakly_preferred(r0.uid):
var_side.extend(expand_match_var(
resident_dict[r_prime], h0, coeff=-1.))
constraints.add_constraint(cplex_py.InequalityConstraint(
var_side=cplex_py.Expression(
expand_match_var(r0, h0, -h0.capacity)
+ expand_match_var(r1, h1, -h0.capacity)
+ [cplex_py.CoeffVar(coeff=-h0.capacity,
var='x_%d,%d,%d' % (couple.uid,
h_prime_pair[0],
h_prime_pair[1]))
for h_prime_pair in
couple.get_all_weakly_preferred(
(h0.uid, h1.uid), [])]
+ var_side),
const_side=cplex_py.CoeffVar(-h0.capacity + 1)))
if verify_file is not None:
r_match_dict = {}
c_match_dict = {}
h_match_dict = {}
with open(verify_file, 'r') as f:
for line in f:
if line.startswith('r '):
s = line.split()
h = (hospital_dict[int(s[2])]
if int(s[2]) != -1 else NIL_HOSPITAL)
r = resident_dict[int(s[1])]
r_match_dict[r] = h
h_match_dict[h] = r
for couple in self.couples:
ordering = couple.get_ordering()
r0 = couple.residents[0]
r1 = couple.residents[1]
c_match_dict[couple] = (r_match_dict[couple.residents[0]],
r_match_dict[couple.residents[1]])
def eval_cplex_constraint(constraint):
if isinstance(constraint, cplex_py.InequalityConstraint):
total_left = 0
for var in constraint.var_side.terms_list:
if var.var.startswith('alpha'):
return (True, 0.0)
if var.var.startswith('x_'):
s = var.var.split(',')
s[0] = s[0][2:]
if len(s) == 3:
var_val = (1. if c_match_dict[
couple_dict[int(s[0])]]
== (hospital_dict[int(s[1])],
hospital_dict[int(s[2])]) else 0.)
else:
var_val = (1. if r_match_dict[
resident_dict[int(s[0])]]
== hospital_dict[int(s[1])] else 0.)
total_left += (var.coeff * var_val
if var.coeff is not None
else var_val)
return ((total_left <= constraint.const_side.coeff),
total_left)
if isinstance(constraint, cplex_py.EqualityConstraint):
total_left = 0
for var in constraint.var_side.terms_list:
if var.var.startswith('alpha'):
return (True, 0.0)
if var.var.startswith('x_'):
s = var.var.split(',')
s[0] = s[0][2:]
if len(s) == 3:
var_val = (1. if c_match_dict[
couple_dict[int(s[0])]] ==
(hospital_dict[int(s[1])],
hospital_dict[int(s[2])]) else 0.)
else:
var_val = (1. if r_match_dict[
resident_dict[int(s[0])]]
== hospital_dict[int(s[1])] else 0.)
total_left += (var.coeff * var_val
if var.coeff is not None
else var_val)
return ((total_left == constraint.const_side.coeff),
total_left)
for constraint in constraints.constraints:
if not eval_cplex_constraint(constraint)[0]:
print constraint.var_side
print constraint.const_side
print eval_cplex_constraint(constraint)[1]
return
if run_solver:
(objective, vals) = cplex_py.solve_using_CPLEX(
objective=cplex_py.Expression(
terms_list=[cplex_py.CoeffVar(var=binaries[0])]),
constraints=constraints, binaries=binaries,
maximize=True, clean_files=True,
treememory=TREEMEM_LIM, run_solver=run_solver,
problem_name=problem_name, solver_path=solver)
else:
(objective, vals) = cplex_py.solve_using_CPLEX(
objective=cplex_py.Expression(
terms_list=[cplex_py.CoeffVar(var=binaries[0])]),
constraints=constraints, binaries=binaries, maximize=True,
clean_files=True, treememory=TREEMEM_LIM,
run_solver=run_solver, problem_name=problem_name,
solver_path=solver, filename=output_filename)
if run_solver:
if objective is None:
return
else:
for val in vals:
if vals[val] == 1. and val.startswith('x_'):
s = val.split(',')
s[0] = s[0][2:]
if len(s) == 3:
couple = couple_dict[int(s[0])]
if int(s[1]) != NIL_HOSPITAL_UID:
self.matching[
couple.residents[0].uid] = int(s[1])
if int(s[2]) != NIL_HOSPITAL_UID:
self.matching[
couple.residents[1].uid] = int(s[2])
elif int(s[1]) != NIL_HOSPITAL_UID:
self.matching[int(s[0])] = int(s[1])
def solve_sat(self, solver,
problem_name='problem',
verbose=False, verify_file=None, run_solver=True,
output_filename=None,
enumerate_all=False, find_RPopt=False):
if verbose:
for single in self.singles:
print 'Single %d prefs %s' % (single.uid, str(
single.preference_function.internal_list))
for couple in self.couples:
print 'Couple %d prefs %s' % (couple.uid, str(
couple.preference_function.internal_list))
for resident in couple.residents:
print ' Resident %d' % (resident.uid)
for hospital in self.hospitals:
print 'Hospital %d capacity %d prefs %s' % (
hospital.uid,
hospital.capacity if hospital.capacity is not None else -1,
str(hospital.preference_function.internal_list))
variable_registry = {}
import random
random_suffix = random.randint(0, 100000)
constraints_buffer_filename = 'constraints_buffer-%d' % (random_suffix)
while os.path.isfile(constraints_buffer_filename):
random_suffix = random.randint(0, 100000)
constraints_buffer_filename = 'constraints_buffer-%d' % (
random_suffix)
if output_filename and not run_solver:
solver_input_filename = output_filename
else:
solver_input_filename = '%s-%d.sat' % (problem_name, random_suffix)
solver_output_filename = 'output-%d' % (random_suffix)
constraints = ConstraintsBuffer(filename=constraints_buffer_filename)
num_constraints = 0
# this will keep track of the DIMACS number of each matching variable
res_match = {}
var_uid_allocator = UIDAllocator(first_uid=1)
# create numbers for all matching variables
for resident in self.singles:
assert resident not in res_match
res_match[resident] = {}
for hospital_uid in resident.get_ordering():
hospital = hospital_dict[hospital_uid]
res_match[resident][hospital] = \
var_uid_allocator.allocate_uid()
variable_registry[res_match[resident][hospital]] = \
'xr_%d,%d' % (resident.uid, hospital.uid)
res_match[
resident][NIL_HOSPITAL] = var_uid_allocator.allocate_uid()
variable_registry[res_match[resident][NIL_HOSPITAL]] = \
'xr_%d,%d' % (resident.uid, NIL_HOSPITAL_UID)
constraints.append(DIMACSClause([
res_match[resident][hospital_dict[h_uid]]
for h_uid in resident.get_ordering()]
+ [res_match[resident][NIL_HOSPITAL]]))