-
Notifications
You must be signed in to change notification settings - Fork 5
/
Agent.py
executable file
·1573 lines (1284 loc) · 63 KB
/
Agent.py
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
# Agent.py
from Tools import *
from agTools import *
from random import *
import graphicDisplayGlobalVarAndFunctions as gvf
import commonVar as common
import numpy.random as npr
import numpy
import pandas as pd
import os
def mySort(ag):
if ag == []:
return []
numAg = []
for a in ag:
numAg.append((a.number, a))
numAg.sort()
agSorted = []
for i in range(len(numAg)):
agSorted.append(numAg[i][1])
return agSorted
def applyRationallyTheRateOfChange(base,rate):
if rate >= 0:
return base*(1+rate)
if rate < 0:
return base/(1+abs(rate))
class Agent(SuperAgent):
def __init__(self, number, myWorldState,
xPos=0, yPos=0, agType=""):
# print xPos,yPos
# the graph
if gvf.getGraph() == 0:
gvf.createGraph()
common.g.add_node(self)
# the environment
self.agOperatingSets = []
self.number = number
self.agType = agType
self.numOfWorkers = 0 # never use it directly to make calculations
self.profit = 0
self.plannedProduction = 0
self.soldProduction = 0
self.revenue = 0
self.consumption = 0
self.consumptionQuantity=0
self.employed = False
self.extraCostsResidualDuration = 0
self.profitStrategyReverseAfterN=0
self.priceSwitchIfProfitFalls=""
if agType == 'workers': #useful in initial creation
common.orderedListOfNodes.append(self)
# use to keep the order
# in output (ex. adjacency matrix)
# colors at http://www.w3schools.com/html/html_colornames.asp
gvf.colors[self] = "OrangeRed"
self.employed = False
self.workTroubles = 0
self.unspentConsumptionCapability = 0
self.jump = 0
if agType == 'entrepreneurs': #useful in initial creation
common.orderedListOfNodes.append(self)
# use to keep the order
# in output (ex. adjacency matrix)
# colors at http://www.w3schools.com/html/html_colornames.asp
gvf.colors[self] = "LawnGreen"
self.employed = True
self.plannedProduction = -100 # not used in plots if -100
self.hasTroubles = 0
self.unspentConsumptionCapability = 0
self.jump = 0
self.myWorldState = myWorldState
self.agType = agType
# the agents
if common.verbose:
print("agent of type", self.agType,
"#", self.number, "has been created at", xPos, ",", yPos)
gvf.pos[self] = (xPos, yPos)
if common.nodeNumbersInGraph:
common.g_labels[self] = str(number)
# to be used to clone (if any)
self.xPos = xPos
self.yPos = yPos
# price memory
self.buyPrice = -1000
self.sellPrice = 1000
self.sellPriceDefined=False
# consumption planning for the current cycle
# if the planning has been made, the variable contains
# the number of the cycle
self.consumptionPlanningInCycleNumber = -1
# status to be used in actOnMarketPlace acting as a buyer
# 0 means never used
# 1 if previous action was a successful buy attempt
# -1 if previous action was an unsuccessful buy attempt
self.statusB = 0
# status to be used in actOnMarketPlace acting as a seller
# 0 means never used
# 1 if previous action was a successful sell attempt
# -1 if previous action was an unsuccessful sell attempt
self.statusS = 0
# talk
def talk(self):
print(self.agType, self.number)
# reset values, redefining the method of agTools.py in $$slapp$$
def setNewCycleValues(self):
# the if is to save time, given that the order is arriving to
# all the agents (in principle, to reset local variables)
if not common.agent1existing:
print("At least one of the agents has to have number==1")
print("Missing that agent, all the agents are resetting common values")
if self.number == 1 or not common.agent1existing:
# introduced with V6
# V6 reset block starts hene
# this part is specific of the first hayekian cycle
# where it replaces the lack of a previous value in
# quantity
# here, if possible, we use the price at t-2
if common.startHayekianMarket > 1:
if common.cycle == common.startHayekianMarket:
if len(common.ts_df.price.values) == 1:
previuosPrice = common.ts_df.price.values[-1] # t=2
if len(common.ts_df.price.values) > 1:
previuosPrice = common.ts_df.price.values[-2] # t>2
# the code above can act only if t>1
if common.cycle > 1: # if == 1 do nothing
# makeProductionPlan acts
# establishing directly
# self.plannedProduction and the total
# common.totalPlannedProduction
common.totalConsumptionInQuantityInPrevious_TimeStep = \
common.totalPlannedConsumptionInValueInA_TimeStep \
/ previuosPrice
# not in case common.cycle == common.startHayekianMarket == 1
elif common.cycle > common.startHayekianMarket:
common.totalConsumptionInQuantityInPrevious2_TimeStep= \
common.totalConsumptionInQuantityInPrevious1_TimeStep # init. in common
common.totalConsumptionInQuantityInPrevious1_TimeStep = \
common.totalConsumptionInQuantityInA_TimeStep
if common.cycle==common.startHayekianMarket+1:
common.totalConsumptionInQuantityInPrevious_TimeStep = \
common.totalConsumptionInQuantityInPrevious1_TimeStep
if common.cycle > common.startHayekianMarket+1:
common.totalConsumptionInQuantityInPrevious_TimeStep = \
common.Q*common.totalConsumptionInQuantityInPrevious1_TimeStep +\
(1-common.Q)*common.totalConsumptionInQuantityInPrevious2_TimeStep
# !!!! here we can use also delayed values, look at !!!! in
# notesOnHayekianTransformation.md
common.totalConsumptionInQuantityInA_TimeStep = 0
# list of all the transaction prices in a cycle of the
# hayekian market
common.hayekianMarketTransactionPriceList_inACycle=[]
# v6 reset block ends here
common.totalProductionInA_TimeStep = 0
common.totalPlannedConsumptionInValueInA_TimeStep = 0
common.totalProfit = 0
common.totalPlannedProduction = 0
# ratio sellers/buyers
common.ratioSellersBuyersAlreadySet=False
# troubles related idividual variables
if self.agType == "entrepreneurs":
self.hasTroubles = 0
if self.agType == "workers":
self.workTroubles = 0
# hireIfProfit
def hireIfProfit(self):
# workers do not hire
if self.agType == "workers":
return
if self.profit <= common.hiringThreshold:
return
tmpList = []
for ag in self.agentList:
if ag != self:
if ag.agType == "workers" and not ag.employed:
tmpList.append(ag)
if len(tmpList) > 0:
hired = tmpList[randint(0, len(tmpList) - 1)]
hired.employed = True
gvf.colors[hired] = "Aqua"
gvf.createEdge(self, hired) # self, here, is the hiring firm
# count edges (workers) of the firm, after hiring (the values is
# recorded, but not used directly)
self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self)
# nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through once.
print("entrepreneur", self.number, "has",
self.numOfWorkers, "edge/s after hiring")
def hireFireWithProduction(self):
# workers do not hire/fire
if self.agType == "workers":
return
# to decide to hire/fire we need to know the number of employees
# the value is calcutated on the fly, to be sure of accounting for
# modifications coming from outside
# (nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through once.)
laborForce0 = gvf.nx.degree(common.g, nbunch=self) + \
1 # +1 to account for the entrepreneur herself
# required labor force
laborForceRequired = int(
self.plannedProduction / common.laborProductivity)
#
# countUnemployed=0
# for ag in self.agentList:
# if not ag.employed: countUnemployed+=1
# print "I'm entrepreneur %d laborForce %d and required %d unemployed are %d" %\
#(self.number, laborForce0, laborForceRequired, countUnemployed)
# no action
if laborForce0 == laborForceRequired:
return
# hire
if laborForce0 < laborForceRequired:
n = laborForceRequired - laborForce0
tmpList = []
for ag in self.agentList:
if ag != self:
if ag.agType == "workers" and not ag.employed:
tmpList.append(ag)
if len(tmpList) > 0:
k = min(n, len(tmpList))
shuffle(tmpList)
for i in range(k):
hired = tmpList[i]
hired.employed = True
gvf.colors[hired] = "Aqua"
gvf.createEdge(self, hired)
# self, here, is the hiring firm
# count edges (workers) of the firm, after hiring (the values is
# recorded, but not used directly)
self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self)
# nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through
# once.
print(
"entrepreneur",
self.number,
"is applying prod. plan and has",
self.numOfWorkers,
"edge/s after hiring")
# fire
if laborForce0 > laborForceRequired:
n = laborForce0 - laborForceRequired
# the list of the employees of the firm
#entrepreneurWorkers = gvf.nx.neighbors(common.g, self) with nx 2.0
entrepreneurWorkers = list(common.g.neighbors(self))
# print "entrepreneur", self.number, "could fire",
# entrepreneurWorkers
# the list returnes by nx is unstable as order
entrepreneurWorkers = mySort(entrepreneurWorkers)
if len(entrepreneurWorkers) > 0: # has to be, but ...
shuffle(entrepreneurWorkers)
for i in range(n):
fired = entrepreneurWorkers[i]
gvf.colors[fired] = "OrangeRed"
fired.employed = False
# common.g_edge_labels.pop((self,fired)) no labels in edges
common.g.remove_edge(self, fired)
# count edges (workers) after firing (recorded, but not used
# directly)
self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self)
# nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through
# once.
print(
"entrepreneur",
self.number,
"is applying prod. plan and has",
self.numOfWorkers,
"edge/s after firing")
# fireIfProfit
def fireIfProfit(self):
# workers do not fire
if self.agType == "workers":
return
if self.profit >= common.firingThreshold:
return
# the list of the employees of the firm
#entrepreneurWorkers = gvf.nx.neighbors(common.g, self) with nx 2.0
entrepreneurWorkers = list(common.g.neighbors(self))
# print "entrepreneur", self.number, "could fire", entrepreneurWorkers
# the list returnes by nx is unstable as order
entrepreneurWorkers = mySort(entrepreneurWorkers)
if len(entrepreneurWorkers) > 0:
fired = entrepreneurWorkers[randint(
0, len(entrepreneurWorkers) - 1)]
gvf.colors[fired] = "OrangeRed"
fired.employed = False
# common.g_edge_labels.pop((self,fired)) no label in edges
common.g.remove_edge(self, fired)
# count edges (workers) after firing (recorded, but not used
# directly)
self.numOfWorkers = gvf.nx.degree(common.g, nbunch=self)
# nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through
# once.
print("entrepreneur", self.number, "has",
self.numOfWorkers, "edge/s after firing")
# produce
def produce(self):
# this is an entrepreneur action
if self.agType == "workers":
return
# to produce we need to know the number of employees
# the value is calcutated on the fly, to be sure of accounting for
# modifications coming from outside
# (nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through once.)
laborForce = gvf.nx.degree(common.g, nbunch=self) + \
1 # +1 to account for the entrepreneur herself
print("I'm entrepreneur", self.number, "my laborforce is", laborForce)
# productivity is set to 1 in the benginning from common space
self.production = common.laborProductivity * \
laborForce
# totalProductionInA_TimeStep
common.totalProductionInA_TimeStep += self.production
# having a copy, that is update after each agent's action
common.totalProductionInPrevious_TimeStep = common.totalProductionInA_TimeStep
# produce
def produceV5(self):
# this is an entrepreneur action
if self.agType == "workers":
return
# to produce we need to know the number of employees
# the value is calcutated on the fly, to be sure of accounting for
# modifications coming from outside
# (nbunch : iterable container, optional (default=all nodes)
# A container of nodes. The container will be iterated through once.)
laborForce = gvf.nx.degree(common.g, nbunch=self) + \
1 # +1 to account for the entrepreneur herself
print("I'm entrepreneur", self.number, "my laborforce is", laborForce)
# productivity is set to 1 in the benginning from common space
self.production = common.laborProductivity * \
laborForce
# print "I'm entrepreneur",self.number,"production before correction is",\
# self.production
# correction for work troubles, if any
# self.hasTroubles is 0 if no troubles
self.production *= (1. - self.hasTroubles)
# print "I'm entrepreneur",self.number,"production after correction is",\
# self.production
# totalProductionInA_TimeStep
common.totalProductionInA_TimeStep += self.production
# having a copy, that is update after each agent's action
common.totalProductionInPrevious_TimeStep = common.totalProductionInA_TimeStep
# makeProductionPlan
def makeProductionPlan(self):
# this is an entrepreneur action
if self.agType == "workers":
return
if common.projectVersion >= "3" and common.cycle == 1:
nEntrepreneurs = 0
for ag in self.agentList:
if ag.agType == "entrepreneurs":
nEntrepreneurs += 1
# print nEntrepreneurs
nWorkersPlus_nEntrepreneurs = len(self.agentList)
# print nWorkersPlus_nEntrepreneurs
common.nu = (
common.rho * nWorkersPlus_nEntrepreneurs) / nEntrepreneurs
# print common.rho, common.nu
if (common.projectVersion >= "3" and common.cycle == 1) or \
common.projectVersion < "3":
self.plannedProduction = npr.poisson(
common.nu, 1)[0] # 1 is the number
# of element of the returned matrix (vector)
# print self.plannedProduction
common.totalPlannedProduction += self.plannedProduction
# print "entrepreneur", self.number, "plan", self.plannedProduction,\
# "total", common.totalPlannedProduction
# adaptProductionPlan
def adaptProductionPlan(self):
if common.cycle > 1:
nEntrepreneurs = 0
for ag in self.agentList:
if ag.agType == "entrepreneurs":
nEntrepreneurs += 1
# previous period price
#print ("++++++++++++++++++++++", common.ts_df.price.values[-1])
#print ("&&&&&&&&&&&&&&&&&&&&&&",len(common.ts_df.price.values))
if len(common.ts_df.price.values) == 1:
previuosPrice = common.ts_df.price.values[-1] # t=2
if len(common.ts_df.price.values) > 1:
previuosPrice = common.ts_df.price.values[-2] # t>2
# NB adapt acts from t>1
self.plannedProduction = (common.totalDemandInPrevious_TimeStep /
previuosPrice) \
/ nEntrepreneurs
#self.plannedProduction += common.mg.myGauss(0,self.plannedProduction/10)
shock = uniform(
-common.randomComponentOfPlannedProduction,
common.randomComponentOfPlannedProduction)
if shock >= 0:
self.plannedProduction *= (1. + shock)
if shock < 0:
shock *= -1.
self.plannedProduction /= (1. + shock)
# print self.number, self.plannedProduction
common.totalPlannedProduction += self.plannedProduction
# print "entrepreneur", self.number, "plan", self.plannedProduction,\
# "total", common.totalPlannedProduction
# adaptProductionPlanV6
def adaptProductionPlanV6(self):
# pre hayekian period
if common.cycle > 1 and common.cycle < common.startHayekianMarket:
# count of the entrepreneur number
nEntrepreneurs = 0
for ag in self.agentList:
if ag.agType == "entrepreneurs":
nEntrepreneurs += 1
# with the scheme of prices until V.5c_fd
if len(common.ts_df.price.values) == 1:
previuosPrice = common.ts_df.price.values[-1] # t=2
if len(common.ts_df.price.values) > 1:
previuosPrice = common.ts_df.price.values[-2] # t>2
# NB adapt acts from t>1
self.plannedProduction = (common.totalDemandInPrevious_TimeStep /
previuosPrice) \
/ nEntrepreneurs
shock = uniform(
-common.randomComponentOfPlannedProduction,
common.randomComponentOfPlannedProduction)
if shock >= 0:
self.plannedProduction *= (1. + shock)
if shock < 0:
shock *= -1.
self.plannedProduction /= (1. + shock)
# print self.number, self.plannedProduction
common.totalPlannedProduction += self.plannedProduction
# print "entrepreneur", self.number, "plan", self.plannedProduction,\
# "total", common.totalPlannedProduction
# hayekian period
if common.cycle >1 and common.cycle >= common.startHayekianMarket:
#the case common.cycle==1, with common.startHayekianMarket==1, is
#absorbed by makeProductionPlan
nEntrepreneurs = 0
for ag in self.agentList:
if ag.agType == "entrepreneurs":
nEntrepreneurs += 1
self.plannedProduction = \
common.totalConsumptionInQuantityInPrevious_TimeStep \
/ nEntrepreneurs
shock = uniform(
-common.randomComponentOfPlannedProduction,
common.randomComponentOfPlannedProduction)
if shock >= 0:
self.plannedProduction *= (1. + shock)
if shock < 0:
shock *= -1.
self.plannedProduction /= (1. + shock)
# print self.number, self.plannedProduction
common.totalPlannedProduction += self.plannedProduction
# print "entrepreneur", self.number, "plan", self.plannedProduction,\
# "total", common.totalPlannedProduction
# to record sold production and revenue in hayekian phase
self.soldProduction=0
self.revenue=0
# set initial sell and buy prices in hayekian market
def setInitialPricesHM(self):
# 1 -----------------------------------------
if common.cycle >= common.startHayekianMarket:
if not common.ratioSellersBuyersAlreadySet:
nEntrepreneurs = 0
for ag in self.agentList:
if ag.agType == "entrepreneurs":
nEntrepreneurs += 1
nSellers=nEntrepreneurs
nBuyers=len(self.agentList)
common.ratioSellersBuyersAlreadySet=True
common.ratioSellersBuyers=nSellers/nBuyers
print("\nRatio sellers/buyers =",common.ratioSellersBuyers,"\n")
# in setNewCycleValues common.ratioSellersBuyersAlreadySet=False
# at the beginning of each cycle
# 2 -----------------------------------------
if common.cycle == common.startHayekianMarket and \
not common.priceWarmingDone:
# setting the basic price uniquely before the first hayekian cycle
common.sellPrice=1000
common.buyPrice=-1000
if common.startHayekianMarket>1:
if len(common.ts_df.price.values) == 1:
common.buyPrice = common.sellPrice = \
common.ts_df.price.values[-1] # the last price
#print("Ag.", self.number,"buying at", self.buyPrice,
# "selling at",self.sellPrice)
# NB the code above can act only if t>1
if len(common.ts_df.price.values) > 1:
common.buyPrice = common.sellPrice = \
common.ts_df.price.values[-2] # the second last price
#print("Ag.", self.number,"buying at", self.buyPrice,
# "selling at",self.sellPrice)
# NB the code above can act only if t>2
# NB NB we set the sellPrice also for workers but we do not
# use it
# when a worker becomes an entreprenuer she copies the
# sell price of the firm she is coming from
else: # case t==1 being common.startHayekianMarket==1
# look at the equilibrium price that would have been created
# at t==1 in the non-hayekian execution
# in the common.startHayekianMarket == 1 case, when
# actOnMaketPlace is activated
# we already have
# common.totalPlannedConsumptionInValueInA_TimeStep and
# common.totalProductionInA_TimeStep
# so, we can calculate
common.buyPrice = common.sellPrice = \
common.totalPlannedConsumptionInValueInA_TimeStep \
/ common.totalProductionInA_TimeStep
# outside WorldState setMarketPriceV3 method, to avoid here
# random shocks
# NB NB we set the sellPrice also for workers but we do not
# use it
# when a worker becomes an entreprenuer she copies the
# sell price of the firm she is coming from
#startingHayekianCommonPrice
print("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("starting hayekian common price",common.buyPrice)
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
common.priceWarmingDone = True
# 3 -----------------------------------------
# individual starting prices
if common.cycle == common.startHayekianMarket:
#starting sell price
self.sellPrice = \
applyRationallyTheRateOfChange(common.sellPrice,\
uniform(-common.initShift*common.initShock, \
(1-common.initShift)*common.initShock))
if self.agType=="entrepreneurs":
print("entrepreneur", self.number, "has initial sell price",\
self.sellPrice)
self.sellPriceDefined=True
# starting individual buy price
self.buyPrice = \
applyRationallyTheRateOfChange(common.buyPrice,\
uniform((common.initShift-1)*common.initShock, \
common.initShift*common.initShock))
# modify a specific sell price with a jump on the side of the up
# corrections, in full hayekian market
# NB we are at the end of each cycle
def nextSellPriceJumpFHM(self):
if self.agType != "entrepreneurs": return
if common.hParadigm=="quasi": return
if common.pJump != -1 and npr.uniform(0,1)<=common.pJump:
if self.jump == 0:
self.jump=common.jump
self.sellPrice *= 1 + self.jump
print("entrepreur # ", self.number, \
"raises the sell price with a jump")
else:
self.sellPrice /= 1 + self.jump
self.jump=0
print("entrepreur # ", self.number, \
"reduces the sell price with a jump back")
# modify sell prices in quasi hayekian market
# NB we are at the end of each cycle
def nextSellPricesQHM(self):
if self.agType != "entrepreneurs": return
if common.hParadigm=="full": return
# hayekian period, "quasi" hayekian paradigm
# i) considering relative unsold quantity
if common.hParadigm=="quasi" and common.quasiHchoice=="unsold":
if common.cycle >= common.startHayekianMarket:
oldP=self.sellPrice
if common.cycle >1 and \
common.entrepreneursMindIfPlannedProductionFalls and \
common.ts_df.iloc[-1, 3] / common.totalPlannedProduction - 1 >= \
common.thresholdToDecreaseThePriceIfTotalPlannedPFalls:
# indexing Python style, pos. -1 is the last one
self.sellPrice = applyRationallyTheRateOfChange(self.sellPrice,\
uniform(common.decreasingRateRange, 0))
print(("end of t = %d entrepreneur %d initial production"+\
" %.2f sold %.3f \nold price %.3f new price %.3f as "+\
" total plannedProduction falls") %\
(common.cycle,self.number,self.production,\
self.soldProduction,oldP,self.sellPrice))
else:
if self.soldProduction/self.production <= common.soldThreshold1:
self.sellPrice = applyRationallyTheRateOfChange(self.sellPrice,\
uniform(common.decreasingRateRange, 0))
if self.production/self.production>=common.soldThreshold2:
self.sellPrice = applyRationallyTheRateOfChange(self.sellPrice,\
uniform(0, common.increasingRateRange))
print(("end of t = %d entrepreneur %d initial production"+\
" %.2f sold %.3f \nold price %.3f new price %.3f") %\
(common.cycle,self.number,self.production,\
self.soldProduction,oldP,self.sellPrice))
return
# ii) considering randomUp
if common.hParadigm=="quasi" and common.quasiHchoice=="randomUp":
if common.pJump != -1 and npr.uniform(0,1)<=common.pJump:
if self.jump == 0:
self.jump=common.jump
self.sellPrice *= 1 + self.jump
print("entrepreur # ", self.number, \
"raises the sell price with a jump")
else:
self.sellPrice /= 1 + self.jump
self.jump=0
print("entrepreur # ", self.number, \
"reduces the sell price with a jump back")
return
# iii) consideirng profit falls to act on price
if common.hParadigm=="quasi" and common.quasiHchoice=="profit":
if common.cycle >= common.startHayekianMarket:
if self.profitStrategyReverseAfterN==0:
if common.priceSwitchIfProfitFalls=="raise":
if npr.uniform(0,1)<=0.6:
self.priceSwitchIfProfitFalls="raise"
else:
self.priceSwitchIfProfitFalls="lower"
if common.priceSwitchIfProfitFalls=="lower":
if npr.uniform(0,1)<=0.4:
self.priceSwitchIfProfitFalls="raise"
else:
self.priceSwitchIfProfitFalls="lower"
if common.pJump != -1 and self.profit <0 and \
npr.uniform(0,1)<=common.pJump:
if self.priceSwitchIfProfitFalls=="raise":
self.sellPrice *= 1 + common.jump
print("entrepreur # ", self.number, \
"with profit<0, is raising the sell price")
self.profitStrategyReverseAfterN=\
common.profitStrategyReverseAfterN
# 0 means: acting again always possible
# a value > the number of cycles means:
# acting again never possible
if self.priceSwitchIfProfitFalls=="lower":
self.sellPrice /= 1 + common.jump
print("entrepreur # ", self.number, \
"with profit<0, is lowering the sell price")
self.profitStrategyReverseAfterN=\
common.profitStrategyReverseAfterN
else:
self.profitStrategyReverseAfterN-=1
if self.profitStrategyReverseAfterN==0:
if self.priceSwitchIfProfitFalls=="raise":
self.sellPrice /= 1 + common.jump
print("entrepreur # ", self.number, \
"lowering back the sell price")
if self.priceSwitchIfProfitFalls=="lower":
self.sellPrice *= 1 + common.jump
print("entrepreur # ", self.number, \
"raising back the sell price")
return
# here in error
print("Using the 'quasi' option in hayekian market:\n",\
"the",common.quasiHchoice, "value is not one of the\n",
"valid option (unsold, randomUp, profit)")
os.sys.exit(1)
# all acting as consumers on the market place
def actOnMarketPlace(self):
if common.cycle < common.startHayekianMarket: return
# in each sub step, we show residual consumption and production; the
# code operates on different agents, but consistently (in each call,
# the elaboration jumps from an instance of agent to another one)
if common.checkResConsUnsoldProd:
#print(self.number)
if common.withinASubstep:
common.internalSubStepAgentCounter+=1
#print('*',common.internalSubStepAgentCounter)
if common.internalSubStepAgentCounter==len(self.agentList):
common.withinASubstep=False
else: # not withinASubstep
common.withinASubstep=True
common.internalSubStepAgentCounter=1
if common.currentCycle != common.cycle:
common.currentCycle = common.cycle
common.subStepCounter=0
common.readySellerList=False
print()
common.subStepCounter+=1
residualConsumptionCapabilityInValue=0
residualUnsoldProduction=0
for anAgent in self.agentList:
residualConsumptionCapabilityInValue += anAgent.consumption
if anAgent.agType=="entrepreneurs":
residualUnsoldProduction+= \
anAgent.production - anAgent.soldProduction
print(\
"subc. %2d.%3d starts with cons. capab. (v) %.1f and uns. p. (q) %.1f"\
% (common.cycle, common.subStepCounter, residualConsumptionCapabilityInValue,\
residualUnsoldProduction))
try: common.wr.writerow
except:
print("The file firstStepOutputInHayekianMarket.csv was not"+\
" created in mActions.py")
os.sys.exit(1)
# first call in each cycle, preparing action (only once per cycle)
#if self.currentCycle != common.cycle:
if not common.readySellerList:
#self.currentCycle = common.cycle
common.readySellerList=True
# we check that the planning of the consumption has been
# made for the current cycle
if self.consumptionPlanningInCycleNumber != common.cycle:
print('Attempt of using actOnMarketPlace method before'+\
' consumption planning')
os.sys.exit(1) # to stop the execution, in the calling module
# we have multiple except, with 'SystemExit' case
# create a temporary list of sellers, starting each step (cycle)
common.sellerList=[]
for anAg in self.agentList:
if anAg.getType() == "entrepreneurs":
if not anAg.sellPriceDefined:
print("Inconsistent situation, an active selles"\
+" has no sell price defined.")
os.sys.exit(1)
else: common.sellerList.append(anAg)
# acting (NB self.consumption comes from planConsumptionInValueV6)
# if buying action is possible
#print("cycle",common.cycle,"ag",self.number,"cons val",self.consumption)
if self.consumption > 0:
if common.sellerList != []:
# chose a seller
mySeller=common.sellerList[randint(0,len(common.sellerList)-1)]
sellerQ=mySeller.production - mySeller.soldProduction
if sellerQ>0:
# try a deal
if self.buyPrice < mySeller.sellPrice:
self.statusB=mySeller.statusS=-1
if self.buyPrice >= mySeller.sellPrice:
self.statusB=mySeller.statusS= 1
#print(common.cycle,"entr.",mySeller.number,\
# mySeller.production,mySeller.soldProduction,\
# mySeller.sellPrice)
# NB production can be < plannedProduction due to lack of workers
# consumption in value cannot exceed self.maxConsumptionInAStep
buyerQ=min(self.consumption/mySeller.sellPrice, sellerQ,\
self.maxConsumptionInAStep/mySeller.sellPrice)
mySeller.soldProduction+=buyerQ
mySeller.revenue+=buyerQ*mySeller.sellPrice
self.consumption-=buyerQ*mySeller.sellPrice
self.unspentConsumptionCapability=self.consumption
#print("cycle",common.cycle,"ag",self.number,"deal: cons val",\
# buyerQ*mySeller.sellPrice,"price",mySeller.sellPrice)
# saving the price of the transaction
common.hayekianMarketTransactionPriceList_inACycle.\
append(mySeller.sellPrice)
common.totalConsumptionInQuantityInA_TimeStep += buyerQ
#ouput - seller has no goods to sell
elif common.cycle==common.startHayekianMarket:
common.wr.writerow\
(["nogoods", "buy", numpy.nan, self.consumption, self.number,\
"sell", numpy.nan,mySeller.number])
#output - deal vs. nodeal
if common.cycle==common.startHayekianMarket:
if mySeller.statusS==1:
common.wr.writerow\
(["deal", "buy", self.buyPrice, self.consumption, self.number,\
"sell", mySeller.sellPrice,mySeller.number])
if mySeller.statusS==-1 and mySeller.sellPriceDefined:
common.wr.writerow\
(["nodeal", "buy", self.buyPrice, self.consumption, self.number,\
"sell", mySeller.sellPrice,mySeller.number])
# correct running prices
# if the status is != 0 the agent has already been acting
if self.statusB == 1: # buyer case (statusB 1, successful buy attempt,
# acting mostly to decrease the reservation price)
self.buyPrice = applyRationallyTheRateOfChange(self.buyPrice,\
uniform(-(1-common.runningShiftB)* \
common.runningShockB, \
common.runningShiftB* \
common.runningShockB))
if self.statusB == -1: # buyer case (statusB -1, unsuccessful buy attempt,
# acting mostly to increase the reservation price)
self.buyPrice = applyRationallyTheRateOfChange(self.buyPrice,\
uniform(-common.runningShiftB* \
common.runningShockB, \
(1-common.runningShiftB)* \
common.runningShockB))
if mySeller.statusS == 1 and common.hParadigm=="full" or \
(common.hParadigm=="quasi" and \
common.cycle==common.startHayekianMarket):
# seller case (statusS 1, successful sell attempt,
mySeller.sellPrice = applyRationallyTheRateOfChange(mySeller.sellPrice,\
common.ratioSellersBuyers*\
uniform(-common.runningShiftS* \
common.runningShockS,
(1-common.runningShiftS)* \
common.runningShockS))
if mySeller.statusS == -1 and common.hParadigm=="full" or \
(common.hParadigm=="quasi" and \
common.cycle==common.startHayekianMarket):
# seller case (statusS -1, unsuccess. s. attempt,
# acting mostly to decrease the reservation price)
mySeller.sellPrice = applyRationallyTheRateOfChange(mySeller.sellPrice,\
common.ratioSellersBuyers*\
uniform(-(1-common.runningShiftS)* \
common.runningShockS, \
common.runningShiftS* \
common.runningShockS))
#print("ag.", self.number, "new prices", self.buyPrice, mySeller.sellPrice)
# cleaning the situation (redundant)\\
self.statusB=mySeller.statusS=0
#output - common.sellerList==[]
elif common.cycle==common.startHayekianMarket:
common.wr.writerow\
(["nosellers", "buy", self.buyPrice, self.consumption, self.number,\
"sell", numpy.nan,numpy.nan])
#output - self.consumption<=0
elif common.cycle==common.startHayekianMarket:
common.wr.writerow\
(["noconsumption", "buy", numpy.nan, self.consumption, self.number,\
"sell", numpy.nan,numpy.nan])
#output close
if common.cycle==common.startHayekianMarket+1 and not common.closed:
common.csvf.close()
common.closed=True
# calculateProfit V0