-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSP_model_CPLEX.c
1133 lines (1000 loc) · 31.2 KB
/
TSP_model_CPLEX.c
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
#include <cplex.h>
#include <float.h>
#include <time.h>
#include "utilities.h"
#include "tsp.h"
#include "constructing_heuristics.h"
#include "meta-heuristics.h"
#define VERBOSE 9
#define LOCAL_BRANCHING_MIN_IMPROVEMENT 0.015 //1.5%
#define LOCAL_BRANCHING_MAX_SMALL_IMPROVEMENT 3
void print_error(const char* err)
{
printf("\n\n ERROR: %s \n\n", err);
fflush(NULL);
exit(1);
}
void updateUB(Instance* inst, int succ[], double* UB)
{
double cost = 0.0;
int* sol = (int*)calloc(inst->nnodes, sizeof(int));
succ2sol(inst, inst->cplexSucc, sol);
for (int i = 0; i < inst->nnodes-1; i++)
{
cost += inst->dist[sol[i]*inst->nnodes + sol[i+1]];
}
cost += inst->dist[sol[inst->nnodes-1] * inst->nnodes + sol[0]];
if (cost <= *UB)
{
*UB = cost;
}
}
void computeCost(Instance* inst, int succ[], double* UB)
{
double cost = 0.0;
for (int i = 0; i < inst->nnodes; i++)
{
cost += inst->dist[i* inst->nnodes + succ[i]];
}
*UB = cost;
}
float randomFloat()
{
float ran = (float)rand() / (float)RAND_MAX;
return ran;
}
int xpos(int i, int j, Instance* inst)
{
if (i == j) print_error(" i == j in xpos");
if (i > j) return xpos(j, i, inst);
int pos = i * inst->nnodes + j - ((i + 1) * (i + 2)) / 2;
return pos;
}
/***************************************************************************************************************************/
void build_model(Instance* inst, CPXENVptr env, CPXLPptr lp)
/**************************************************************************************************************************/
{
double zero = 0.0;
char binary = 'B';
char** cname = (char**)calloc(1, sizeof(char*)); // (char **) required by cplex...
cname[0] = (char*)calloc(100, sizeof(char));
// add binary var.s x(i,j) for i < j
for (int i = 0; i < inst->nnodes; i++)
{
for (int j = i + 1; j < inst->nnodes; j++)
{
sprintf(cname[0], "x(%d,%d)", i + 1, j + 1); // ... x(1,2), x(1,3) ....
double obj = inst->dist[i*inst->nnodes +j]; // cost == distance
double lb = 0.0;
double ub = 1.0;
if (CPXnewcols(env, lp, 1, &obj, &lb, &ub, &binary, cname)) print_error(" wrong CPXnewcols on x var.s");
if (CPXgetnumcols(env, lp) - 1 != xpos(i, j, inst)) print_error(" wrong position for x var.s");
}
}
// add the degree constraints
int* index = (int*)calloc(inst->nnodes, sizeof(int));
double* value = (double*)calloc(inst->nnodes, sizeof(double));
for (int h = 0; h < inst->nnodes; h++) // add the degree constraint on node h
{
double rhs = 2.0;
char sense = 'E'; // 'E' for equality constraint
sprintf(cname[0], "degree(%d)", h + 1);
int nnz = 0;
for (int i = 0; i < inst->nnodes; i++)
{
if (i == h) continue;
index[nnz] = xpos(i, h, inst);
value[nnz] = 1.0;
nnz++;
}
int izero = 0;
if (CPXaddrows(env, lp, 0, 1, nnz, &rhs, &sense, &izero, index, value, NULL, &cname[0])) print_error("CPXaddrows(): error 1");
}
free(value);
free(index);
free(cname[0]);
free(cname);
if (VERBOSE >= 100)
{
int status = CPXwriteprob(env, lp, "model.lp", NULL);
if (status)
{
printf("Status error: %d\n", status);
exit(1);
}
}
}
//#define DEBUG // comment out to avoid debugging
//#define EPS 1e-5
// Bender's loop method:
// receives integer solution made of one or mode cycles
//
/*********************************************************************************************************************************/
void build_sol(const double* xstar, Instance* inst, int* succ, int* comp, int* ncomp) // build succ() and comp() wrt xstar()...
/*********************************************************************************************************************************/
{
#ifdef DEBUG // I check if degree of all nodes is two and if xstar does not contain fract. components
int* degree = (int*)calloc(inst->nnodes, sizeof(int));
for (int i = 0; i < inst->nnodes; i++)
{
for (int j = i + 1; j < inst->nnodes; j++)
{
int k = xpos(i, j, inst);
if (fabs(xstar[k]) > EPS && fabs(xstar[k] - 1.0) > EPS) print_error(" wrong xstar in build_sol()");
if (xstar[k] > 0.5)
{
++degree[i];
++degree[j];
}
}
}
for (int i = 0; i < inst->nnodes; i++)
{
if (degree[i] != 2) print_error("wrong degree in build_sol()");
}
free(degree);
#endif
* ncomp = 0;
for (int i = 0; i < inst->nnodes; i++)
{
succ[i] = -1;
comp[i] = -1;
}
for (int start = 0; start < inst->nnodes; start++)
{
if (comp[start] >= 0) continue; // node "start" was already visited, just skip it
// a new component is found
(*ncomp)++;
int i = start;
int done = 0;
while (!done) // go and visit the current component
{
comp[i] = *ncomp;
done = 1;
for (int j = 0; j < inst->nnodes; j++)
{
if (i != j && xstar[xpos(i, j, inst)] > 0.5 && comp[j] == -1) // the edge [i,j] is selected in xstar and j was not visited before
{
succ[i] = j;
i = j;
done = 0;
break;
}
}
}
succ[i] = start; // last arc to close the cycle
// go to the next component...
}
}
void patching(Instance* inst, int succ[], int comp[], int ncomp)
{
while (ncomp > 1)
{
double deltaCost = DBL_MAX;
double costNew = 0.0;
double costOld = 0.0;
int tmpA = 0, tmpB = 0;
int a = 0, sa = 0, b = 0, sb = 0;
for (int i = 1; i <= ncomp; i++)
{
for (int j = 0; j < inst->nnodes; j++)
{
if (comp[j] == i)
{
for (int k = j + 1; k < inst->nnodes; k++)
{
if (comp[j] < comp[k])
{
costOld = inst->dist[j * inst->nnodes + succ[j]] + inst->dist[k * inst->nnodes + succ[k]];
costNew = inst->dist[j * inst->nnodes + succ[k]] + inst->dist[k * inst->nnodes + succ[j]];
if (costNew - costOld < deltaCost)
{
deltaCost = costNew - costOld;
a = j;
sa = succ[j];
b = k;
sb = succ[k];
}
}
}
}
}
}
// update components
int compA = comp[a];
int tmp = sb;
while (tmp != b)
{
comp[tmp] = compA;
tmp = succ[tmp];
}
comp[tmp] = compA;
// update successors
succ[a] = sb;
succ[b] = sa;
// check if there are more than two components
int prev = comp[0];
int flag = 0;
for (int i = 1; i < inst->nnodes; i++)
{
tmp = comp[i];
if (tmp != prev)
{
flag = 1;
break;
}
}
if (flag == 0)
{
break;
}
}
}
// alternative to Benders'
/********************************************************************************************************/
static int CPXPUBLIC my_callback(CPXCALLBACKCONTEXTptr context, CPXLONG contextid, void* userhandle)
/********************************************************************************************************/
{
// +++++++++
// Threadsafe: no variable inside inst must be modified
// rand() is not thread safe!!!!! Create a thread safe RNG yourself
// +++++++++
//printf("\n+++++++++++++++++++++++++++++++\n");
clock_t start = clock();
Instance* inst = (Instance*)userhandle;
double* xstar = (double*)malloc(inst->ncols * sizeof(double)); // current candidate solution will go here: IT'S A INTEGER SOLUTION (collection of cycles)
double objval = CPX_INFBOUND;
if (CPXcallbackgetcandidatepoint(context, xstar, 0, inst->ncols - 1, &objval)) print_error("CPXcallbackgetcandidatepoint error");
// get some random information at the node (as an example for the students)
int mythread = -1;
CPXcallbackgetinfoint(context, CPXCALLBACKINFO_THREADID, &mythread); //thread starts from 0
// if you want to know at which node of the branching tree this function has been called:
int mynode = -1;
CPXcallbackgetinfoint(context, CPXCALLBACKINFO_NODECOUNT, &mynode);
// value of the incumbent (cost of best solution) when this function (my_callback) is called:
double incumbent = CPX_INFBOUND;
CPXcallbackgetinfodbl(context, CPXCALLBACKINFO_BEST_SOL, &incumbent);
//if ( VERBOSE >= 100 ) printf(" ... callback at node %5d thread %2d incumbent %10.2lf, candidate value %10.2lf\n", .....);
int nnz = 0;
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int* index = (int*)calloc(inst->ncols, sizeof(int)); // put in instance the number of columns
double* coeff = (double*)calloc(inst->ncols, sizeof(double));
int ncomp = 0;
char sense = 'L';
char** cname = (char**)calloc(1, sizeof(char*)); // (char **) required by cplex...
cname[0] = (char*)calloc(inst->nnodes, sizeof(char));
int izero = 0;
build_sol(xstar, inst, succ, comp, &ncomp);
//if xstar is infeasible, find a violated cut and store it in the usual Cplex's data structure (rhs, sense, nnz, index and value)
//as we did in build_sol
if (ncomp <= 1)
{
free(xstar);
free(succ);
free(comp);
free(index);
free(coeff);
free(cname[0]);
free(cname);
return 0;
}
for (int k = 1; k <= ncomp; k++)
{
//check if overall time is over
clock_t end = clock();
double diff = (double)(end - inst->tstart) / CLOCKS_PER_SEC;
//If time is over, patch the solution
if (diff > inst->timeLimit)
{
if (inst->patchFlag == 0)
{
inst->patchFlag = 1;
patching(inst, succ, comp, ncomp);
int flag = 1;
double cost = DBL_MAX;
updateUB(inst, succ, &cost);
while (flag == 1)
{
flag = two_opt(inst, succ, &cost, 0, 0);
}
for (int index = 0; index < inst->nnodes; index++)
{
inst->cplexSucc[index] = succ[index];
}
if (inst->verbose >= 10)
{
printf("New best cost: %f\n", cost);
}
inst->cplexCost = cost;
}
break;
}
int nnz = 0;
double rhs = -1;
for (int l = 0; l < inst->ncols; l++)
{
index[l] = 0;
coeff[l] = 0.0;
}
for (int i = 0; i < inst->nnodes; i++)
{
if (comp[i] == k)
{
rhs += 1;
for (int j = i + 1; j < inst->nnodes - 1; j++)
{
if (comp[j] == k)
{
index[nnz] = xpos(i, j, inst);
coeff[nnz] = 1.0;
nnz += 1;
}
}
}
}
if (nnz >= 2) // means that the solution is infeasible and a violated cut has been found -> insert SEC's
{
/*if (inst->verbose >= 10)
{
printf("the solution is infeasible and a violated cut has been found\n");
}*/
int izero = 0;
if (CPXcallbackrejectcandidate(context, 1, nnz, &rhs, &sense, &izero, index, coeff)) print_error("CPXcallbackrejectcandidate() error"); // reject the solution and adds one cut
}
}
free(xstar);
free(succ);
free(comp);
free(index);
free(coeff);
free(cname[0]);
free(cname);
return 0;
}
int TSPCallback(Instance* inst)
{
inst->tstart = clock();
// open CPLEX model
int error;
CPXENVptr env = CPXopenCPLEX(&error);
if (error) print_error("CPXopenCPLEX() error");
CPXLPptr lp = CPXcreateprob(env, &error, "TSP model version 1");
if (error) print_error("CPXcreateprob() error");
build_model(inst, env, lp);
double LB = -CPX_INFBOUND;
double UB = 0.0;
inst->greedySucc = (int*)calloc(inst->nnodes, sizeof(int));
greed_search(inst, 0, 0, NULL, 0, &UB);
// Cplex's parameter setting
CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF);
if (VERBOSE >= 60) CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); // Cplex output on screen
CPXsetintparam(env, CPX_PARAM_RANDOMSEED, 123456);
CPXsetdblparam(env, CPX_PARAM_TILIM, inst->timeLimit); //MODIFY THIS FOR THE TIME LIMIT
CPXsetdblparam(env, CPX_PARAM_CUTUP, UB);
int ncols = CPXgetnumcols(env, lp);
inst->ncols = ncols;
// install callbacks (BEFORE CALLING CPXmipopt):
// install a "lazyconstraint" callback to cut infeasible integer sol.s (found e.g. by heuristics)
CPXLONG contextid = CPX_CALLBACKCONTEXT_CANDIDATE;
if (CPXcallbacksetfunc(env, lp, contextid, my_callback, inst)) print_error("CPXcallbacksetfunc() error");
// I need to call the callback only when CPLEX finds a candidate integer solution
error = CPXmipopt(env, lp);
if (error)
{
//printf("CPX error code %d\n", error);
printf("Error is %d!\n", error);
print_error("CPXmipopt() error");
}
// Check if time is over
clock_t end = clock();
double diff = (double)(end - inst->tstart) / CLOCKS_PER_SEC;
if (diff > inst->timeLimit)
{
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
return 0;
}
double* xstar = (double*)calloc(ncols, sizeof(double));
error = CPXgetx(env, lp, xstar, 0, ncols - 1);
if (error)
{
printf("Error is %d!!\n", error);
print_error("CPXgetx() error");
}
CPXgetbestobjval(env, lp, &UB);
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int ncomp = 0;
build_sol(xstar, inst, succ, comp, &ncomp);
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
//update UB and inst->cplexSucc
for (int i = 0; i < inst->nnodes; i++)
{
inst->cplexSucc[i] = succ[i];
}
updateUB(inst, succ, &UB);
inst->cplexCost = UB;
free(xstar);
free(succ);
free(comp);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
static int CPXPUBLIC ad_hoc(CPXCALLBACKCONTEXTptr context, CPXLONG contextid, void* userhandle)
{
clock_t start = clock();
Instance* inst = (Instance*)userhandle;
double* xstar = (double*)calloc(inst->ncols, sizeof(double)); // current candidate solution will go here: IT'S A INTEGER SOLUTION (collection of cycles)
double objval = CPX_INFBOUND;
if (CPXcallbackgetcandidatepoint(context, xstar, 0, inst->ncols - 1, &objval)) print_error("CPXcallbackgetcandidatepoint error");
int nnz = 0;
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int* index = (int*)calloc(inst->ncols, sizeof(int)); // put in instance the number of columns
double* coeff = (double*)calloc(inst->ncols, sizeof(double));
int ncomp = 0;
char sense = 'L';
int izero = 0;
build_sol(xstar, inst, succ, comp, &ncomp);
//if xstar is infeasible, find a violated cut and store it in the usual Cplex's data structure (rhs, sense, nnz, index and value)
//as we did in build_sol
if (ncomp <= 1)
{
return 0;
}
double* xheu = (double*)calloc(inst->ncols, sizeof(double));
int* ind = (int*)calloc(inst->ncols, sizeof(int));
for (int i = 0; i < inst->ncols; i++)
{
ind[i] = i;
xheu[i] = 0.0;
}
patching(inst, succ, comp, ncomp);
int flag = 1;
while (flag == 1)
{
flag = two_opt(inst, succ, &objval, 0, 0);
}
//Check if time is over
clock_t end = clock();
double diff = (double)((end - inst->tstart)) / CLOCKS_PER_SEC;
if (diff > inst->timeLimit)
{
if (inst->patchFlag == 0)
{
inst->patchFlag = 1;
patching(inst, succ, comp, ncomp);
flag = 1;
double cost = DBL_MAX;
updateUB(inst, succ, &cost);
while (flag == 1)
{
flag = two_opt(inst, succ, &cost, 0, 0);
}
for (int cntr = 0; cntr < inst->nnodes; cntr++)
{
inst->best_succ[cntr] = succ[cntr];
}
inst->cplexCost = cost;
if (inst->verbose >= 10)
{
printf("New best cost: %f\n", cost);
}
}
free(ind);
free(xstar);
free(succ);
free(comp);
free(index);
free(coeff);
free(xheu);
return 0;
}
for (int i = 0; i < inst->nnodes; i++)
{
xheu[xpos(i, succ[i], inst)] = 1.0;
}
double UB = DBL_MAX;
updateUB(inst, succ, &UB);
if (CPXcallbackpostheursoln(context, inst->ncols, ind, xheu, UB, CPXCALLBACKSOLUTION_NOCHECK)) print_error("CPXcallbackpostheursoln() error");
free(ind);
free(xstar);
free(succ);
free(comp);
free(index);
free(coeff);
free(xheu);
return 0;
}
int TSPadHoc(Instance* inst)
{
inst->tstart = clock();
inst->starting_node = 0;
// open CPLEX model
int error;
CPXENVptr env = CPXopenCPLEX(&error);
if (error) print_error("CPXopenCPLEX() error");
CPXLPptr lp = CPXcreateprob(env, &error, "TSP model version 1");
if (error) print_error("CPXcreateprob() error");
build_model(inst, env, lp);
double LB = -CPX_INFBOUND;
double UB = 0.0;
// Cplex's parameter setting
CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF);
if (VERBOSE >= 60) CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); // Cplex output on screen
CPXsetintparam(env, CPX_PARAM_RANDOMSEED, 123456);
inst->greedySucc = (int*)calloc(inst->nnodes, sizeof(int));
greed_search(inst, 0, 0, NULL, 0, &UB);
CPXsetdblparam(env, CPX_PARAM_TILIM, inst->timeLimit); //MODIFY THIS FOR THE TIME LIMIT
CPXsetdblparam(env, CPX_PARAM_CUTUP, UB);
int ncols = CPXgetnumcols(env, lp);
inst->ncols = ncols;
// install callbacks (BEFORE CALLING CPXmipopt):
// install a "lazyconstraint" callback to cut infeasible integer sol.s (found e.g. by heuristics)
CPXLONG contextid = CPX_CALLBACKCONTEXT_CANDIDATE;
if (CPXcallbacksetfunc(env, lp, contextid, ad_hoc, inst)) print_error("CPXcallbacksetfunc() error");
error = CPXmipopt(env, lp);
if (error)
{
//printf("CPX error code %d\n", error);
printf("Error is %d!\n", error);
print_error("CPXmipopt() error");
}
//Check if time is over
clock_t end = clock();
double diff = (double)(end - inst->tstart) / CLOCKS_PER_SEC;
if (diff > inst->timeLimit)
{
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
return 0;
}
double* xstar = (double*)calloc(ncols, sizeof(double));
error = CPXgetx(env, lp, xstar, 0, ncols - 1);
if (error)
{
printf("Error is %d!!\n", error);
print_error("CPXgetx() error");
}
CPXgetbestobjval(env, lp, &UB);
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int ncomp = 0;
build_sol(xstar, inst, succ, comp, &ncomp);
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
//update UB and inst->cplexSucc
for (int i = 0; i < inst->nnodes; i++)
{
inst->cplexSucc[i] = succ[i];
}
inst->cplexCost = UB;
free(xstar);
free(succ);
free(comp);
}
int TSPHardFixing(Instance* inst)
{
inst->tstart = clock();
// open CPLEX model
int error;
CPXENVptr env = CPXopenCPLEX(&error);
if (error) print_error("CPXopenCPLEX() error");
CPXLPptr lp = CPXcreateprob(env, &error, "TSP model version 1");
if (error) print_error("CPXcreateprob() error");
build_model(inst, env, lp);
// Cplex's parameter setting
CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF);
if (VERBOSE >= 60) CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); // Cplex output on screen
CPXsetintparam(env, CPX_PARAM_RANDOMSEED, 123456);
CPXsetdblparam(env, CPX_PARAM_TILIM, inst->timeLimit);
//use greedy to obtain a starting solution, which will be saved in inst->best_sol, and from there apply hard fixing
// STOPPING CONDITION: On UB and time
double UB = 0.0;
double prev_UB = CPX_INFBOUND;
double LB = -CPX_INFBOUND;
int ncols = CPXgetnumcols(env, lp);
inst->ncols = ncols;
inst->greedySucc = (int*)calloc(inst->nnodes, sizeof(int)); // will be freed by free_memory() in main;
greed_search(inst, 0, 0, NULL, 0, &UB);
CPXsetdblparam(env, CPX_PARAM_CUTUP, UB);
CPXsetintparam(env, lp, CPX_PARAM_NODELIM, 1000);
CPXLONG contextid = CPX_CALLBACKCONTEXT_CANDIDATE;
if (CPXcallbacksetfunc(env, lp, contextid, my_callback, inst)) print_error("CPXcallbacksetfunc() error");
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* sol = (int*)calloc(inst->nnodes, sizeof(int));
for (int i = 0; i < inst->nnodes; i++)
{
succ[i] = inst->greedySucc[i];
}
succ2sol(inst, succ, sol);
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int ncomp = 0;
char lu = 'L';
double bd_one = 1.0;
double bd_zero = 0.0;
while (1)
{
// fix lower bound
//use xpos to get the column position
for (int i = 0; i < inst->nnodes; i++)
{
float probability = (float)rand()/RAND_MAX;
if (probability < 0.2)
{
if (i == inst->nnodes - 1)
{
int position = xpos(sol[i], sol[0], inst);
CPXchgbds(env, lp, 1, &position, &lu, &bd_one);
}
else
{
int position = xpos(sol[i], sol[i+1], inst);
CPXchgbds(env, lp, 1, &position, &lu, &bd_one);
}
}
}
// solve
error = CPXmipopt(env, lp);
if (error)
{
printf("CPX error code %d\n", error);
print_error("CPXmipopt() error");
}
// Check if time is over
clock_t end = clock();
double diff = (double)(end - inst->tstart) / CLOCKS_PER_SEC;
CPXsetdblparam(env, CPX_PARAM_TILIM, inst->timeLimit - diff);
if (diff > inst->timeLimit)
{
free(succ);
free(comp);
free(sol);
break;
}
// if time is not over, update UB
double* xstar = (double*)calloc(ncols, sizeof(double));
error = CPXgetx(env, lp, xstar, 0, ncols - 1);
if (error)
{
printf("Error is %d!!\n", error);
print_error("CPXgetx() error");
}
build_sol(xstar, inst, succ, comp, &ncomp);
CPXgetbestobjval(env, lp, &UB);
double handCompCost = 0.0;
computeCost(inst, succ, &handCompCost);
if (UB < prev_UB)
{
prev_UB = UB;
for (int i = 0; i < inst->nnodes; i++)
{
inst->cplexSucc[0] = succ[0];
}
succ2sol(inst, succ, sol);
inst->cplexCost = UB;
if (inst->verbose >= 10)
{
printf("New best cost: %f\n", UB);
}
}
free(xstar);
for (int i = 0; i < inst->nnodes; i++)
{
for (int j = i + 1; j < inst->nnodes; j++)
{
int position = xpos(i, j, inst);
CPXchgbds(env, lp, 1, &position, &lu, &bd_zero);
}
}
}
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
}
void TSPLocalBranching(Instance* inst)
{
inst->tstart = clock();
if (VERBOSE >= 10) printf("\nStart Local branching matheuristic\n");
// open CPLEX model
int error;
CPXENVptr env = CPXopenCPLEX(&error);
if (error) print_error("CPXopenCPLEX() error");
CPXLPptr lp = CPXcreateprob(env, &error, "TSP model version 1");
if (error) print_error("CPXcreateprob() error");
//CPXsetdblparam(env, CPXPARAM_TimeLimit, inst->timeLimit);
build_model(inst, env, lp);
// Cplex's parameter setting
CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF);
if (VERBOSE >= 60) CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); // Cplex output on screen
CPXsetintparam(env, CPX_PARAM_RANDOMSEED, 123456);
//CPXsetdblparam(env, CPX_PARAM_TILIM, inst->timeLimit);
//first we need to find a feasible solution
long ncols = CPXgetnumcols(env, lp);
inst->ncols = ncols;
int* indexes = (int*)calloc(inst->ncols, sizeof(int));
double* values = (double*)calloc(inst->ncols, sizeof(double));
double* xh = (double*)calloc(inst->ncols, sizeof(double));
double UB = 0.0;
inst->greedySucc = (int*)calloc(inst->nnodes, sizeof(int));
greed_search(inst, 0, 0, NULL, 0, &UB);
CPXsetdblparam(env, CPX_PARAM_CUTUP, UB);
for (int i = 0; i < inst->nnodes; i++)
{
xh[xpos(i,inst->greedySucc[i], inst)] = 1.0;
}
//Setting up indices array. Setting up it here avoids on setting it up everytime the 2-opt callback need it. One time initialization and that's all.
int* ind = (int*)calloc(inst->ncols, sizeof(int));
int k = 0;
for (int i = 0; i < inst->ncols; i++)
{
ind[i] = i;
}
int beg = 0;
int level = CPX_MIPSTART_NOCHECK;
if (CPXaddmipstarts(env, lp, 1, inst->ncols, &beg, ind, xh, &level, NULL)) print_error("CPXaddmipstarts() error");
CPXLONG contextid = CPX_CALLBACKCONTEXT_CANDIDATE;
if (CPXcallbacksetfunc(env, lp, contextid, my_callback, inst)) print_error("CPXcallbacksetfunc() error");
double K[] = { 10, 20, 30, 40 };
int k_index = 0;
double actual_val = 0.0;
double actual_best = UB;
int small_imp = 0;
char sense = 'G'; // >=
int matbeg = 0;
int num_iter = 0; //counter of iteration
double bd_one = 1.0;
int* succ = (int*)calloc(inst->nnodes, sizeof(int));
int* sol = (int*)calloc(inst->nnodes, sizeof(int));
int* comp = (int*)calloc(inst->nnodes, sizeof(int));
int ncomp = 0;
for (int i = 0; i < inst->nnodes; i++)
{
succ[i] = inst->greedySucc[i];
}
succ2sol(inst, inst->greedySucc, sol);
char** cname = (char**)calloc(1, sizeof(char));
cname[0] = (char*)calloc(100, sizeof(char));
sprintf(cname[0], "Local branching constraint");
while (1)
{
if (k_index >= (sizeof(K) / sizeof(*K))) { break; }
clock_t end = clock();
double diff = (double)(end - inst->tstart) / CLOCKS_PER_SEC;
if (diff > inst->timeLimit) { break; } //stop
double time_remain = inst->timeLimit - diff;
CPXsetdblparam(env, CPXPARAM_TimeLimit, time_remain);
int k = 0;
for (int i = 0; i < inst->nnodes; i++)
{
if (xh[xpos(i,succ[i], inst)] > 0.5)
{
indexes[k] = xpos(i,succ[i], inst);
values[k] = 1.0;
k++;
}
}
double rhs = inst->nnodes - K[k_index];
if (CPXaddrows(env, lp, 0, 1, k, &rhs, &sense, &matbeg, indexes, values, NULL, &cname[0])) print_error("CPXaddrows() error");
//solve the model
error = CPXmipopt(env, lp);
if (error)
{
printf("CPX error code %d\n", error);
print_error("CPXmipopt() error");
}
CPXgetx(env, lp, xh, 0, ncols - 1);
build_sol(xh, inst, succ, comp, &ncomp);
CPXgetobjval(env, lp, &actual_val);
double improved_cost = 1 - actual_val / actual_best;
if (actual_val < actual_best)
{
if (improved_cost < LOCAL_BRANCHING_MIN_IMPROVEMENT)
{
small_imp++;
}
else //se ho capito cosa volevi fare, penso che l'else vada qui, ma se mi sono sbagliato mettilo pure dov'era prima
{
small_imp = 0;
}
if (small_imp % LOCAL_BRANCHING_MAX_SMALL_IMPROVEMENT == 0 && k_index < (sizeof(K) / sizeof(*K)) - 1)
{
k_index++;
}
//Update solution
actual_best = actual_val;
for (int i = 0; i < inst->nnodes; i++)
{
inst->cplexSucc[i] = succ[i];
}
succ2sol(inst, succ, sol);
inst->cplexCost = actual_val;
if (inst->verbose >= 10)
{
printf("New best cost: %f\n", inst->cplexCost);
}
}
// Remove the added soft-fixing constraints
int numrows = CPXgetnumrows(env, lp);
error = CPXdelrows(env, lp, numrows - 1, numrows - 1);
if (error)
{
printf("CPXdelrows error code %d\n", error);
print_error("CPXdelrows() error");
}
num_iter++;
for (int i = 0; i < ncols; i++) // "clean" indexes and values
{
indexes[i] = 0;
values[i] = 0.0;
}
}
free(cname[0]);
free(cname);
free(comp);
free(succ);
free(sol);
free(xh);
free(values);
free(indexes);
free(ind);
CPXfreeprob(env, &lp);
CPXcloseCPLEX(&env);
}
/**************************************************************************************************************************/
int TSPopt(Instance* inst)
/**************************************************************************************************************************/
{
inst->tstart = clock();
// open CPLEX model
int error;
CPXENVptr env = CPXopenCPLEX(&error);
if (error) print_error("CPXopenCPLEX() error");
CPXLPptr lp = CPXcreateprob(env, &error, "TSP model version 1");
if (error) print_error("CPXcreateprob() error");
build_model(inst, env, lp);
// Cplex's parameter setting
CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_OFF);
if (VERBOSE >= 60) CPXsetintparam(env, CPX_PARAM_SCRIND, CPX_ON); // Cplex output on screen
CPXsetintparam(env, CPX_PARAM_RANDOMSEED, 123456);
CPXsetdblparam(env, CPX_PARAM_TILIM, 3600.0);
//CPXsetintparam(env, CPX_PARAM_THREADS, 1); // single thread -> just for debugging
double UB = 0.0;
inst->greedySucc = (int*)calloc(inst->nnodes, sizeof(int)); // will be freed by free_memory() in main;
greed_search(inst, 0, 0, NULL, 0, &UB);
CPXsetdblparam(env, CPX_PARAM_CUTUP, UB);
CPXsetintparam(env, lp, CPX_PARAM_NODELIM, 100);
error = CPXmipopt(env, lp);
if (error)
{
printf("CPX error code %d\n", error);
print_error("CPXmipopt() error");
}
// use the optimal solution found by CPLEX
int ncols = CPXgetnumcols(env, lp);
inst->ncols = ncols;
double* xstar = (double*)calloc(ncols, sizeof(double));
if (CPXgetx(env, lp, xstar, 0, ncols - 1)) print_error("CPXgetx() error");