-
Notifications
You must be signed in to change notification settings - Fork 1
/
marzone.cpp
1376 lines (1134 loc) · 54.8 KB
/
marzone.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
// C++ file for Marxan with Zones
#include <ctype.h>
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits>
#include <omp.h>
#include <chrono>
#define MARZONE
#undef MEMDEBUG
#define DEBUGTRACEFILE
#undef ANNEALINGDETAILDEBUGTRACE
#undef EXTRADEBUGTRACE
#undef ANNEALING_TEST
#undef DEBUG_CM // this definition for debugging run time error in CM>0
#undef DEBUGFPERROR
#undef DEBUGCHECKCHANGE
#undef DEBUGCALCPENALTIES
#undef DEBUGNEWPENALTY
#undef DEBUGSHOWTIMEPASSED
#undef DEBUG_ZONECONNECTIONCALCS
#undef DEBUG_CONNECTIONCOST2
#undef DEBUG_COUNT_MISSING
#undef DEBUG_CONNECTIONCOST2_LINEAR
#undef DEBUGINITIALISERESERVE
#undef DEBUG_PuNotInAllowedZone
#undef DEBUG_CALC_PENALTIES
#undef DEBUG_CHANGE_PEN
#undef DEBUG_PEW_CHANGE_PEN
#undef ASYMCON
#undef PENX_MOD
#undef DEBUG_ZONATION_COST
#undef DEBUG_CONNOLLYINIT
#define DEBUG_PENALTY_NEGATIVE
#include "analysis.hpp"
#include "logger.hpp"
#include "marzone.hpp"
// Solver files
#include "solvers/simulated_annealing.hpp"
#include "solvers/population_annealing.hpp"
#include "solvers/heuristic.hpp"
#include "solvers/iterative_improvement.hpp"
namespace marzone {
// Version specific constants
string sVersionString = "Marxan with Zones v 4.0.6";
string sMarxanWebSite = "https://marxansolutions.org/";
string sDebugTraceFileName = "DebugTraceFile_Marxan_with_Zones.txt";
int iMemoryUsed=0;
int fSpecPROPLoaded = 0;
// version 2.0 introduces these features;
// enhanced flexibility in objectives
// probabilistic treatment of threats (1D prob)
// probabilistic treatment of species (2D prob)
// asymmetric connectivity
// multiple connectivity files
int iVerbosity;
int iOptimisationIterativeImprovement = 1, iPuZoneCount = 0;
int iOptimisationCalcPenalties = 1;
int asymmetricconnectivity = 0;
int iZoneContrib3On = 0;
int iZonationCost = 0;
mt19937 rngEngine;
Logger logger;
chrono::high_resolution_clock::time_point startTime;
string StartMessage()
{
stringstream myfile;
myfile << " " << sVersionString << " \n\n Spatial Prioritization via Zoning and Annealing\n\n";
myfile << " Marxan with Zones coded by Matthew Watts\n";
myfile << " Written by Ian Ball, Hugh Possingham and Matthew Watts\n\n";
myfile << " Based on Marxan coded by Ian Ball, modified by Matthew Watts\n";
myfile << " Written by Ian Ball and Hugh Possingham\n\n";
myfile << " Marxan website\n\n";
myfile << sMarxanWebSite << "\n\n";
return myfile.str();
}
int MarZone(string sInputFileName, int marxanIsSecondary)
{
// Set start time
startTime = chrono::high_resolution_clock::now();
srunoptions runoptions = {};
sfname fnames = {};
sanneal anneal = {};
int iMessageCounter = 0, iZoneSumSolnIndex;
int seedinit, aggexist=0,sepexist=0;
int itemp, ipu;
string tempname;
double rBestScore;
ShowStartupScreen();
SetOptions(sInputFileName, runoptions, anneal, fnames);
logger.verbosity = runoptions.verbose;
iVerbosity = runoptions.verbose;
SetRunOptions(runoptions);
#ifdef DEBUGTRACEFILE
logger.StartDebugTraceFile(sDebugTraceFileName);
logger.AppendDebugTraceFile(sVersionString + " begin execution\n\nLoadOptions\n");
if (iVerbosity > 3)
DumpFileNames(fnames, logger);
#endif
#ifdef DEBUGCHECKCHANGE
StartDebugFile("debug_MarZone_CheckChange.csv","ipu,puid,R,total,cost,connection,penalty,threshpen\n",fnames);
#endif
#ifdef DEBUG_CHANGE_PEN
StartDebugFile("debug_MarZone_ChangePen.csv","ipu,puid,isp,spid,cost,newamount,famount\n",fnames);
#endif
#ifdef DEBUG_PEW_CHANGE_PEN
StartDebugFile("debug_MarZone_PewChangePen.csv","iteration,ipu,isp,puid,spid,Zone,newZone,ZoneTarget,PUAmount,Amount,newAmount,Shortfall,newShortfall,rSF,rNSF,iCSF,iNSF,zone\n",fnames);
#endif
#ifdef DEBUGCALCPENALTIES
StartDebugFile("debug_MarZone_CalcPenalties.csv","\n",fnames);
#endif
delta = 10e-12;
rngEngine = mt19937(runoptions.iseed); // Initialize rng engine
#ifdef DEBUG
SaveSeed(runoptions.iseed);
#endif
logger.AppendDebugTraceFile("RandSeed iseed " + to_string(runoptions.iseed) + "\n");
// **** Data File Entry * * * * * * *
logger.ShowGenProg("\nEntering in the data files \n");
logger.AppendDebugTraceFile("before Loading Cost Names\n");
Costs costs(fnames, logger);
logger.AppendDebugTraceFile("before Loading Zone Files\n");
Zones zones(fnames, costs, logger); // load all zone files
// read in the MarZone files
logger.AppendDebugTraceFile("before Loading Pu Files (Pu lock, pu zone etc.)\n");
Pu pu(fnames, costs, asymmetricconnectivity, zones.zoneNames, logger);
logger.ShowDetProg(" Reading in the Planning Unit names \n");
logger.ShowGenProg(" There are " + to_string(pu.puno) + " Planning units.\n " + to_string(pu.puno) + " Planning Unit names read in \n");
logger.ShowDetProg(" Reading in the species file \n");
Species spec(fnames, logger);
logger.AppendDebugTraceFile("After Loading species files\n");
logger.ShowGenProg(" " + to_string(spec.spno) + " species read in \n");
#ifdef DEBUGTRACEFILE
if (iVerbosity > 3)
{
pu.DumpCostValues(fnames.outputdir + "debugCostValues.csv");
zones.DumpZoneNames(fnames.outputdir + "debugZoneNames.csv");
costs.DumpCostNames(fnames.outputdir + "debugCostNames.csv");
zones.DumpZoneContrib(fnames.outputdir + "debugZoneContrib.csv");
zones.DumpZoneContrib2(fnames.outputdir + "debugZoneContrib2.csv");
zones.DumpZoneContrib3(fnames.outputdir + "debugZoneContrib3.csv");
zones.DumpZoneTarget(fnames.outputdir + "debugZoneTarget.csv");
zones.DumpZoneTarget2(fnames.outputdir + "debugZoneTarget2.csv");
zones.DumpZoneCost(fnames.outputdir + "debugZoneCost.csv");
if (!fnames.pulockname.empty())
pu.DumpPuLock(fnames.outputdir + "debugPuLock.csv");
if (!fnames.puzonename.empty())
pu.DumpPuZone(fnames.outputdir + "debugPuZone.csv");
if (!fnames.relconnectioncostname.empty())
zones.DumpRelConnectionCost(fnames.outputdir + "debugZoneConnectionCost.csv");
}
#endif
// Build zone contributions.
zones.BuildZoneContributions(spec, pu);
if (fnames.zonetargetname.empty() && fnames.zonetarget2name.empty())
{
logger.ShowGenProg("Warning: No targets specified for zones.\n");
logger.AppendDebugTraceFile("Warning: No targets specified for zones.\n");
}
#ifdef DEBUGTRACEFILE
if (iVerbosity > 3)
{
zones.DumpZoneContribFinalValues(fnames.outputdir + "debug_ZoneContrib.csv", spec);
zones.DumpZoneCostFinalValues(fnames.outputdir + "debug_ZoneCost.csv", costs);
zones.DumpRelConnectionCostFinalValues(fnames.outputdir + "debug_ZoneConnectionCost.csv");
pu.DumpPuLockZoneData(fnames.outputdir + "debugPuLockZone.csv");
}
#endif
// Init analysis object
Analysis analysis;
if (fnames.savesumsoln)
{
logger.AppendDebugTraceFile("before InitSumSoln\n");
analysis.initSumSolution(pu.puno, zones.zoneCount);
logger.AppendDebugTraceFile("after InitSumSoln\n");
}
logger.ShowGenProg(" " + to_string(pu.connections.size()) + " connections entered \n");
logger.ShowDetProg(" Reading in the Planning Unit versus Species File \n");
logger.AppendDebugTraceFile("before LoadSparseMatrix\n");
pu.LoadSparseMatrix(spec, fnames.inputdir + fnames.puvsprname, logger);
logger.ShowGenProg(to_string(pu.puvspr.size()) + " conservation values counted, " +
to_string(pu.puno*spec.spno) + " big matrix size, " + to_string(pu.density) + "% density of matrix \n");
logger.AppendDebugTraceFile("after LoadSparseMatrix\n");
#ifdef DEBUGTRACEFILE
logger.AppendDebugTraceFile("before CalcTotalAreas\n");
CalcTotalAreas(pu,spec);
logger.AppendDebugTraceFile("after CalcTotalAreas\n");
#endif
if (fnames.savetotalareas)
{
tempname = fnames.savename + "_totalareas" + getFileSuffix(fnames.savetotalareas);
CalcTotalAreas(pu, spec, tempname);
}
// finalise zone and non-zone targets now that matrix has been loaded
if (spec.fSpecPROPLoaded)
{
logger.AppendDebugTraceFile("before ApplySpecProp\n");
// species have prop value specified
ApplySpecProp(spec, pu);
logger.AppendDebugTraceFile("after ApplySpecProp\n");
}
logger.AppendDebugTraceFile("before Build_ZoneTarget\n");
zones.BuildZoneTarget(spec, pu, fnames, logger);
logger.AppendDebugTraceFile("after Build_ZoneTarget\n");
if (iVerbosity > 3)
zones.DumpZoneTargetFinalValues(fnames.outputdir + "debug_ZoneTarget.csv", spec);
// Read and process species block definitions
logger.AppendDebugTraceFile("before process block definitions\n");
if (!fnames.blockdefname.empty())
{
logger.ShowDetProg(" Setting Block Definitions \n");
vector<double> totalSpecAmount = pu.TotalSpeciesAmount(spec.spno);
spec.SetSpeciesBlockDefinitions(totalSpecAmount);
}
spec.SetSpeciesDefaults();
logger.AppendDebugTraceFile("after process block definitions\n");
logger.ShowGenProgInfo("Checking to see if there are aggregating or separating species.\n");
if (fnames.savesen)
{
logger.AppendDebugTraceFile("before OutputScenario\n");
tempname = fnames.savename + "_sen.dat";
OutputScenario(pu.puno,spec.spno,zones.zoneCount, costs.costCount, logger, anneal, runoptions, tempname);
logger.AppendDebugTraceFile("after OutputScenario\n");
}
if (runoptions.verbose > 1)
logger.ShowTimePassed(startTime);
logger.AppendDebugTraceFile("before initializing reserve\n");
Reserve reserve(spec, zones.zoneCount, runoptions.clumptype);
// Init reserve object
reserve.InitializeSolution(pu.puno);
logger.AppendDebugTraceFile("after initializing reserve\n");
logger.AppendDebugTraceFile("before InitialiseReserve\n");
reserve.RandomiseSolution(pu, rngEngine, zones.zoneCount);
logger.AppendDebugTraceFile("after InitialiseReserve\n");
// * * * Pre-processing * * * * ***
logger.ShowGenProg("\nPre-processing Section. \n");
logger.ShowGenProgInfo(" Calculating all the penalties \n");
if (fnames.penaltyname.empty())
{
if (fnames.matrixspordername.empty())
{
logger.AppendDebugTraceFile("before CalcPenalties\n");
// we don't have sporder matrix available, so use slow CalcPenalties method
itemp = CalcPenalties(pu, spec, zones, reserve, runoptions.clumptype);
logger.AppendDebugTraceFile("after CalcPenalties\n");
}
else
{
logger.AppendDebugTraceFile("before CalcPenalties\n");
itemp = CalcPenalties(pu, spec, zones, reserve, runoptions.clumptype);
logger.AppendDebugTraceFile("after CalcPenalties\n");
}
if (itemp > 0)
logger.ShowProg(to_string(itemp) + " species cannot meet target%c.\n");
}
else
{
logger.AppendDebugTraceFile("before LoadPenalties\n");
spec.LoadCustomPenalties(fnames.inputdir + fnames.penaltyname, logger);
logger.AppendDebugTraceFile("after LoadPenalties\n");
}
logger.ShowTimePassed(startTime);
if (runoptions.AnnealingOn)
{
logger.ShowGenProgInfo(" Calculating temperatures.\n");
if (!anneal.Titns)
logger.ShowErrorMessage("Initial Temperature is set to zero. Fatal Error \n");
anneal.Tlen = anneal.iterations/anneal.Titns;
logger.ShowGenProgInfo(" Temperature length " + to_string(anneal.Tlen) + " \n");
logger.ShowGenProgInfo(" iterations " + to_string(anneal.iterations) + ", repeats " + to_string(runoptions.repeats) +" \n");
} // Annealing Preprocessing. Should be moved to SetAnnealingOptions
if (fnames.savepenalty)
{
string savePenaltyName = fnames.savename + "_penalty" + getFileSuffix(fnames.savepenalty);
spec.WritePenalties(savePenaltyName, fnames.savepenalty);
}
if (fnames.savespeciesdata)
{
string saveSpeciesName = fnames.savename + "_spec.csv";
spec.WriteSpeciesData(saveSpeciesName, reserve.speciesAmounts);
}
if (fnames.savesolutionsmatrix)
{
string saveSolutionMatrixName = fnames.savename + "_solutionsmatrix" + getFileSuffix(fnames.savesolutionsmatrix);
pu.WriteSolutionsMatrixHeader(saveSolutionMatrixName,fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
for (int i=0;i<zones.zoneCount;i++)
{
string saveSolutionMatrixNameByZone = fnames.savename + "_solutionsmatrix_zone" + to_string(zones.IndexToId(i)) + getFileSuffix(fnames.savesolutionsmatrix);
// init solutions matrix for each zone separately
pu.WriteSolutionsMatrixHeader(saveSolutionMatrixNameByZone,fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
}
}
// The larger repetition loop
// for each repeat run
Reserve bestR;
vector<string> summaries(runoptions.repeats);
bestR.objective.total = numeric_limits<double>::max();
// lock for bestR
omp_lock_t bestR_write_lock;
omp_init_lock(&bestR_write_lock);
// lock for solutions matrix
omp_lock_t matrix_write_lock;
omp_init_lock(&matrix_write_lock);
//create seeds for local rng engines
vector<unsigned int> seeds(runoptions.repeats);
for (int run_id = 1; run_id <= runoptions.repeats; run_id++)
seeds[run_id - 1] = run_id*runoptions.iseed;
bool quitting_loop = false;
int maxThreads = omp_get_max_threads();
logger.ShowGenProg("Running " + to_string(runoptions.repeats) + " runs multithreaded over number of threads: " + to_string(maxThreads) + "\n");
logger.ShowGenProg("Runs will show as they complete, and may not be in sequential order.\n");
#pragma omp parallel for schedule(dynamic)
for (int irun = 1;irun <= runoptions.repeats;irun++)
{
if(quitting_loop)
continue; //skipping iterations. It is not allowed to break or throw out omp for loop.
mt19937 rngThread(seeds[irun-1]);
stringstream debugbuffer; // buffer to print at the end
stringstream progbuffer; // buffer to print at the end
try
{
// Create new reserve object and init
Reserve reserveThread(spec, zones.zoneCount, runoptions.clumptype, irun);
reserveThread.InitializeSolution(pu.puno);
reserveThread.RandomiseSolution(pu, rngThread, zones.zoneCount);
debugbuffer << "annealing start run " << irun << "\n";
if (runoptions.verbose > 1)
progbuffer << "\nRun: " << irun << " ";
SimulatedAnnealing sa(fnames, runoptions.AnnealingOn, anneal,
rngEngine, fnames.saveannealingtrace, irun);
if (runoptions.AnnealingOn && !runoptions.PopulationAnnealingOn)
{
debugbuffer << "before Annealling Init run " << irun << "\n";
// init sa parameters if setting is appropriate
sa.Initialize(spec, pu, zones, runoptions.clumptype, runoptions.blm);
debugbuffer << "after Annealling Init run " << irun << "\n";
if (runoptions.verbose > 1)
progbuffer << " Using Calculated Tinit = " << sa.settings.Tinit << "Tcool = " << sa.settings.Tcool << "\n";
} // Annealing Setup only for sa
if (runoptions.verbose > 1)
progbuffer << " creating the initial reserve \n";
debugbuffer << "before ZonationCost run " << irun << "\n";
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
debugbuffer << "after ZonationCost run " << irun << "\n";
if (runoptions.verbose > 1)
{
progbuffer << "\n Init:";
PrintResVal(reserveThread, spec, zones, runoptions.misslevel, progbuffer);
}
if (runoptions.verbose > 5)
{
logger.ShowTimePassed(startTime);
}
// * * * * * * * * * * * * * * * * * * * ***
// * * * main annealing algorithm * * * * *
// * * * * * * * * * * * * * * * * * * * ***
if (runoptions.AnnealingOn && !runoptions.PopulationAnnealingOn)
{
debugbuffer << "before Annealing run " << irun << "\n";
if (runoptions.verbose > 1)
progbuffer << " Main Annealing Section.\n";
sa.RunAnneal(reserveThread, spec, pu, zones, runoptions.tpf1, runoptions.tpf2, runoptions.costthresh, runoptions.blm, logger);
if (runoptions.verbose > 1)
{
progbuffer << " ThermalAnnealing:";
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
PrintResVal(reserveThread, spec, zones, runoptions.misslevel, progbuffer);
}
debugbuffer << "after Annealing run " << irun << "\n";
}
else if (runoptions.PopulationAnnealingOn)
{
// run population annealing instead of regular thermal annealing
debugbuffer << "before population annealing run " << irun << "\n";
progbuffer << " Main Population Annealing Section.\n";
PopulationAnnealing popAnneal(anneal, rngEngine, irun, fnames);
popAnneal.Run(reserveThread, spec, pu, zones, runoptions.tpf1, runoptions.tpf2, runoptions.costthresh, runoptions.blm, logger);
if (runoptions.verbose > 1)
{
progbuffer << " PopAnnealing:";
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
PrintResVal(reserveThread, spec, zones, runoptions.misslevel, progbuffer);
}
}
if (runoptions.HeuristicOn)
{
debugbuffer << "before Heuristics run " << irun << "\n";
Heuristic heur = Heuristic(rngThread, runoptions.heurotype);
heur.RunHeuristic(reserveThread, spec, pu, zones, runoptions.tpf1, runoptions.tpf2, runoptions.costthresh, runoptions.blm);
if (runoptions.verbose > 1 && (runoptions.runopts == 2 || runoptions.runopts == 5))
{
progbuffer << "\n Heuristic:";
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
PrintResVal(reserveThread, spec, zones, runoptions.misslevel, progbuffer);
}
debugbuffer << "after Heuristics run " << irun << "\n";
} // Activate Greedy
if (runoptions.ItImpOn)
{
debugbuffer << "before IterativeImprovementOptimise run " << irun << "\n";
IterativeImprovement itImp = IterativeImprovement(rngThread, fnames, runoptions.itimptype);
itImp.Run(reserveThread, spec, pu, zones, runoptions.tpf1, runoptions.tpf2, runoptions.costthresh, runoptions.blm);
debugbuffer << "after IterativeImprovementOptimise run " << irun << "\n";
if (runoptions.verbose > 1)
{
progbuffer << " Iterative Improvement:";
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
PrintResVal(reserveThread, spec, zones, runoptions.misslevel, progbuffer);
}
} // Activate Iterative Improvement
debugbuffer << "before file output run " << irun << "\n";
// Start writing output
string tempname2;
string paddedRun = intToPaddedString(irun, 5);
if (fnames.saverun)
{
tempname2 = fnames.savename + "_r" + paddedRun + getFileSuffix(fnames.saverun);
reserveThread.WriteSolution(tempname2, pu, zones, fnames.saverun);
}
debugbuffer << "WriteSolution ran " << irun << "\n";
// re-evaluate entire system in case of any floating point/evaluation errors.
reserveThread.EvaluateObjectiveValue(pu, spec, zones, runoptions.blm);
if (fnames.savespecies && fnames.saverun)
{
// output species distribution for a run (specific reserve)
tempname2 = fnames.savename + "_mv" + paddedRun + getFileSuffix(fnames.savespecies);
OutputFeatures(tempname2, zones, reserveThread, spec, fnames.savespecies, runoptions.misslevel);
}
if (fnames.savesum)
{
summaries[irun - 1] = OutputSummaryString(pu, spec, zones, reserveThread, runoptions.misslevel, fnames.savesum, runoptions.blm);
}
#ifdef DEBUGFPERROR
debugbuffer << "OutputSummary ran\n";
#endif
// Saving the best from all the runs
if (fnames.savebest)
{
if (reserveThread.objective.total < bestR.objective.total)
{
omp_set_lock(&bestR_write_lock);
if (reserveThread.objective.total < bestR.objective.total)
{
bestR = reserveThread; // deep copy
if (runoptions.verbose > 1)
{
progbuffer << " Best:";
PrintResVal(bestR, spec, zones, runoptions.misslevel, progbuffer);
}
}
omp_unset_lock(&bestR_write_lock);
}
}
if (fnames.savesumsoln) // Add current run to my summed solution
analysis.ApplyReserveToSumSoln(reserveThread);
if (fnames.savesolutionsmatrix)
{
omp_set_lock(&matrix_write_lock);
string solutionsMatrixName = fnames.savename + "_solutionsmatrix" + getFileSuffix(fnames.savesolutionsmatrix);
reserveThread.AppendSolutionsMatrix(solutionsMatrixName, zones.zoneCount, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
for (int i = 0; i < zones.zoneCount; i++)
{
string solutionsMatrixZoneName = fnames.savename + "_solutionsmatrix_zone" + to_string(zones.IndexToId(i)) + getFileSuffix(fnames.savesolutionsmatrix);
// append solutions matrix for each zone separately
reserveThread.AppendSolutionsMatrixZone(solutionsMatrixZoneName, i, fnames.savesolutionsmatrix, fnames.solutionsmatrixheaders);
}
omp_unset_lock(&matrix_write_lock);
}
if (fnames.savezoneconnectivitysum)
{
string zoneConnectivityName = fnames.savename + "_zoneconnectivitysum" + paddedRun + getFileSuffix(fnames.savezoneconnectivitysum);
reserveThread.WriteZoneConnectivitySum(zoneConnectivityName, pu, zones, fnames.savezoneconnectivitysum);
}
debugbuffer << "after file output run " << irun << "\n";
debugbuffer << "annealing end run " << irun << "\n";
if (marxanIsSecondary == 1)
WriteSecondarySyncFileRun(irun);
}
catch (const exception &e)
{
// No matter how thread runs, record the message and exception if any.
string msg = "Exception on run " + to_string(irun) + " Message: " + e.what() + "\n";
progbuffer << msg;
debugbuffer << msg;
//cannot throw or break out of omp loop
quitting_loop = true;
continue;
}
// print the logs/debugs
logger.ShowProg(progbuffer.str());
logger.AppendDebugTraceFile(debugbuffer.str());
if (runoptions.verbose > 1)
logger.ShowTimePassed(startTime);
} // ** the repeats **
if (quitting_loop)
{
logger.ShowErrorMessage("\nRuns were aborted due to error.\n");
}
// Output summary
if (fnames.savesum)
{
string tempname2 = fnames.savename + "_sum" + getFileSuffix(fnames.savesum);
OutputSummary(pu, zones, summaries, tempname2, fnames.savesum);
}
logger.AppendDebugTraceFile("before final file output\n");
if (fnames.savebest)
{
string saveBestName = fnames.savename + "_best" + getFileSuffix(fnames.savebest);
bestR.WriteSolution(saveBestName, pu, zones, fnames.savebest);
logger.AppendDebugTraceFile("Best solution is run " + to_string(bestR.id) + "\n");
logger.ShowProg("\nBest solution is run " + to_string(bestR.id) + "\n");
// Print the best solution
stringstream bestbuf;
PrintResVal(bestR, spec, zones, runoptions.misslevel, bestbuf);
logger.ShowWarningMessage(bestbuf.str());
if (fnames.savezoneconnectivitysum)
{
string saveZoneConnectivityName = fnames.savename + "_zoneconnectivitysumbest" + getFileSuffix(fnames.savezoneconnectivitysum);
bestR.WriteZoneConnectivitySum(saveZoneConnectivityName, pu, zones, fnames.savezoneconnectivitysum);
}
if (fnames.savespecies)
{
string saveBestSpeciesName = fnames.savename + "_mvbest" + getFileSuffix(fnames.savespecies);
OutputFeatures(saveBestSpeciesName,zones, bestR, spec,fnames.savespecies, runoptions.misslevel);
}
}
if (fnames.savesumsoln)
{
string saveSumSolnName = fnames.savename + "_ssoln" + getFileSuffix(fnames.savesumsoln);
analysis.WriteAllSumSoln(saveSumSolnName, pu, zones, fnames.savesumsoln);
}
ShowShutdownScreen();
logger.CloseLogFile();
#ifdef DEBUGTRACEFILE
logger.AppendDebugTraceFile("end final file output\n");
logger.AppendDebugTraceFile("\nMarxan with Zones end execution\n");
#endif
return 0;
} // MarZone
// *** Set run options. Takes an integer runopts value and returns flags ***
void SetRunOptions(srunoptions& runoptions)
{
if (runoptions.runopts < 0)
return; // runopts < 0 indicates that these are set in some other way
switch (runoptions.runopts)
{
case 0:
runoptions.AnnealingOn = 1;
runoptions.HeuristicOn = 1;
runoptions.ItImpOn = 0;
break;
case 1:
runoptions.AnnealingOn = 1;
runoptions.HeuristicOn = 0;
runoptions.ItImpOn = 1;
break;
case 2:
runoptions.AnnealingOn = 1;
runoptions.HeuristicOn = 1;
runoptions.ItImpOn = 1;
break;
case 3:
runoptions.AnnealingOn = 0;
runoptions.HeuristicOn = 1;
runoptions.ItImpOn = 0;
break;
case 4:
runoptions.AnnealingOn = 0;
runoptions.HeuristicOn = 0;
runoptions.ItImpOn = 1;
break;
case 5:
runoptions.AnnealingOn = 0;
runoptions.HeuristicOn = 1;
runoptions.ItImpOn = 1;
break;
case 6:
runoptions.AnnealingOn = 1;
runoptions.HeuristicOn = 0;
runoptions.ItImpOn = 0;
break;
default:
runoptions.AnnealingOn = 0;
runoptions.HeuristicOn = 0;
runoptions.ItImpOn = 0;
break;
}
} // Set Run Options
// * * * * Calculate Initial Penalties * * * *
// This routine calculates the initial penalties or the penalty if you had no representation
int CalcPenalties(Pu& pu, Species& spec, Zones& zones, Reserve& r, int clumptype) {
int badspecies = 0, goodspecies = 0, itargetocc;
double rZoneSumTarg, iZoneSumOcc, penalty, ftarget, rAmount, ftemp;
vector<double> specTargetZones = zones.AggregateTargetAreaBySpecies(spec.spno);
vector<int> specOccurrenceZones = zones.AggregateTargetOccurrenceBySpecies(spec.spno);
vector<vector<lockedPenaltyTerm>> lockedSpecAmounts;
vector<vector<penaltyTerm>> specPuAmounts = pu.getPuAmountsSorted(spec.spno, lockedSpecAmounts); // list of pus that contribute to a species.
for (int i = 0; i < spec.spno; i++)
{
rZoneSumTarg = specTargetZones[i];
iZoneSumOcc = specOccurrenceZones[i];
sspecies &specTerm = spec.specList[i];
if (specTerm.target > rZoneSumTarg)
rZoneSumTarg = specTerm.target;
if (specTerm.targetocc > iZoneSumOcc)
iZoneSumOcc = specTerm.targetocc;
if (specTerm.target2)
{
int j = r.ComputePenaltyType4(specTerm, specPuAmounts[i], i, rZoneSumTarg, specTerm.target2, iZoneSumOcc);
badspecies += (j > 0);
goodspecies += (j < 0);
continue;
} // Species has aggregation requirements
itargetocc = 0, ftarget = 0.0, penalty = 0.0;
int lockedZone = -1;
double lockedContrib = 0.0;
// For this species, sum up all locked occurrences and areas.
for (lockedPenaltyTerm& term: lockedSpecAmounts[i]) {
lockedZone = term.lockedZoneId;
//lockedContrib = zones.GetZoneContrib(i, lockedZone);
//if (lockedContrib) {
// Do this calculation by taking into account zonecontrib of the locked zone. If positive contrib, we count it.
// rAmount = term.amount*lockedContrib;
rAmount = term.amount;
if (rAmount > 0) {
ftarget += rAmount;
itargetocc++;
penalty += rtnMaxNonAvailableCost(term.puindex, pu, zones);
}
//}
}
spec.specList[i].penalty = penalty;
// Already adequately represented on type 2 planning unit
if (ftarget >= rZoneSumTarg && itargetocc >= iZoneSumOcc)
{
goodspecies++;
logger.ShowGenProgInfo("Species " + to_string(spec.specList[i].name) +"(" +
spec.specList[i].sname + ") has already met target " + to_string(rZoneSumTarg) +"\n");
continue;
}
// cycle through all pus that contain this spec, and keep adding until spec target is met
bool targetMet = false;
for (penaltyTerm& p: specPuAmounts[i]) {
if (p.amount) {
ftarget += p.amount;
itargetocc++;
spec.specList[i].penalty += p.cost;
}
// Check if targets met
if (ftarget >= rZoneSumTarg && itargetocc >= iZoneSumOcc) {
targetMet = true;
break;
}
}
// If target not met with available pu, scale the penalty.
if (!targetMet) {
logger.ShowGenProgInfo("Species " + to_string(spec.specList[i].name) + "(" +
spec.specList[i].sname + ") cannot reach target " + to_string(rZoneSumTarg) + " there is only " + to_string(ftarget) + " available.\n");
if (ftarget == 0)
ftarget = delta; // Protect against divide by zero
ftemp = 0;
if (ftarget < rZoneSumTarg)
ftemp = rZoneSumTarg / ftarget;
if (itargetocc < iZoneSumOcc && itargetocc) // If ! itargetocc then also !ftarget
ftemp += (double)iZoneSumOcc / (double)itargetocc;
spec.specList[i].penalty = spec.specList[i].penalty * ftemp; // Scale it up
// This value will be ~ 1/delta when there are no occ's of target species in system
badspecies++;
}
}
if (goodspecies)
logger.ShowGenProg(to_string(goodspecies) + " species are already adequately represented.\n");
logger.AppendDebugTraceFile("CalcPenalties end\n");
return(badspecies);
}
double rtnMaxNonAvailableCost(int ipu, Pu& pu, Zones& zones)
{
double fcost = 0, rMaxCost = 0;
if (zones.availableZoneCost) // only needed if there is zone cost specified.
for (int iZone = 0; iZone < zones.zoneCount; iZone++)
{
fcost = ReturnPuZoneCost(ipu, iZone, pu, zones);
if (fcost > rMaxCost)
rMaxCost = fcost;
}
else
rMaxCost = pu.puList[ipu].cost;
rMaxCost += pu.ConnectionCost1(ipu);
return(rMaxCost);
} // Cost of Planning Unit
// return cost of planning unit in given zone
// parameter iZone is zero base
double ReturnPuZoneCost(int ipu,int iZone, Pu& pu, Zones& zones)
{
return zones.AggregateTotalCostByPuAndZone(iZone, pu.puList[ipu].costBreakdown);
}
// * * * * * * * * * * * * * * * * * * * * * * * * *****
// * * * * *** Post Processing * * * * * * * * * * * * *
// * * * * * * * * * * * * * * * * * * * * * * * * *****
// * * * * Reporting Value of a Reserve * * * *
void PrintResVal(Reserve& reserve, Species& spec, Zones& zones, double misslevel, stringstream& buffer)
{
int iMissing;
double rMPM;
iMissing = reserve.CountMissing(spec, zones, misslevel, rMPM);
string sPuZones = reserve.CountPuZones(zones);
// Attach message to buffer
buffer << "Value " << reserve.objective.total << " "
<< "Cost " << reserve.objective.cost << " " << sPuZones << " "
<< "Connection " << reserve.objective.connection << " "
<< "Missing " << iMissing << " "
<< "Shortfall " << reserve.objective.shortfall << " "
<< "Penalty " << reserve.objective.penalty << " "
<< "MPM " << rMPM << "\n";
} /* * * * Print Reserve Value * * * * */
/*
Output functions
*/
/* * * * ***** Output Solutions * * * * * * * */
/** imode = 1 Output Summary Stats only ******/
/** imode = 2 Output Everything * * * * *****/
void OutputSummary(Pu& pu, Zones& zones, vector<string>& summaries, string filename, int imode) {
ofstream fp; /* Imode = 1, REST output, Imode = 2, Arcview output */
fp.open(filename);
if (!fp.is_open())
logger.ShowErrorMessage("Cannot save output to " + filename + " \n");
string sZoneNames = zones.ZoneNameHeaders(imode, " PuCount");
string sZoneCostNames = zones.ZoneNameHeaders(imode, " Cost");
if (imode > 1)
{
fp << "\"Run Number\",\"Score\",\"Cost\",\"Planning Units\"" << sZoneNames << sZoneCostNames;
fp << ",\"Connection Strength\",\"Penalty\",\"Shortfall\",\"Missing_Values\",\"MPM\"\n";
}
else
{
fp << "Run no. Score Cost Planning Units " << sZoneNames << sZoneCostNames;
fp << " Connection_Strength Penalty Shortfall Missing_Values MPM\n";
}
// write all summaries in run order
for (string& s: summaries) {
fp << s;
}
fp.close();
}
// formats a summary string for a particular run.
string OutputSummaryString(Pu& pu, Species& spec, Zones& zones, Reserve& r, double misslevel, int imode, double blm)
{
int ino=0,isp;
double connectiontemp = 0,rMPM;
stringstream s;
string d = imode > 1 ? "," : " ";
string sZoneNames,sZonePuCount,sZoneCostNames,sZoneCost;
r.CountPuZones2(zones, imode, sZonePuCount);
r.CostPuZones(pu, zones, sZoneCost, imode);
/*** Ouput the Summary Statistics *****/
for (int i=0;i<pu.puno;i++)
if (r.solution[i] < 0)
ino ++;
isp = r.CountMissing(spec, zones, misslevel, rMPM);
for (int i=0;i<pu.puno;i++)
{
connectiontemp += zones.ConnectionCost2Linear(pu, i, 1, r.solution, blm);
} /* Find True (non modified) connection */
s << r.id << d << r.objective.total << d << r.objective.cost << d << ino << sZonePuCount
<< sZoneCost << d << connectiontemp << d << r.objective.penalty << d << r.objective.shortfall << d << isp << d << rMPM << "\n";
return s.str();
} // OutputSummary
/* * * * * * * * * * * * * * * * * * * * ****/
/* * * * Main functions * * * * * * * * ***/
/* * * * * * * * * * * * * * * * * * * * ****/
/* The following function shows the startup screen information.
The program title and authors */
void ShowStartupScreen(void)
{
logger.ShowProg(StartMessage());
} /* Show Startup Screen */
/* Show ShutDown Screen displays all the end of program information. It only displays when
the iVerbosity has been set to 1 or higher */
void ShowShutdownScreen(void)
{
logger.ShowProg("\n");
logger.ShowTimePassed(startTime);
logger.ShowProg("\n The End. \n");
}
void SaveSeed(int iseed)
{
ofstream fp;
fp.open("debug.out");
fp << "Debugging Output! \n";
fp << "iseed is " << iseed << " \n";
fp.close();
}
/* ShowPauseExit delivers a message prior to exiting */
void ShowPauseExit(void)
{
logger.ShowProg("Press return to exit.\n");
std::cin.get();
} /* Show Pause Exit */
void WriteSecondarySyncFileRun(int iSyncRun)
{
FILE *fsync;
char sSyncFileName[80];
if (iSyncRun)
sprintf(sSyncFileName, "sync%i", iSyncRun);
else
sprintf(sSyncFileName, "sync");
fsync = fopen(sSyncFileName, "w");
fprintf(fsync, "%s", sSyncFileName);
fclose(fsync);