-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbehaviour.cpp
More file actions
1674 lines (1391 loc) · 50.3 KB
/
behaviour.cpp
File metadata and controls
1674 lines (1391 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "behaviour.h"
#include <QtGlobal>
#include "QtWidgets/qerrormessage.h"
#include "account.h"
#include <QDebug>
#include <limits>
#include <algorithm>
#include <math.h>
QList<Behaviour*> Behaviour::behaviours;
Behaviour *Behaviour::currentBehaviour = nullptr;
Behaviour *Behaviour::defaultBehaviour = nullptr;
QMap<ParamType,QString> Behaviour::parameterKeys
{
{ParamType::procurement, "govt-procurement"},
{ParamType::emp_rate, "employment-rate"},
{ParamType::prop_con, "propensity-to-consume"},
{ParamType::inc_tax_rate, "income-tax-rate"},
{ParamType::inc_thresh, "income-threshold"},
{ParamType::sales_tax_rate, "sales-tax-rate"},
{ParamType::firm_creation_prob, "firm-creation-prob"},
{ParamType::dedns, "pre-tax-dedns-rate"},
{ParamType::unemp_ben_rate, "unempl-benefit-rate"},
{ParamType::active_pop, "active-population-rate"},
{ParamType::distrib, "reserve-rate"},
{ParamType::prop_inv, "prop-invest"},
{ParamType::boe_int, "boe-interest"},
{ParamType::bus_int, "bus-interest"},
{ParamType::loan_prob, "loan-prob"},
{ParamType::recoup, "capex-recoup-periods"},
};
// This function creates a Behaviour with the given name and default
// parameters (but doesn't set it as current -- perhaps it should).
Behaviour *Behaviour::createBehaviour(QString name)
{
qDebug() << "Behaviour::createBehaviour(): name =" << name;
qDebug() << "Behaviour::createBehaviour(): setting default parameters for model" << name;
if (name.isEmpty()) {
}
// Store default parameters:
// Note that global parameters (Behaviour-wide) are not listed in ParamType
// because they have no conditional values and so cannot be looked up in
// the general parameter retrieval function getParameterVal(). They are
// therefore dealt with as special cases without the convenience of being
// listed in parameter_keys[ParamType].
QSettings settings;
settings.beginGroup(name);
// Add all Behaviour-specific parameters with default values here,,,
settings.beginGroup("/default");
settings.setValue(parameterKeys[ParamType::procurement], 0);
settings.setValue(parameterKeys[ParamType::emp_rate], 95);
settings.setValue(parameterKeys[ParamType::prop_con], 80);
settings.setValue(parameterKeys[ParamType::inc_tax_rate], 10);
settings.setValue(parameterKeys[ParamType::inc_thresh], 50);
settings.setValue(parameterKeys[ParamType::sales_tax_rate], 0);
settings.setValue(parameterKeys[ParamType::firm_creation_prob], 0);
settings.setValue(parameterKeys[ParamType::dedns], 0);
settings.setValue(parameterKeys[ParamType::unemp_ben_rate], 60);
// This setting is not currently used and should not be confused with the
// emp_rate property. active_pop was intended to allow a distinction to be
// made between the population as a whole and the part of it that was
// actually active. In practice this hasn't been needed as we have
// assumed that the whole population is active (or equivalently that the
// nominal population size refers only to the active population).
settings.setValue(parameterKeys[ParamType::active_pop], 60);
settings.setValue(parameterKeys[ParamType::distrib], 50);
settings.setValue(parameterKeys[ParamType::prop_inv], 2);
settings.setValue(parameterKeys[ParamType::boe_int], 1);
settings.setValue(parameterKeys[ParamType::bus_int], 3);
settings.setValue(parameterKeys[ParamType::loan_prob], 0);
settings.setValue(parameterKeys[ParamType::recoup], 10);
settings.endGroup();
settings.endGroup();
// Create a Behaviour using the default parameters
qDebug() << "Behaviour::createBehaviour(): creating Behaviour"
<< name;
Behaviour *behaviour = new Behaviour(name);
// Add it to the global (static) list of models
qDebug() << "Behaviour::createBehaviour(): adding Behaviour"
<< name
<< "to list";
behaviours.append(behaviour);
// Return a pointer to the new Behaviour
return behaviour;
}
Behaviour *Behaviour::getBehaviour(QString name)
{
qDebug() << "Behaviour::getBehaviour("
<< name
<< "):"
<< "checking"
<< behaviours.count()
<< "behaviours";
for (int i = 0; i < behaviours.count(); i++)
{
if (behaviours[i]->name() == name)
{
qDebug() << "Behaviour::getBehaviour(): found behaviour with name"
<< name;
currentBehaviour = behaviours[i];
return currentBehaviour;
}
}
qDebug() << "Behaviour::getBehaviour(): cannot find behaviour with name"
<< name;
return nullptr; // no model found with that name
}
Behaviour *Behaviour::createDefaultBehaviour()
{
defaultBehaviour = new Behaviour("");
return defaultBehaviour;
}
// This creates a new Behaviour having the given name but without setting any
// parameters. These must be set immediately by calling setParameters() (TBD).
// If invoked with an empty behaviourName will create a default behaviour
// with default parameters. This is done in the This may subsequently be retrieved using
// static const Behaviour *Behaviour::defaultBehaviour(). Incidently, this is
// initially set to nullptr
Behaviour::Behaviour(QString behaviourName)
{
if (behaviourName.isEmpty())
{
if (nullptr != defaultBehaviour)
{
QErrorMessage msg;
msg.showMessage(tr("Cannot reset default behaviour"));
exit(997);
}
else
{
defaultBehaviour = this;
Params *p = new Params; // default parameter set
p->procurement.val = 0;
p->emp_rate.val = 95;
p->prop_con.val = 80;
p->inc_tax_rate.val = 10;
p->inc_thresh.val = 50;
p->sales_tax_rate.val = 0;
p->firm_creation_prob.val = 0;
p->dedns.val = 0;
p->unemp_ben_rate.val = 100;
p->active_pop.val = 60;
p->distrib.val = 90;
p->prop_inv.val = 20;
p->boe_int.val = 2;
p->bus_int.val = 3;
p->loan_prob.val = 4;
p->recoup.val = 10;
parameterSets.append(p);
_name = ""; // would not be valid for a user-defined behaviour
}
}
else
{
_name = behaviourName;
qDebug() << "Behaviour::Behaviour():" << behaviourName << "reading parameters";
readParameters();
// This should be global, and therefore maintained by MainWindow
#if 0
// _notes and _iterations must be retrieved from settings. Possibly best not
// to do this until they are needed as this constructor is called while
// traversing settings and looking up different settings seems likely to
// disrupt the process. Haven't checked this.
_notes = notes;
_iterations = iterations;
#endif
// ------------
// NEXT: The following processing should be Domain-specific
// ------------
#if 0
// Create the Government. This will automatically set up a single firm
// representing nationalised industries, civil service, and any other
// government owned business. Note that the Government itself (created
// here) is not a business and taxation is not a payment for goods or
// services. To access the Government-owned firm, use
// Government::gov_firm().
qDebug() << "Behaviour::Behaviour(" << behaviourName << "): creating Government";
// TODO: *** Government and central Bank now belong to Domain, but leave
// them here as well until new setup is in place. ***
_gov = new Government(this);
_bank = new Bank(this);
// -------------------------------------------------------------------------
// To add a new property it must be added to the enum class Property in the
// header file, and to the prop_list below (in the same position). Ordering
// is significant because it will be assumed in the getProperty() function.
// -------------------------------------------------------------------------
prop_list << Property::current_period
<< Property::pop_size
<< Property::gov_exp
<< Property::bens_paid
<< Property::gov_exp_plus
<< Property::gov_recpts
<< Property::deficit
<< Property::gov_bal
<< Property::num_firms
<< Property::num_emps
<< Property::pc_emps
<< Property::num_unemps
<< Property::pc_unemps
<< Property::num_gov_emps
<< Property::pc_active
<< Property::num_hired
<< Property::num_fired
<< Property::prod_bal
<< Property::wages
<< Property::consumption
<< Property::deficit_pc
<< Property::bonuses
<< Property::dedns
<< Property::inc_tax
<< Property::sales_tax
<< Property::dom_bal
<< Property::amount_owed
<< Property::bus_size
<< Property::hundred
<< Property::zero
<< Property::procurement
<< Property::productivity
<< Property::rel_productivity
<< Property::unbudgeted
<< Property::investment
<< Property::gdp
<< Property::profit
<< Property::num_properties; // dummy (keep at end)
// Set up an empty series for each property
qDebug() << "Behaviour::Behaviour():" << behaviourName << "setting up results series";
for (int i = 0; i < static_cast<int>(Property::num_properties); i++)
{
series[prop_list[i]] = new QLineSeries;
}
#endif
}
}
double Behaviour::scale(Property p)
{
double val = getPropertyVal(p);
switch(p)
{
case Property::current_period:
case Property::pc_emps:
case Property::pc_unemps:
case Property::pc_active:
case Property::deficit_pc:
case Property::hundred:
case Property::zero:
case Property::productivity:
case Property::rel_productivity:
case Property::num_properties:
return val;
case Property::pop_size:
case Property::gov_exp:
case Property::bens_paid:
case Property::gov_exp_plus:
case Property::unbudgeted:
case Property::gov_recpts:
case Property::deficit:
case Property::gov_bal:
case Property::num_firms:
case Property::num_emps:
case Property::num_unemps:
case Property::num_gov_emps:
case Property::num_hired:
case Property::num_fired:
case Property::prod_bal:
case Property::wages:
case Property::consumption:
case Property::bonuses:
case Property::dedns:
case Property::inc_tax:
case Property::sales_tax:
case Property::dom_bal:
case Property::amount_owed:
case Property::bus_size:
case Property::procurement:
case Property::investment:
case Property::gdp:
case Property::profit:
return val * _scale;
}
}
double Behaviour::gini()
{
int pop = workers.count();
double a = 0.0;
int n[pop]; //
for (int i = 0; i < pop; i++)
{
Worker *w = workers[i];
n[i] = w->getAverageWages(); // extend as required
}
std::sort(n, n + pop); // ascending order
for (int i = 1; i < pop; i++)
{
n[i] += n[i - 1]; // make values cumulative
}
double cum_tot = n[pop - 1];
double a_tot = (cum_tot * pop) / 2.0; // area A+B
for (int i = 0; i < pop; i++)
{
double diff = ((cum_tot * (i + 1)) / pop) - n[i];
if (diff < 0) {
diff = -diff;
qDebug() << "Behaviour::gini(): negative diff (" << diff << ") at interval" << i;
}
a += diff; // area A
}
qDebug() << "Behaviour::gini(): cum_tot =" << cum_tot << ", pop =" << pop << ", a =" << a << ", a_tot =" << a_tot;
_gini = a / a_tot;
return _gini;
}
double Behaviour::getGini()
{
return _gini;
}
double Behaviour::getProductivity()
{
return productivity();
}
double Behaviour::productivity()
{
double tot = 0.0;
int count = firms.count();
for (int i = 0; i < count; i++)
{
Firm *f = firms[i];
tot += f->getNumEmployees() * f->getProductivity();
}
double res = count == 0 ? 0 : (tot * 100) / _pop_size;
return res;
}
void Behaviour::readParameters()
{
// Get parameters for this Behaviour from settings.
QSettings settings;
qDebug() << "Behaviour::readParameters(): file is" << settings.fileName();
// TODO: Global settings (these should be read by, and stored in MainWindow)
_iterations = settings.value("iterations", 100).toInt();
_startups = settings.value("startups", 10).toInt();
_first_period = settings.value("start-period", 1).toInt();
_scale = settings.value("nominal-population", 1000).toDouble() / 1000;
_std_wage = settings.value("unit-wage", 100).toInt();
_population = 1000;
// Select parameters for this Behaviour
settings.beginGroup("Behaviours\\" + _name);
// Default (non-conditional) settings
settings.beginGroup(_name + "\\default");
// For the default parameter set we only care about the val component of
// each pair (and that's all that will have been stored for default
// parameters). For conditional parameters we will have to read in both
// elements of the pair.
Params *p = new Params; // default parameter set
p->procurement.val = settings.value(parameterKeys[ParamType::procurement], 0).toInt();
p->emp_rate.val = settings.value(parameterKeys[ParamType::emp_rate], 95).toInt();
p->prop_con.val = settings.value(parameterKeys[ParamType::prop_con], 80).toInt();
p->inc_tax_rate.val = settings.value(parameterKeys[ParamType::inc_tax_rate], 10).toInt();
p->inc_thresh.val = settings.value(parameterKeys[ParamType::inc_thresh], 50).toInt();
p->sales_tax_rate.val = settings.value(parameterKeys[ParamType::sales_tax_rate], 0).toInt();
p->firm_creation_prob.val = settings.value(parameterKeys[ParamType::firm_creation_prob], 0).toInt();
p->dedns.val = settings.value(parameterKeys[ParamType::dedns], 0).toInt();
p->unemp_ben_rate.val = settings.value(parameterKeys[ParamType::unemp_ben_rate], 100).toInt();
p->active_pop.val = settings.value(parameterKeys[ParamType::active_pop], 60).toInt();
p->distrib.val = settings.value(parameterKeys[ParamType::distrib], 90).toInt();
p->prop_inv.val = settings.value(parameterKeys[ParamType::prop_inv], 20).toInt();
p->boe_int.val = settings.value(parameterKeys[ParamType::boe_int], 2).toInt();
p->bus_int.val = settings.value(parameterKeys[ParamType::bus_int], 3).toInt();
p->loan_prob.val = settings.value(parameterKeys[ParamType::loan_prob], 4).toInt();
p->recoup.val = settings.value(parameterKeys[ParamType::recoup], 10).toInt();
settings.endGroup(); // end defaults
parameterSets.clear(); // TODO: it would be better to do this after appending
parameterSets.append(p); // append the defaults we just read
// How many conditional parameter sets...
numParameterSets = settings.value("pages", 1).toInt();
qDebug() << "Behaviour::readParameters(): Behaviour"
<< _name
<< "has"
<< numParameterSets
<< "pages";
for (int page = 1; page < numParameterSets; page++)
{
p = new Params; // conditional parameter set
// Start conditional settings
settings.beginGroup("condition-" + QString::number(page));
// Conditions are relations between properties and integer values
p->condition.property = getProperty(settings.value("property").toInt());
// relations are encoded as integers
int rel = settings.value("rel").toInt();
switch (rel)
{
case 0:
p->condition.opr = Opr::eq;
break;
case 1:
p->condition.opr = Opr::neq;
break;
case 2:
p->condition.opr = Opr::lt;
break;
case 3:
p->condition.opr = Opr::gt;
break;
case 4:
p->condition.opr = Opr::leq;
break;
case 5:
p->condition.opr = Opr::geq;
break;
default:
p->condition.opr = Opr::invalid_op;
break;
}
// Set the value
p->condition.val = settings.value("value").toInt();
// Get the parameter values to be applied if the codition is met. Where
// is_set is false the value will be ignored and the existing value --
// either default or from a previous condition -- used instead
QString attrib;
attrib = parameterKeys[ParamType::procurement];
p->procurement.is_set = settings.value(attrib + "/isset").toBool();
p->procurement.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::emp_rate];
p->emp_rate.is_set = settings.value(attrib + "/isset").toBool();
p->emp_rate.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::prop_con];
p->prop_con.is_set = settings.value(attrib + "/isset").toBool();
p->prop_con.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::inc_tax_rate];
p->inc_tax_rate.is_set = settings.value(attrib + "/isset").toBool();
p->inc_tax_rate.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::inc_thresh];
p->inc_thresh.is_set = settings.value(attrib + "/isset").toBool();
p->inc_thresh.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::sales_tax_rate];
p->sales_tax_rate.is_set = settings.value(attrib + "/isset").toBool();
p->sales_tax_rate.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::firm_creation_prob];
p->firm_creation_prob.is_set = settings.value(attrib + "/isset").toBool();
p->firm_creation_prob.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::dedns];
p->dedns.is_set = settings.value(attrib + "/isset").toBool();
p->dedns.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::unemp_ben_rate];
p->unemp_ben_rate.is_set = settings.value(attrib + "/isset").toBool();
p->unemp_ben_rate.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::active_pop];
p->active_pop.is_set = settings.value(attrib + "/isset").toBool();
p->active_pop.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::distrib];
p->distrib.is_set = settings.value(attrib + "/isset").toBool();
p->distrib.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::prop_inv];
p->prop_inv.is_set = settings.value(attrib + "/isset").toBool();
p->prop_inv.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::boe_int];
p->boe_int.is_set = settings.value(attrib + "/isset").toBool();
p->boe_int.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::bus_int];
p->bus_int.is_set = settings.value(attrib + "/isset").toBool();
p->bus_int.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::loan_prob];
p->loan_prob.is_set = settings.value(attrib + "/isset").toBool();
p->loan_prob.val = settings.value(attrib + "/value").toInt();
attrib = parameterKeys[ParamType::recoup];
p->recoup.is_set = settings.value(attrib + "/isset").toBool();
p->recoup.val = settings.value(attrib + "/value").toInt();
// End settings for this condition
settings.endGroup();
parameterSets.append(p);
}
settings.endGroup(); // end Behaviours group
qDebug() << "Behaviour::readParameters(): completed OK";
}
Behaviour::Property Behaviour::getProperty(int n)
{
Property p;
foreach(p, prop_list)
{
if (n == static_cast<int>(p))
{
return p;
}
}
Q_ASSERT(false);
return Property::zero; // prevent compiler warning
}
QString Behaviour::name()
{
return _name;
}
int Behaviour::getIters()
{
return _iterations;
}
int Behaviour::getStartPeriod()
{
return _first_period;
}
void Behaviour::restart()
{
readParameters();
// Clear all series
for (int i = 0; i < static_cast<int>(Property::num_properties); i++)
{
Property prop = prop_list[i];
series[prop]->clear();
}
int num_workers = workers.count();
int num_firms = firms.count();
// Delete all workers and clear the list
for (int i = 0; i < num_workers; i++)
{
delete workers[i];
}
workers.clear();
// Delete all firms and clear the list
for (int i = 0; i < num_firms; i++)
{
delete firms[i];
}
firms.clear();
firms.reserve(100);
// Reset the Government, which will re-create the gov firm as the first
// firm in the list
gov()->reset();
// Don't scale the number of startups internally, but must be scaled in
// stats reporting
for (int i = 0; i < _startups; i++)
{
createFirm();
}
}
// -----------------------------------------
// TODO: *** Remove all this function to MainWindow (?)
// Behaviour::run() is the main driver function
//
// TODO: Investigate using different cycles for salaries and payments
// -----------------------------------------
void Behaviour::run(bool randomised)
{
qDebug() << "Behaviour::run(): randomised =" << randomised << " _name =" << _name;
restart();
// ***
// Seed the pseudo-random number generator.
// We need reproducibility so we always seed with the same number.
// This makes inter-model comparisons more valid.
// ***
if (!randomised) {
qDebug() << "Behaviour::run(): using fixed seed (42)";
qsrand(42);
}
for (_period = 0; _period <= _iterations + _first_period; _period++)
{
// -------------------------------------------
// Initialise objects ready for next iteration
// -------------------------------------------
_dedns = 0; // deductions are tracked by the model object and are
// accumulated within but not across periods
_gov->init();
int num_workers = workers.count();
int num_firms = firms.count();
for (int i = 0; i < num_firms; i++) {
firms[i]->init();
}
for (int i = 0; i < num_workers; i++) {
workers[i]->init();
}
// Reset counters
num_hired = 0;
num_fired = 0;
num_just_fired = 0;
// -------------------------------------------
// Trigger objects
// -------------------------------------------
// Triggering government will direct payments to firms and benefits to
// workers before they are triggered
_gov->trigger(_period);
// Triggering firms will pay deductions to government and wages to
// workers. Firms will also fire any workers they can't afford to pay.
// Workers receiving payment will pay income tax to the government
for (int i = 0; i < num_firms; i++) {
firms[i]->trigger(_period);
}
// Trigger workers to make purchases
for (int i = 0; i < num_workers; i++) {
workers[i]->trigger(_period);
}
// -------------------------------------------
// Post-trigger (epilogue) phase
// -------------------------------------------
// Post-trigger for firms so they can pay tax on sales just made, pay
// bonuses, and hire more employees (investment)
for (int i = 0, c = firms.count(); i < c; i++) {
firms[i]->epilogue(_period);
}
// Same for workers so they can keep rolling averages up to date
for (int i = 0, c = workers.count(); i < c; i++) {
workers[i]->epilogue(_period);
}
// -------------------------------------------
// Stats
// -------------------------------------------
// Append the values from this iteration to the series
if (_period >= _first_period)
{
for (int i = 0; i < _num_properties/*static_cast<int>(Property::num_properties)*/; i++)
{
Property prop = prop_list[i];
double val = scale(prop);
series[prop]->append(_period, val);
int j = static_cast<int> (prop);
if (_period == _first_period)
{
max_val[j] = val;
min_val[j] = val;
sum[j] = val;
}
else
{
if (val > max_val[j])
{
max_val[j] = val;
}
else if (val < min_val[j])
{
min_val[j] = val;
}
sum[j] += val;
}
}
}
// -------------------------------------------
// Exogenous changes
// -------------------------------------------
// Create a new firm, possibly
if (qrand() % 100 < getFCP()) {
createFirm();
}
}
qDebug() << "Behaviour::run(): _name =" << _name << " gini =" << gini();
}
int Behaviour::period()
{
return _period;
}
int Behaviour::min_value(int ix)
{
qDebug() << "Behaviour::min_value(" << ix << ") returning" << min_val[ix];
return min_val[ix];
}
int Behaviour::max_value(int ix)
{
qDebug() << "Behaviour::max_value(" << ix << ") returning" << max_val[ix];
return max_val[ix];
}
int Behaviour::total(int ix)
{
return sum[ix];
}
Government *Behaviour::gov()
{
return _gov;
}
Bank *Behaviour::bank()
{
return _bank;
}
Firm *Behaviour::createFirm(bool state_supported)
{
Firm *firm = new Firm(this, state_supported);
if (state_supported)
{
QSettings settings;
hireSome(firm, getStdWage(), 0, settings.value("government-employees").toInt());
}
firms.append(firm);
return firm;
}
// Returns a random non-government firm or nullptr if there are none
Firm *Behaviour::selectRandomFirm(Firm *exclude)
{
// ***
// Any firm apart from the government firm. This is a bit of a trick. We
// make sure that the main (and currently, only) government-supported firm
// is created first so it will always be firms[0]. This enables us to
// select a random firm but excluding the government firm from the
// selection. Special acion is required if there are fewer than 2 firms.
// ***
Firm *res;
int n = firms.size();
if (n < 3) {
res = nullptr;
} else if (n == 3) {
return (exclude == firms[1] ? firms[2] : firms[1]);
} else {
while ((res = firms[(qrand() % (firms.size() - 1)) + 1]) == exclude);
}
return res;
}
int Behaviour::getWageBill(Firm *employer, bool include_dedns)
{
int tot = 0;
for (int i = 0; i < workers.count(); i++)
{
Worker *w = workers[i];
if (w->employer == employer)
{
tot += w->agreed_wage;
}
}
if (include_dedns)
{
tot *= (1.0 + getPreTaxDedns());
}
return tot;
}
int Behaviour::payWages(Firm *payer, int period)
{
double amt_paid = 0;
num_just_fired = 0;
QSettings settings;
double dedns_rate = getPreTaxDedns();
int num_workers = workers.count();
for (int i = 0; i < num_workers; i++)
{
Worker *w = workers[i];
if (w->isEmployedBy(payer))
{
int wage_due = w->agreed_wage;
double dedns = dedns_rate * wage_due;
double funds_available = payer->getBalance();
bool ok_to_pay = false;
if (funds_available - amt_paid < wage_due + dedns)
{
double shortfall = wage_due + dedns - funds_available + amt_paid;
if (payer->isGovernmentSupported())
{
// Get additional funds from government
gov()->debit(payer, shortfall);
// Transfer the funds to the payer
payer->credit(shortfall, gov());
ok_to_pay = true;
}
else
{
// Possibly request a loan, depending on policy.
// This assumes there are getLoanProb() returns an integer
// from 0 (= never) to 4 (= always)
if (qrand() % 4 < getLoanProb())
{
// Apply a bank loan to cover the shortfall
_bank->lend(shortfall, getBusRate(), payer);
ok_to_pay = true;
}
}
}
else
{
ok_to_pay = true;
}
if (ok_to_pay)
{
// Pay the full amount of wages to worker
workers[i]->credit(wage_due, payer);
// Pay the deductions straight back to the government.
gov()->credit(dedns, payer);
amt_paid += wage_due + dedns;
_dedns += dedns;
}
else
{
if (payer->isGovernmentSupported())
{
// This should never happen as govt-suptd payer can
// always get required funds from government
Q_ASSERT(false);
}
else
{
// Not able to pay this worker so fire instead
fire(w, period);
}
}
}
}
return amt_paid; // so caller can update balance
}
double Behaviour::payWorkers(double amount, Account *source, Reason reason)
{
double amt_paid = 0;
int num_workers = workers.count();
for (int i = 0; i < num_workers; i++)
{
switch (reason)
{
case for_benefits:
if (!workers[i]->isEmployed())
{
workers[i]->credit(amount, source);
amt_paid += amount;
}
break;
case for_bonus:
// Note that when paying bonuses we do not check that
// sufficient funds are available -- it's up to the caller to
// ensure that the amount is correct. Any overpayment will
// simply create a negative balance in the caller's account.
if (workers[i]->getEmployer() == source)
{
workers[i]->credit(amount, source);
amt_paid += amount;
}
break;
}
}
return amt_paid;
}
// ----------------------------------------------------------------------------
// These functions retrieve model properties
// ----------------------------------------------------------------------------
// IMPORTANT: Values must be retrieved in ascending order of Property because
// we save results on the way through so they can be used to deliver composite
// results more efficiently. If we ever need the composite results
// independently they should be calculated from scratch.
// Note also that this function returns a double, regardless of whether the
// parameter is integral or not. Stored values (generally marked by having '_'
// as the first character) are held in the most appropriate form, and access
// functions (e.g. period(), getWagesPaid(), etc) also return the correct type.
double Behaviour::getPropertyVal(Property p)
{
switch(p)