-
Notifications
You must be signed in to change notification settings - Fork 31
/
GCoptimization.cpp
1877 lines (1601 loc) · 58.2 KB
/
GCoptimization.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
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
#ifdef MATLAB_MEX_FILE
#include <mex.h>
#endif
#include "GCoptimization.h"
#include "LinkedBlockList.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
// will leave this one just for the laughs :)
//#define olga_assert(expr) assert(!(expr))
// Choose reasonably high-precision timer (sub-millisec resolution if possible).
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#define NOMINMAX
#include <windows.h>
extern "C" gcoclock_t GCO_CLOCKS_PER_SEC = 0;
extern "C" inline gcoclock_t gcoclock() // TODO: not thread safe; separate begin/end so that end doesn't have to check for query frequency
{
gcoclock_t result = 0;
if (GCO_CLOCKS_PER_SEC == 0)
QueryPerformanceFrequency((LARGE_INTEGER*)&GCO_CLOCKS_PER_SEC);
QueryPerformanceCounter((LARGE_INTEGER*)&result);
return result;
}
#else
extern "C" {
gcoclock_t GCO_CLOCKS_PER_SEC = CLOCKS_PER_SEC;
}
extern "C" gcoclock_t gcoclock() { return clock(); }
#endif
#ifdef MATLAB_MEX_FILE
extern "C" bool utIsInterruptPending();
static void flushnow()
{
// Don't flush to frequently, for overall speed.
static gcoclock_t prevclock = 0;
gcoclock_t now = gcoclock();
if (now - prevclock > GCO_CLOCKS_PER_SEC/5) {
prevclock = now;
mexEvalString("drawnow;");
}
}
#define INDEX0 1 // print 1-based label and site indices for MATLAB
#else
inline static bool utIsInterruptPending() { return false; }
static void flushnow() { }
#define INDEX0 0 // print 0-based label and site indices
#endif
// Singly-linked list helper functions; works on any struct with a 'next' member.
template <typename T>
void slist_clear(T*& head)
{
while (head) {
T* temp = head;
head = head->next;
delete temp;
}
}
template <typename T>
void slist_prepend(T*& head, T* val)
{
val->next = head;
head = val;
}
void GCException::Report()
{
printf("\n%s\n",message);
exit(0);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// First we have functions for the base class
/////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor for base class
GCoptimization::GCoptimization(SiteID nSites, LabelID nLabels)
: m_num_labels(nLabels)
, m_num_sites(nSites)
, m_datacostIndividual(0)
, m_smoothcostIndividual(0)
, m_labelcostsAll(0)
, m_labelcostsByLabel(0)
, m_labelcostCount(0)
, m_smoothcostFn(0)
, m_datacostFn(0)
, m_numNeighborsTotal(0)
, m_queryActiveSitesExpansion(&GCoptimization::queryActiveSitesExpansion<DataCostFnFromArray>)
, m_setupDataCostsSwap(0)
, m_setupDataCostsExpansion(0)
, m_setupSmoothCostsSwap(0)
, m_setupSmoothCostsExpansion(0)
, m_applyNewLabeling(0)
, m_updateLabelingDataCosts(0)
, m_giveSmoothEnergyInternal(0)
, m_solveSpecialCases(&GCoptimization::solveSpecialCases<DataCostFnFromArray>)
, m_datacostFnDelete(0)
, m_smoothcostFnDelete(0)
, m_random_label_order(false)
, m_verbosity(0)
, m_labelingInfoDirty(true)
, m_lookupSiteVar(new SiteID[nSites])
, m_labeling(new LabelID[nSites])
, m_labelTable(new LabelID[nLabels])
, m_labelingDataCosts(new EnergyTermType[nSites])
, m_labelCounts(new SiteID[nLabels])
, m_activeLabelCounts(new SiteID[m_num_labels])
, m_stepsThisCycle(0)
, m_stepsThisCycleTotal(0)
{
if ( nLabels <= 1 ) handleError("Number of labels must be >= 2");
if ( nSites <= 0 ) handleError("Number of sites must be >= 1");
if ( !m_lookupSiteVar || !m_labelTable || !m_labeling ){
if (m_lookupSiteVar) delete [] m_lookupSiteVar;
if (m_labelTable) delete [] m_labelTable;
if (m_labeling) delete [] m_labeling;
if (m_labelingDataCosts) delete [] m_labelingDataCosts;
if (m_labelCounts) delete [] m_labelCounts;
handleError("Not enough memory.");
}
memset(m_labeling, 0, m_num_sites*sizeof(LabelID));
memset(m_lookupSiteVar,-1,m_num_sites*sizeof(SiteID));
setLabelOrder(false);
specializeSmoothCostFunctor(SmoothCostFnPotts());
}
//-------------------------------------------------------------------
GCoptimization::~GCoptimization()
{
delete [] m_labelTable;
delete [] m_lookupSiteVar;
delete [] m_labeling;
delete [] m_labelingDataCosts;
delete [] m_labelCounts;
delete [] m_activeLabelCounts;
if (m_datacostFnDelete) m_datacostFnDelete(m_datacostFn);
if (m_smoothcostFnDelete) m_smoothcostFnDelete(m_smoothcostFn);
if (m_datacostIndividual) delete [] m_datacostIndividual;
if (m_smoothcostIndividual) delete [] m_smoothcostIndividual;
// Delete label cost bookkeeping structures
//
slist_clear(m_labelcostsAll);
if (m_labelcostsByLabel) {
for ( LabelID i = 0; i < m_num_labels; ++i )
slist_clear(m_labelcostsByLabel[i]);
delete [] m_labelcostsByLabel;
}
}
//-------------------------------------------------------------------
template <>
GCoptimization::SiteID GCoptimization::queryActiveSitesExpansion<GCoptimization::DataCostFnSparse>(LabelID alpha_label,SiteID *activeSites)
{
return ((DataCostFnSparse*)m_datacostFn)->queryActiveSitesExpansion(alpha_label,m_labeling,activeSites);
}
//-------------------------------------------------------------------
template <>
void GCoptimization::setupDataCostsExpansion<GCoptimization::DataCostFnSparse>(SiteID size,LabelID alpha_label,EnergyT *e,SiteID *activeSites)
{
DataCostFnSparse* dc = (DataCostFnSparse*)m_datacostFn;
DataCostFnSparse::iterator dciter = dc->begin(alpha_label);
for ( SiteID i = 0; i < size; ++i )
{
SiteID site = activeSites[i];
while ( dciter.site() != site )
++dciter;
addterm1_checked(e,i,dciter.cost(),m_labelingDataCosts[site]);
}
}
//-------------------------------------------------------------------
template <>
void GCoptimization::applyNewLabeling<GCoptimization::DataCostFnSparse>(EnergyT *e,SiteID *activeSites,SiteID size,LabelID alpha_label)
{
DataCostFnSparse* dc = (DataCostFnSparse*)m_datacostFn;
DataCostFnSparse::iterator dciter = dc->begin(alpha_label);
for ( SiteID i = 0; i < size; i++ )
{
if ( e->get_var(i) == 0 )
{
SiteID site = activeSites[i];
LabelID prev = m_labeling[site];
m_labeling[site] = alpha_label;
m_labelCounts[alpha_label]++;
m_labelCounts[prev]--;
while ( dciter.site() != site )
++dciter;
m_labelingDataCosts[site] = dciter.cost();
}
}
m_labelingInfoDirty = true;
updateLabelingInfo(false,true,false); // labels have changed, so update necessary labeling info
}
//-------------------------------------------------------------------
template <typename UserFunctor>
void GCoptimization::specializeDataCostFunctor(const UserFunctor f) {
if ( m_datacostFnDelete )
m_datacostFnDelete(m_datacostFn);
if ( m_datacostIndividual )
{
delete [] m_datacostIndividual;
m_datacostIndividual = 0;
}
m_datacostFn = new UserFunctor(f);
m_datacostFnDelete = &GCoptimization::deleteFunctor<UserFunctor>;
m_queryActiveSitesExpansion = &GCoptimization::queryActiveSitesExpansion<UserFunctor>;
m_setupDataCostsExpansion = &GCoptimization::setupDataCostsExpansion<UserFunctor>;
m_setupDataCostsSwap = &GCoptimization::setupDataCostsSwap<UserFunctor>;
m_applyNewLabeling = &GCoptimization::applyNewLabeling<UserFunctor>;
m_updateLabelingDataCosts = &GCoptimization::updateLabelingDataCosts<UserFunctor>;
m_solveSpecialCases = &GCoptimization::solveSpecialCases<UserFunctor>;
}
template <typename UserFunctor>
void GCoptimization::specializeSmoothCostFunctor(const UserFunctor f) {
if ( m_smoothcostFnDelete )
m_smoothcostFnDelete(m_smoothcostFn);
if ( m_smoothcostIndividual )
{
delete [] m_smoothcostIndividual;
m_smoothcostIndividual = 0;
}
m_smoothcostFn = new UserFunctor(f);
m_smoothcostFnDelete = &GCoptimization::deleteFunctor<UserFunctor>;
m_giveSmoothEnergyInternal = &GCoptimization::giveSmoothEnergyInternal<UserFunctor>;
m_setupSmoothCostsExpansion = &GCoptimization::setupSmoothCostsExpansion<UserFunctor>;
m_setupSmoothCostsSwap = &GCoptimization::setupSmoothCostsSwap<UserFunctor>;
}
//-------------------------------------------------------------------
template <typename SmoothCostT>
GCoptimization::EnergyType GCoptimization::giveSmoothEnergyInternal()
{
EnergyType eng = (EnergyType) 0;
SiteID i,numN,*nPointer,nSite,n;
EnergyTermType *weights;
SmoothCostT* sc = (SmoothCostT*) m_smoothcostFn;
for ( i = 0; i < m_num_sites; i++ )
{
giveNeighborInfo(i,&numN,&nPointer,&weights);
for ( n = 0; n < numN; n++ )
{
nSite = nPointer[n];
if ( nSite < i )
eng += weights[n]*(sc->compute(i,nSite,m_labeling[i],m_labeling[nSite]));
}
}
return eng;
}
//-------------------------------------------------------------------
OLGA_INLINE void GCoptimization::addterm1_checked(EnergyT* e, VarID i, EnergyTermType e0, EnergyTermType e1)
{
if ( e0 > GCO_MAX_ENERGYTERM || e1 > GCO_MAX_ENERGYTERM )
handleError("Data cost term was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
m_beforeExpansionEnergy += e1;
e->add_term1(i,e0,e1);
}
OLGA_INLINE void GCoptimization::addterm1_checked(EnergyT* e, VarID i, EnergyTermType e0, EnergyTermType e1, EnergyTermType w)
{
if ( e0 > GCO_MAX_ENERGYTERM || e1 > GCO_MAX_ENERGYTERM )
handleError("Smooth cost term was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
if ( w > GCO_MAX_ENERGYTERM )
handleError("Smoothness weight was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
m_beforeExpansionEnergy += e1*w;
e->add_term1(i,e0*w,e1*w);
}
OLGA_INLINE void GCoptimization::addterm2_checked(EnergyT* e, VarID i, VarID j, EnergyTermType e00, EnergyTermType e01, EnergyTermType e10, EnergyTermType e11, EnergyTermType w)
{
if ( e00 > GCO_MAX_ENERGYTERM || e11 > GCO_MAX_ENERGYTERM || e01 > GCO_MAX_ENERGYTERM || e10 > GCO_MAX_ENERGYTERM )
handleError("Smooth cost term was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
if ( w > GCO_MAX_ENERGYTERM )
handleError("Smoothness weight was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
// Inside energy/maxflow code the submodularity check is performed as an assertion,
// but is optimized out. We check it in release builds as well.
if ( e00+e11 > e01+e10 )
handleError("Non-submodular expansion term detected; smooth costs must be a metric for expansion");
m_beforeExpansionEnergy += e11*w;
e->add_term2(i,j,e00*w,e01*w,e10*w,e11*w);
}
//------------------------------------------------------------------
template <typename DataCostT>
GCoptimization::SiteID GCoptimization::queryActiveSitesExpansion(LabelID alpha_label,SiteID *activeSites)
{
SiteID size = 0;
for ( SiteID i = 0; i < m_num_sites; i++ )
if ( m_labeling[i] != alpha_label )
activeSites[size++] = i;
return size;
}
//-------------------------------------------------------------------
template <typename DataCostT>
void GCoptimization::setupDataCostsExpansion(SiteID size,LabelID alpha_label,EnergyT *e,SiteID *activeSites)
{
DataCostT* dc = (DataCostT*)m_datacostFn;
for ( SiteID i = 0; i < size; ++i )
addterm1_checked(e,i,dc->compute(activeSites[i],alpha_label),m_labelingDataCosts[activeSites[i]]);
}
//-------------------------------------------------------------------
template <typename SmoothCostT>
void GCoptimization::setupSmoothCostsExpansion(SiteID size,LabelID alpha_label,EnergyT *e,SiteID *activeSites)
{
SiteID i,nSite,site,n,nNum,*nPointer;
EnergyTermType *weights;
SmoothCostT* sc = (SmoothCostT*)m_smoothcostFn;
for ( i = size - 1; i >= 0; i-- )
{
site = activeSites[i];
giveNeighborInfo(site,&nNum,&nPointer,&weights);
for ( n = 0; n < nNum; n++ )
{
nSite = nPointer[n];
if ( m_lookupSiteVar[nSite] == -1 )
addterm1_checked(e,i,sc->compute(site,nSite,alpha_label,m_labeling[nSite]),
sc->compute(site,nSite,m_labeling[site],m_labeling[nSite]),weights[n]);
else if ( nSite < site )
{
addterm2_checked(e,i,m_lookupSiteVar[nSite],
sc->compute(site,nSite,alpha_label,alpha_label),
sc->compute(site,nSite,alpha_label,m_labeling[nSite]),
sc->compute(site,nSite,m_labeling[site],alpha_label),
sc->compute(site,nSite,m_labeling[site],m_labeling[nSite]),weights[n]);
}
}
}
}
//-----------------------------------------------------------------------------------
template <typename DataCostT>
void GCoptimization::setupDataCostsSwap(SiteID size, LabelID alpha_label, LabelID beta_label,
EnergyT *e,SiteID *activeSites )
{
DataCostT* dc = (DataCostT*)m_datacostFn;
for ( SiteID i = 0; i < size; i++ )
{
e->add_term1(i,dc->compute(activeSites[i],alpha_label),
dc->compute(activeSites[i],beta_label) );
}
}
//-------------------------------------------------------------------
template <typename SmoothCostT>
void GCoptimization::setupSmoothCostsSwap(SiteID size, LabelID alpha_label,LabelID beta_label,
EnergyT *e,SiteID *activeSites )
{
SiteID i,nSite,site,n,nNum,*nPointer;
EnergyTermType *weights;
SmoothCostT* sc = (SmoothCostT*)m_smoothcostFn;
for ( i = size - 1; i >= 0; i-- )
{
site = activeSites[i];
giveNeighborInfo(site,&nNum,&nPointer,&weights);
for ( n = 0; n < nNum; n++ )
{
nSite = nPointer[n];
if ( m_lookupSiteVar[nSite] == -1 )
addterm1_checked(e,i,sc->compute(site,nSite,alpha_label,m_labeling[nSite]),
sc->compute(site,nSite,beta_label, m_labeling[nSite]),weights[n]);
else if ( nSite < site )
{
addterm2_checked(e,i,m_lookupSiteVar[nSite],
sc->compute(site,nSite,alpha_label,alpha_label),
sc->compute(site,nSite,alpha_label,beta_label),
sc->compute(site,nSite,beta_label,alpha_label),
sc->compute(site,nSite,beta_label,beta_label),weights[n]);
}
}
}
}
//-----------------------------------------------------------------------------------
template <typename DataCostT>
void GCoptimization::applyNewLabeling(EnergyT *e,SiteID *activeSites,SiteID size,LabelID alpha_label)
{
DataCostT* dc = (DataCostT*)m_datacostFn;
for ( SiteID i = 0; i < size; i++ )
{
if ( e->get_var(i) == 0 )
{
SiteID site = activeSites[i];
LabelID prev = m_labeling[site];
m_labeling[site] = alpha_label;
m_labelCounts[alpha_label]++;
m_labelCounts[prev]--;
m_labelingDataCosts[site] = dc->compute(site,alpha_label);
}
}
m_labelingInfoDirty = true;
updateLabelingInfo(false,true,false); // labels have changed, so update necessary labeling info
}
//-----------------------------------------------------------------------------------
template <typename DataCostT>
void GCoptimization::updateLabelingDataCosts()
{
DataCostT* dc = (DataCostT*)m_datacostFn;
for (int i = 0; i < m_num_sites; ++i)
m_labelingDataCosts[i] = dc->compute(i,m_labeling[i]);
}
//-----------------------------------------------------------------------------------
template <typename DataCostT>
bool GCoptimization::solveSpecialCases(EnergyType& energy)
{
finalizeNeighbors();
DataCostT* dc = (DataCostT*)m_datacostFn;
bool sc = m_numNeighborsTotal != 0;
bool lc = m_labelcostsAll != 0;
if ( !dc && !sc && !lc )
{
energy = 0;
return true;
}
if ( dc && !sc && !lc ) {
// Special case: No label costs, so return trivial solution
energy = 0;
for ( SiteID i = 0; i < m_num_sites; ++i ) {
LabelID minCostLabel = 0;
EnergyTermType minCost = dc->compute(i, 0);
for ( LabelID l = 1; l < m_num_labels; ++l ) {
EnergyTermType lcost = dc->compute(i, l);
if ( lcost < minCost ) {
minCostLabel = l;
minCost = lcost;
}
}
if ( minCostLabel > GCO_MAX_ENERGYTERM )
handleError("Data cost was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
m_labeling[i] = minCostLabel;
energy += minCost;
}
m_labelingInfoDirty = true;
updateLabelingInfo();
return true;
}
if ( !dc && !sc && lc ) {
// Special case: No data costs, so return trivial solution
LabelID minLabel = 0;
EnergyType minLabelCost = GCO_MAX_ENERGYTERM*(EnergyType)m_num_labels;
for ( LabelID l = 0; l < m_num_labels; ++l ) {
EnergyType lcsum = 0;
for ( LabelCostIter* lci = m_labelcostsByLabel[l]; lci; lci = lci->next )
lcsum += lci->node->cost;
if ( lcsum < minLabelCost ) {
minLabel = l;
minLabelCost = lcsum;
}
}
for ( SiteID i = 0; i < m_num_sites; ++i )
m_labeling[i] = minLabel;
energy = minLabelCost;
m_labelingInfoDirty = true;
updateLabelingInfo();
return true;
}
if ( dc && !sc && lc ) {
LabelCost* lc;
for ( lc = m_labelcostsAll; lc; lc = lc->next )
if ( lc->numLabels > 1)
break;
if ( !lc ) {
// Special case: Data costs and per-label costs
energy = solveGreedy<DataCostT>();
return true;
}
}
// Otherwise, use full-blown expansion/swap
return false;
}
template <>
class GCoptimization::GreedyIter<GCoptimization::DataCostFnSparse> {
public:
GreedyIter(DataCostFnSparse& dc, SiteID)
: m_dc(dc), m_label(0), m_labelend(0)
{ }
OLGA_INLINE void start(const LabelID* labels, LabelID labelCount=1)
{
m_label = labels;
m_labelend = labels + labelCount;
if (labelCount > 0) {
m_site = m_dc.begin(*labels);
m_siteend = m_dc.end(*labels);
while (m_site == m_siteend) {
if (++m_label == m_labelend)
break;
m_site = m_dc.begin(*m_label);
m_siteend = m_dc.end(*m_label);
}
}
}
OLGA_INLINE SiteID site() const { return m_site.site(); }
OLGA_INLINE SiteID label() const { return *m_label; }
OLGA_INLINE bool done() const { return m_label >= m_labelend; }
OLGA_INLINE GreedyIter& operator++()
{
// The inner loop is over sites, not labels, because sparse data costs
// are stored as consecutive [sparse] SiteIDs with respect to each label.
if (++m_site == m_siteend) {
while (++m_label < m_labelend) {
m_site = m_dc.begin(*m_label);
m_siteend = m_dc.end(*m_label);
if (m_site != m_siteend)
break;
}
}
return *this;
}
OLGA_INLINE EnergyTermType compute() const { return m_site.cost(); }
OLGA_INLINE SiteID feasibleSites() const { return (SiteID)(m_siteend - m_site); }
private:
DataCostFnSparse::iterator m_site;
DataCostFnSparse::iterator m_siteend;
DataCostFnSparse& m_dc;
const LabelID* m_label;
const LabelID* m_labelend;
};
template <typename DataCostT>
GCoptimization::EnergyType GCoptimization::solveGreedy()
{
printStatus1("starting greedy algorithm (1 cycle only)");
m_stepsThisCycle = m_stepsThisCycleTotal = 0;
EnergyType estart = compute_energy();
EnergyType efinal = 0;
LabelID* oldLabeling = m_labeling;
m_labeling = new LabelID[m_num_sites];
EnergyType* e = new EnergyType[m_num_labels];
LabelID* order = new LabelID[m_num_labels]; // order[0..activeCount-1] contains the activated labels so far
try {
gcoclock_t ticks0all = gcoclock();
gcoclock_t ticks0 = gcoclock();
// clear active flags
for ( LabelCost* lc = m_labelcostsAll; lc; lc = lc->next)
lc->active = false;
DataCostT* dc = (DataCostT*)m_datacostFn;
GreedyIter<DataCostT> iter(*dc,m_num_sites);
LabelID alpha = 0;
// Treat first iteration as special case.
// Ignore current labeling and just find the greedy initial label.
for ( LabelID l = 0; l < m_num_labels; ++l ) {
e[l] = 0;
for ( LabelCostIter* lci = m_labelcostsByLabel[l]; lci; lci = lci->next )
e[l] += lci->node->cost;
iter.start(&l);
e[l] += (EnergyType)(m_num_sites - iter.feasibleSites()) * GCO_MAX_ENERGYTERM; // pre-add GCO_MAX_ENERGYTERM for all infeasible sites
for (; !iter.done(); ++iter) {
EnergyTermType dataCost = iter.compute();
if ( dataCost > GCO_MAX_ENERGYTERM )
handleError("Data cost was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
e[l] += dataCost;
if ( e[l] > e[alpha] ) // break out early if this will definitely
break; // not be a good label to start from
}
if ( e[l] < e[alpha] ) // choose alpha with minimum energy e[alpha]
alpha = l;
}
for ( SiteID i = 0; i < m_num_sites; ++i ) {
m_labeling[i] = alpha;
m_labelingDataCosts[i] = dc->compute(i,alpha);
}
for ( LabelCostIter* lci = m_labelcostsByLabel[alpha]; lci; lci = lci->next )
lci->node->active = true;
// List of labels in the order that they were expanded upon (order[0] first, order[1] second, ...)
for ( LabelID l = 0; l < m_num_labels; ++l )
order[l] = l;
order[alpha] = 0;
order[0] = alpha;
printStatus2(alpha,-1,m_num_sites,ticks0);
// Greedily expand remaining labels
for ( LabelID alpha_count = 1; alpha_count <= m_num_labels; ++alpha_count) {
checkInterrupt();
ticks0 = gcoclock();
// Energy e[l] for expanding on label 'l' starts at e[alpha] + new labelcosts for introducing l
LabelID alpha_prev = alpha;
for ( LabelID li = alpha_count; li < m_num_labels; ++li ) {
LabelID l = order[li];
e[l] = e[alpha_prev];
for ( LabelCostIter* lci = m_labelcostsByLabel[l]; lci; lci = lci->next )
if ( !lci->node->active )
e[l] += lci->node->cost;
}
// Loop over all sites and all remaining labels to calculate energy drop.
for ( iter.start(&order[alpha_count],m_num_labels-alpha_count); !iter.done(); ++iter ) {
EnergyTermType dc_l = iter.compute();
EnergyTermType dc_i = m_labelingDataCosts[iter.site()];
EnergyTermType delta_i = dc_l - dc_i;
if ( delta_i < 0 )
e[iter.label()] += delta_i;
}
// Choose the next alpha based on lowest resulting energy
LabelID alpha_index = alpha_count-1;
for ( LabelID li = alpha_count; li < m_num_labels; ++li ) {
LabelID l = order[li];
if ( e[l] < e[alpha] ) {
alpha = l;
alpha_index = li;
}
}
if ( alpha == alpha_prev )
break;
// Append alpha to the list of activated labels
LabelID temp = order[alpha_count];
order[alpha_count] = order[alpha_index];
order[alpha_index] = temp;
// Apply the new labeling, updating m_labelingDataCosts and active labelcosts as necessary
iter.start(&alpha);
SiteID size = iter.feasibleSites();
for ( ; !iter.done(); ++iter ) {
EnergyTermType dc_l = iter.compute();
EnergyTermType dc_i = m_labelingDataCosts[iter.site()];
EnergyTermType delta_i = dc_l - dc_i;
if ( delta_i < 0 ) {
m_labeling[iter.site()] = alpha;
m_labelingDataCosts[iter.site()] = dc_l;
}
}
for ( LabelCostIter* lci = m_labelcostsByLabel[alpha]; lci; lci = lci->next )
lci->node->active = true;
printStatus2(alpha,-1,size,ticks0);
}
efinal = e[alpha];
if ( efinal < estart ) {
// Greedy succeeded in lowering energy compared to initial labeling
delete [] oldLabeling;
m_labelingInfoDirty = true;
updateLabelingInfo(true,false,false); // update m_labelCounts only; m_labelingDataCosts and active labelcosts should be up to date
printStatus1(1,false,ticks0all);
} else {
// Greedy failed to find a lower energy, so revert everything
efinal = estart;
delete [] m_labeling;
m_labeling = oldLabeling;
m_labelingInfoDirty = true;
updateLabelingInfo(); // put all labeling info back the way it was
printStatus1(1,false,ticks0all);
}
delete [] order;
delete [] e;
} catch (...) {
delete [] order;
delete [] e;
throw;
}
return efinal;
}
//------------------------------------------------------------------
void GCoptimization::setDataCost(DataCostFn fn) {
specializeDataCostFunctor(DataCostFnFromFunction(fn));
m_labelingInfoDirty = true;
}
//------------------------------------------------------------------
void GCoptimization::setDataCost(DataCostFnExtra fn, void *extraData) {
specializeDataCostFunctor(DataCostFnFromFunctionExtra(fn, extraData));
m_labelingInfoDirty = true;
}
//-------------------------------------------------------------------
void GCoptimization::setDataCost(EnergyTermType *dataArray) {
specializeDataCostFunctor(DataCostFnFromArray(dataArray, m_num_labels));
m_labelingInfoDirty = true;
}
//-------------------------------------------------------------------
void GCoptimization::setDataCost(SiteID s, LabelID l, EnergyTermType e) {
if ( !m_datacostIndividual )
{
EnergyTermType* table = new EnergyTermType[m_num_sites*m_num_labels];
memset(table, 0, m_num_sites*m_num_labels*sizeof(EnergyTermType));
specializeDataCostFunctor(DataCostFnFromArray(table, m_num_labels));
m_datacostIndividual = table;
m_labelingInfoDirty = true;
}
m_datacostIndividual[s*m_num_labels + l] = e;
if ( m_labeling[s] == l )
m_labelingInfoDirty = true; // m_labelingDataCosts is dirty
}
//-------------------------------------------------------------------
void GCoptimization::setDataCostFunctor(DataCostFunctor* f) {
if ( m_datacostFnDelete )
m_datacostFnDelete(m_datacostFn);
if ( m_datacostIndividual )
{
delete [] m_datacostIndividual;
m_datacostIndividual = 0;
}
m_datacostFn = f;
m_datacostFnDelete = 0;
m_queryActiveSitesExpansion = &GCoptimization::queryActiveSitesExpansion<DataCostFunctor>;
m_setupDataCostsExpansion = &GCoptimization::setupDataCostsExpansion<DataCostFunctor>;
m_setupDataCostsSwap = &GCoptimization::setupDataCostsSwap<DataCostFunctor>;
m_applyNewLabeling = &GCoptimization::applyNewLabeling<DataCostFunctor>;
m_updateLabelingDataCosts = &GCoptimization::updateLabelingDataCosts<DataCostFunctor>;
m_solveSpecialCases = &GCoptimization::solveSpecialCases<DataCostFunctor>;
m_labelingInfoDirty = true;
}
//-------------------------------------------------------------------
void GCoptimization::setDataCost(LabelID l, SparseDataCost *costs, SiteID count)
{
if ( !m_datacostFn )
specializeDataCostFunctor(DataCostFnSparse(numSites(),numLabels()));
else if ( m_queryActiveSitesExpansion != (SiteID (GCoptimization::*)(LabelID,SiteID*))&GCoptimization::queryActiveSitesExpansion<DataCostFnSparse> )
handleError("Cannot apply sparse data costs after dense data costs have been used.");
m_labelingInfoDirty = true;
DataCostFnSparse* dc = (DataCostFnSparse*)m_datacostFn;
dc->set(l,costs,count);
}
//-------------------------------------------------------------------
void GCoptimization::setSmoothCost(SmoothCostFn fn) {
specializeSmoothCostFunctor(SmoothCostFnFromFunction(fn));
}
//-------------------------------------------------------------------
void GCoptimization::setSmoothCost(SmoothCostFnExtra fn, void* extraData) {
specializeSmoothCostFunctor(SmoothCostFnFromFunctionExtra(fn, extraData));
}
//-------------------------------------------------------------------
void GCoptimization::setSmoothCost(EnergyTermType *smoothArray) {
specializeSmoothCostFunctor(SmoothCostFnFromArray(smoothArray, m_num_labels));
}
//-------------------------------------------------------------------
void GCoptimization::setSmoothCost(LabelID l1, LabelID l2, EnergyTermType e){
if ( !m_smoothcostIndividual )
{
EnergyTermType* table = new EnergyTermType[m_num_labels*m_num_labels];
memset(table, 0, m_num_labels*m_num_labels*sizeof(EnergyTermType));
specializeSmoothCostFunctor(SmoothCostFnFromArray(table, m_num_labels));
m_smoothcostIndividual = table;
}
m_smoothcostIndividual[l1*m_num_labels + l2] = e;
}
//-------------------------------------------------------------------
void GCoptimization::setSmoothCostFunctor(SmoothCostFunctor* f) {
if ( m_smoothcostFnDelete )
m_smoothcostFnDelete(m_smoothcostFn);
if ( m_smoothcostIndividual )
{
delete [] m_smoothcostIndividual;
m_smoothcostIndividual = 0;
}
m_smoothcostFn = f;
m_smoothcostFnDelete = 0;
m_giveSmoothEnergyInternal = &GCoptimization::giveSmoothEnergyInternal<SmoothCostFunctor>;
m_setupSmoothCostsExpansion = &GCoptimization::setupSmoothCostsExpansion<SmoothCostFunctor>;
m_setupSmoothCostsSwap = &GCoptimization::setupSmoothCostsSwap<SmoothCostFunctor>;
}
//-------------------------------------------------------------------
void GCoptimization::setLabelCost(EnergyTermType cost)
{
EnergyTermType* lc = new EnergyTermType[m_num_labels];
for ( LabelID i = 0; i < m_num_labels; ++i )
lc[i] = cost;
setLabelCost(lc);
delete [] lc;
}
//-------------------------------------------------------------------
void GCoptimization::setLabelCost(EnergyTermType *costArray)
{
for ( LabelID i = 0; i < m_num_labels; ++i )
setLabelSubsetCost(&i, 1, costArray[i]);
}
//-------------------------------------------------------------------
void GCoptimization::setLabelSubsetCost(LabelID* labels, LabelID numLabels, EnergyTermType cost)
{
if ( cost < 0 )
handleError("Label costs must be non-negative.");
if ( cost > GCO_MAX_ENERGYTERM )
handleError("Label cost was larger than GCO_MAX_ENERGYTERM; danger of integer overflow.");
for ( LabelID i = 0; i < numLabels; ++i)
if ( labels[i] < 0 || labels[i] >= m_num_labels )
handleError("Invalid label id was found in label subset list.");
if ( !m_labelcostsByLabel ) {
m_labelcostsByLabel = new LabelCostIter*[m_num_labels];
memset(m_labelcostsByLabel, 0, m_num_labels*sizeof(void*));
}
// If this particular subset already has a cost, simply replace it.
for ( LabelCostIter* lci = m_labelcostsByLabel[labels[0]]; lci; lci = lci->next ) {
if ( numLabels == lci->node->numLabels ) {
if ( !memcmp(labels, lci->node->labels, numLabels*sizeof(LabelID)) ) {
// This label subset already exists, so just update the cost and return
lci->node->cost = cost;
return;
}
}
}
if (cost == 0)
return;
// Create a new LabelCost entry and add it to the appropriate lists
m_labelcostCount++;
LabelCost* lc = new LabelCost;
lc->cost = cost;
lc->active = false;
lc->aux = -1;
lc->numLabels = numLabels;
lc->labels = new LabelID[numLabels];
memcpy(lc->labels, labels, numLabels*sizeof(LabelID));
slist_prepend(m_labelcostsAll, lc);
for ( LabelID i = 0; i < numLabels; ++i ) {
LabelCostIter* lci = new LabelCostIter;
lci->node = lc;
slist_prepend(m_labelcostsByLabel[labels[i]], lci);
}
}
//-------------------------------------------------------------------
void GCoptimization::whatLabel(SiteID start, SiteID count, LabelID* labeling)
{
assert(start >= 0 && start+count <= m_num_sites);
memcpy(labeling, m_labeling+start, count*sizeof(LabelID));
}
//-------------------------------------------------------------------
GCoptimization::EnergyType GCoptimization::giveSmoothEnergy()
{
finalizeNeighbors();
if ( m_giveSmoothEnergyInternal )
return( (this->*m_giveSmoothEnergyInternal)());
return 0;
}
//-------------------------------------------------------------------
GCoptimization::EnergyType GCoptimization::giveDataEnergy()
{
updateLabelingInfo();
EnergyType energy = 0;
for ( SiteID i = 0; i < m_num_sites; i++ )
energy += m_labelingDataCosts[i];
return energy;
}
GCoptimization::EnergyType GCoptimization::giveLabelEnergy()
{
updateLabelingInfo();
EnergyType energy = 0;
for ( LabelCost* lc = m_labelcostsAll; lc; lc = lc->next)
if ( lc->active )
energy += lc->cost;
return energy;
}
//-------------------------------------------------------------------
GCoptimization::EnergyType GCoptimization::compute_energy()
{
return giveDataEnergy() + giveSmoothEnergy() + giveLabelEnergy();
}
//-------------------------------------------------------------------
void GCoptimization::permuteLabelTable()
{
if ( !m_random_label_order )
return;
for ( LabelID i = 0; i < m_num_labels; i++ )
{
LabelID j = i + (rand() % (m_num_labels-i));
LabelID temp = m_labelTable[i];
m_labelTable[i] = m_labelTable[j];
m_labelTable[j] = temp;
}
}
//-------------------------------------------------------------------
GCoptimization::EnergyType GCoptimization::expansion(int max_num_iterations)
{
EnergyType new_energy, old_energy;
if ( (this->*m_solveSpecialCases)(new_energy) )
return new_energy;
permuteLabelTable();
updateLabelingInfo();
try
{
if ( max_num_iterations == -1 )
{
// Strategic expansion loop focuses on labels that successfuly reduced the energy
printStatus1("starting alpha-expansion w/ adaptive cycles");
std::vector<LabelID> queueSizes;
queueSizes.push_back(m_num_labels);
int cycle = 1;
LabelID next = 0;
do
{
gcoclock_t ticks0 = gcoclock();
m_stepsThisCycle = 0;
// Make a pass over the unchecked labels in the current queue, i.e. m_labelTable[next..queueSize-1]
LabelID queueSize = queueSizes.back();
LabelID start = next;
m_stepsThisCycleTotal = queueSize - start;
do
{
if ( !alpha_expansion(m_labelTable[next]) )
std::swap(m_labelTable[next],m_labelTable[--queueSize]); // don't put this label in a new queue
else
++next; // keep this label for the next (smaller) queue
m_stepsThisCycle++;
} while ( next < queueSize );