forked from a-mcinnes/spatiotemporal-urban-model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
market_dynamics_main.py
1864 lines (1439 loc) · 85.4 KB
/
market_dynamics_main.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
import numpy as np
np.random.seed(69)
import pytz
import time
from datetime import datetime
from matplotlib import cm, pyplot as plt
import matplotlib.markers as mmarkers
from matplotlib.colors import ListedColormap
import matplotlib.gridspec as gridspec
import seaborn as sns
from scipy.ndimage.filters import gaussian_filter
from os.path import dirname, abspath
import os
import sys
import shutil
global dirmain, diroutput # relative directories
dirmain = dirname(abspath(__file__))
diroutput = dirmain + '/data/output/'
from market_dynamics_visualisations import visualisation
"""
Alexander McInnes, Jun 2021
This project is licensed under the GNU General Public License Version 3 - see the LICENSE.txt file for details.
*** NOT TO BE SHARED UNTIL PUBLICATION OF PAPER ***
directory setup:
model > market_dynamics.py (main)
> md_visualisations.py (secondary to plot all results)
> data > output (outputted results of simulation) > sim-ID > households_sim-ID_timestep.txt
> dwellings_sim-ID_timestep.txt
> input (used for visualisations after from output results after simulation completed)
Typical workflow:
1. specify case to run in __name__
2. specify params of case/model in simulate.model_parameters()
3. results output, results visualised/plotted
optional 4. in md_visualisation.py, comment out plots to create, run model
"""
class simtime:
def current():
"""
current() converts current time to format of yearmonthdayhourminutesecond for the ID of simulation.
return: simulation ID final
"""
dtT = datetime.now(pytz.timezone('Australia/Sydney'))
final = [dtT.strftime("%"+str(x)) for x in 'ymdHMS']
final=int(''.join(map(str, final)))
return final
class household:
def __init__(self, N, N_min):
"""
__init__ initialises parameters and dictionaries for which characteristics and preferences are sampled from later.
param N: input number of households
param N_min: absolute minimum number of households
"""
self.N = int(N)
self.N_min = int(N_min)
self.q_bound = {'n_people': np.linspace(1,4,4), 'type I/II': [-1,1]} # bounds for characteristics,
# type I/II is for testing different characteristics of households
self.s_bound = {'s_0': [-1,0], 'classical:modern': [-1, 1], 'large house': [0,1],'s1 preference':[-1,1]} # bounds for preferences
def populate(self):
"""
populate() generates households, their characteristics and their preference strengths for dwelling characteristics.
Array data can be either generated or loaded from previous run.
field self.s: preference vector of households [s_0, ...]
field self.q: characteristic vector of households [q_0, ...]
field self.U: utility of households
field self.p: general household info [household ID, on/off-market flag, occupied dwelling ID, n times transacted]
in saving household array, self.p will contain utility values at end.
"""
q = pop.characteristics(self.N) # household characteristics q
self.s_0 = calcs.price_sens_income_dist() # price sensitivity s_0
self.s_ = pop.preferences(self.N) # preferences s_ is the s' vector in Paper 1. in this code it also contains s_0 for ease
self.q = q # group all the household characteristics
self.s = pop.normalise_prefs(s_0=self.s_0, s_=self.s_) # normalise preference vector s by s_0
if sim.case != 'C':
self.s = self.s_0 # restrict to s0 only
self.U = pop.utilities(self.N) # household utilities U
self.p = pop.general(self.N) # general household info p
def characteristics(self, num):
"""
characteristics(num) generates an N*num size characteristic vector for num households and m+1 characteristics;
characteristics are sampled from initialized dictionary within __init__.
param num: length of characteristic vector to generate, i.e. no. households to generate for
return: concatenated characteristic vector returned, size (m+1)*num
"""
q_0 = np.ones(shape=(num, 1)) # characteristic for clustering
q_1 = np.sort(np.random.choice(self.q_bound['n_people'], size=(num, 1)), axis=0)/4 # number of occupants in each household
q_2 = np.random.choice(self.q_bound['type I/II'], size=(num, 1)) # this is a sample test case characteristic
if sim.case == 'D':
q_3 = np.random.choice(self.q_bound['type I/II'], size=(num, 1)) # this is a sample test case characteristic
q = np.concatenate((q_0, q_3), axis=1) # group all the household characteristics
else:
q = q_0
return np.round(np.array(q, dtype=float), 3)
def preferences(self, num):
"""
preferences(num) generates an N*num size preference vector for num households and m+1 preferences;
preferences are sampled from initialized dictionary within __init__.
param num: length of preference vector to generate, i.e. no. households to generate for
return: concatenated preference vector returned, size (n+1)*num
** Later can instantiate random preferences by different dynamics/distributions.
"""
s_1 = 1 - 2*np.random.random_sample(size=(num, 1)) # random preferences for classical (-1)/modern (+1) dwelling
s_2 = np.sort(np.random.random_sample(size=(num, 1)), axis=0) # random preferences for large house
s_3 = 1 - 2*np.random.random_sample(size=(num, 1)) # random preferences to live near factories vs. sea
s_ = np.concatenate((s_1, s_2), axis=1) # group all the preference strengths
if sim.case == 'C':
s_ = s_3 # preference for dwelling characteristic B1
# s_ = np.concatenate((s_1, s_3), axis=1) # group all the preference strengths
return np.array(s_, dtype=float)
def normalise_prefs(self, **kwargs):
"""
normalise_prefs(s_0, s_) normalises the input strength of preferences s_ as according to |s_0|^2 + s_^2 = 1.
param s_0: price sensitivity of households on range (-1, 0), bounding parameter in normalisation
param s_: vector s'(p) containing relative strengths of preferences for various dwelling features.
return: normalised preference vector s containing [s_0, s_1,... , s_n]
"""
if len(kwargs.items())==2:
for key,val in kwargs.items():
exec('self.'+key + '=val')
elif len(kwargs.items())==1:
for key,val in kwargs.items():
exec('self.'+key + '=val')
self.s_0 = np.array([self.s_n[:,0]]).T
self.s_ = np.array(self.s_n[:,1:])
s_norm = [1-abs(x[0])**2 for x in self.s_0] # normalise the strength of preferences as according to |s_0|^2 + s'^2 = 1
s_sum = [sum(x**2) for x in self.s_] # s_sum (total preferences strength vector) must equal s_norm (for normalisation)
s_new = []
for x in range(len(s_norm)):
s_new.append(self.s_[x]*np.sqrt(s_norm[x]/s_sum[x]))
s = np.concatenate((np.array(self.s_0), s_new), axis=1) # join s_1,2,3.. to s_0 array
s = np.nan_to_num(s, nan=0)
return np.round(np.array(s, dtype=float), 3)
def utilities(self, num):
"""
utilities(num) generates an empty num*1 size array to store utilities of households.
param num: length of utility vector to generate, i.e. no. households to generate for
return: empty utility vector U size num*1
"""
U = np.zeros(shape=(num, 1), dtype=object)
return U
def general(self, num):
"""
general(num) generates an empty array for storing general information of households.
param num: length of general info vector to generate, i.e. no. households to generate for
return: empty array p size num*4, [household ID, on/off-market flag, occuping dwelling ID, no. transactions]
"""
p_0 = np.linspace(0, num-1, num, dtype=int) # household ID
p_1 = np.ones(shape=(num, 1), dtype=int) # household on-market flag
p_2 = np.zeros(shape=(num, 1), dtype=int) # dwelling occupied by household
p_3 = np.zeros(shape=(num, 1), dtype=int) # no. transactions by household
p = np.concatenate((np.array([p_0]).T, p_1, p_2, p_3), axis=1) # compile all general household information
return p
def assign_dwellings(self):
"""
assign_dwellings() assigns dwellings to initialised population.
Current method: random assignment
Alternatively, could assign by order of increasing wealth of households to dwellings with positive, ascending U0 values.
i.e., poorest household will be assigned a dwelling with positive U0 closest to 0,
2nd poorest to a dwelling with positive U0 & 2nd closest to 0 etc.
"""
""" ASSIGN VIA ORDER OF U0 & s0 -- not used """
# s_mark = self.s[self.p[:,1]>0]
# on_mkt = len(s_mark)
# s_sort = np.array(sorted(enumerate(s_mark[:,0]), key=lambda x:x[1]), dtype=int)[:,0]
# B_sort = np.array(sorted(dwell.r[dwell.r[:,2]>0], key=lambda x:x[2]), dtype=int)[:len(s_sort)]
# B_sort = np.array(dwell.r[dwell.r[:,2]>0], dtype=int)[:len(s_sort)]
# if len(B_sort) != len(s_sort):
# B_sort = np.array(sorted(dwell.r, key=lambda x:x[2]), dtype=int)[:len(s_sort)]
# U = np.array([dwell.r[B_sort[:,0]][:,2] + np.sum(self.s[s_sort] *dwell.B[B_sort[:,0]], axis=1)]).T
# self.U[-on_mkt:] += U #- abs(U)*calcs.fees # assign utility for random dwelling
# self.p[-on_mkt:,1] = 0 # set off-market
# self.p[-on_mkt:,2] = B_sort[:,0] # assign dwelling
# dwell.r[:,1][B_sort[:,0]] = 0 # set dwelling off-market
"""#################################################"""
""" ASSIGN VIA RANDOM """
on_mkt = len(self.s[self.p[:,1]>0])
r_mark = np.array(dwell.r[np.where(dwell.r[:,1]!=0)][:,0], dtype=int)
dwell_id = np.random.choice(r_mark, on_mkt, replace=False)
self.p[-on_mkt:,2] = dwell_id # assign dwelling
self.p[-on_mkt:,1] = 0 # set household off-market
dwell.r[dwell_id,1] = 0 # set dwelling off-market
"""####################################################"""
""" update U & B0 for all households following assignment """
# household data
p = self.p
U = self.U
q = self.q
s = self.s
# corresponding dwelling data for each household occupying it
r = dwell.r[p[:,2]]
U0 = r[:,2]
r_coord = dwell.r_coord[p[:,2]]
B = dwell.B[p[:,2]]
U_new = U0 + np.sum(s*B, axis=1) # updated utility for their current dwelling
# calculate euclidean distance between all households
loc = dwell.r_coord[p[:,2], 0:2]
dwell_1 = np.reshape(np.repeat(loc, len(loc), axis=1).T, (2,-1)).T
dwell_2 = np.reshape(np.repeat(loc, len(loc), axis=0).T, (2,-1)).T
euclids = np.reshape(np.linalg.norm(dwell_1.T - dwell_2.T, axis=0), (len(loc), -1))
# calculate final term of the utility equation for different types of households.
q = np.array(self.q)
G = sim.G_0*np.exp(-euclids**2/sim.h**2)
U_G = np.sum(np.dot(q, q.T)* G, axis=1) * dwell.price_scale
# temp store utility to assign price B0 to dwelling
tmp_U = np.round(np.array([U_new + U_G], dtype=float).T, 3)
# recalculate B0 from U' = U - s0*B0
if np.shape(dwell.B[p[:,2]])[1] == 1:
dB = tmp_U - self.s*dwell.B[p[:,2]]
else:
dB = tmp_U - np.array([self.s[:,0]*dwell.B[p[:,2], 0]]).T
# assign price B0 to occupied dwellings
dwell.B[p[:,2],0] = np.round(np.array(dB.T, dtype=float), 3)
# recalculate household utility for assigned price
U_new = U0 + np.sum(s*dwell.B[p[:,2]], axis=1)
self.U = np.round(np.array([U_new + U_G], dtype=float).T, 3)
def perturb(self):
"""
perturb() will alter preferences and/or characteristics of households.
Can include age of household/shift preferences with age.
alter household preferences by eq. 17: rotate s' vector in n-dimensional subspace by taking mean of preferences of
households within local neighbourhood.
s = -alpha * [s(p,t) - <s(p',t)>] * ∆t
"""
s = pop.s
if np.shape(s)[1] >1:
p = pop.p
# calculate euclidean distance between all households
loc = dwell.r_coord[p[:,2], 0:2]
dwell_1 = np.reshape(np.repeat(loc, len(loc), axis=1).T, (2,-1)).T
dwell_2 = np.reshape(np.repeat(loc, len(loc), axis=0).T, (2,-1)).T
euclids = np.reshape(np.linalg.norm(dwell_1.T - dwell_2.T, axis=0), (len(loc), -1))
# carry out eq. 17, iterate through households
s_n = []
for h in range(len(p)):
d = euclids[h] # distance of other households from household h
m = np.where(d<=sim.h)[0] # households within local neighbourhood of h
s_m = np.mean(s[m],axis=0) # take mean of local preferences
s_h = -sim.alpha*(s[h] - s_m) # calculate incremental change to preferences via eq. 17
s_tmp = s[h] + s_h # add incremental change to their preferences
s_tmp[0] = s[h,0] # reset first element to their static income sensitivity
s_n.append(s_tmp)
pop.s = pop.normalise_prefs(s_n=np.array(s_n)) # normalise and reassign perturbed preferences
# re-calculate income distribution and wealth
# household.mng_wealth(self)
def mng_wealth(self):
"""
mng_wealth() will shift income, emulate wage growth, recalculate price sensitivity s_0
"""
# in early versions maybe just upshift income with age (generally) and lower price sensitivity,
# but negatively perturb the price sensitivity of random households so that the income distribution remains relatively static.
# i.e. can fluctuate slightly as noise but not correlated with time.
# as people are removed, new households with same price sensitivity or higher price sensitivity such that static distribution is maintained
#this will also include wage/wealth growth etc. Calculate current wealth from a pre-defined networth as a function of age
pass
def evolve(self):
"""
evolve() contains methods relating to manipulation of the total number of households
i.e. altering demand via increasing/decreasing number of households.
Emulates population growth/decline (birth, death, marriage, immigration, emmigrate, moving out etc.)
Method for increasing calls functions used in the populate() function during initialisation of the households class (pop),
creates 'new' number of households.
Method for decreasing deletes 'demo' number of random households, setting their occupied dwellings on-market.
Both methods re-adjust the household IDs to correspond with the total number of households in the model.
"""
""" HOUSEHOLD CREATION """
new = int(sim.eps*self.N) # no. households to create
# check for upper bound on creation
if self.N + new <= dwell.M:
pass
else:
new = dwell.M - self.N
if new > 0 and sim.step/4>40: # threshold to create households, if any & after time period t
if hasattr(sim, 'new_min') == False:
sim.new_min = sim.step # timestep at which household creation begins
if self.N + new <= dwell.M:
pop.growth(new)
elif sim.eps!=0 and new == 0 and sim.step/4>40 and hasattr(sim, 'new_max') == False:
sim.new_max = sim.step # timestep at which household creation ceases
""" HOUSEHOLD DESTRUCTION """
demo = int(sim.rho*self.N) # no. households to destroy
# check for lower bound on destruction
if self.N - demo > self.N_min:
pass
else:
demo = self.N - self.N_min
if demo > 0 and sim.step/4>40:
if hasattr(sim, 'new_min') == False:
sim.new_min = sim.step # timestep at which household creation begins
if self.N -demo >= self.N_min:
pop.destroy(demo)
elif sim.rho!=0 and new == 0 and sim.step/4>40 and hasattr(sim, 'new_max') == False:
sim.new_max = sim.step # timestep at which household creation ceases
def growth(self, new):
"""
growth() generates new housholds to add to existing households. Characteristics, preferences, and all other info
is generated as per the populate() function.
param new: input number of households to create
"""
dq = pop.characteristics(new)
ds_0 = calcs.sample_s0_income_dist(new)
ds_ = pop.preferences(new)
ds = pop.normalise_prefs(s_0=ds_0, s_=ds_)
dU = pop.utilities(new)
dp = pop.general(new)
dp[:,0] += np.shape(self.p)[0]
# check shape of s vector and q vector
if np.shape(self.s)[1] == 1:
ds = np.array([ds[:,0]], dtype=float).T
if np.shape(self.q)[1] == 1:
dq = np.array([dq[:,0]], dtype=float).T
# concatenate all new households with existing
self.s = np.concatenate((self.s, ds), axis=0)
self.U = np.concatenate((self.U, dU), axis=0)
self.p = np.concatenate((self.p, dp), axis=0)
self.q = np.concatenate((self.q, dq), axis=0)
# un_occ_dwell = dwell.r[dwell.r[:,1]!=0]
# if np.size(un_occ_dwell) >0:
pop.assign_dwellings() # assign new households to dwellings
# else: # this else statement is for if there are no available dwellings for households
""" ADJUST THIS IF REQUIRED - capacity for households to remain 'dwelling-less' i.e. homeless"""
# self.p[-new:,1] = 1 # set leave household on-market
# self.p[-new:,2] = -1 # set household occupied dwelling to -1
self.N = len(self.U) # re-assign total number of households to pop.N
def destroy(self, demo):
"""
destroy() removes a number of households from the model, setting previously occupied dwellings on-market.
param demo: input number of households to remove
"""
del_ind = np.random.choice(range(self.N), size=(demo,1), replace=False) # index of dwellings to delete
dwells = self.p[del_ind,2] # dwellings occupied by households to delete
dwell.r[dwells,1] = 1 # set occupied dwellings to on-market
# delete all indices of households to be destroyed
self.s = np.delete(self.s, del_ind, axis=0)
self.U = np.delete(self.U, del_ind, axis=0)
self.p = np.delete(self.p, del_ind, axis=0)
self.q = np.delete(self.q, del_ind, axis=0)
self.p[:,0] = np.linspace(0,len(self.s)-1, len(self.s)) # re-number households after deletion
self.N = len(self.U) # re-assign total number of households to pop.N
class dwelling:
def __init__(self, M, R, u0_max, u0_wid, price_scale, M_min, M_max, cent):
"""
__init__ initialises parameters and dictionaries for which characteristics are sampled from later.
param M: input number of dwellings
param R: linear size of model
param u0_max: maximum U0 value
param u0_wid: window size for U0 distribution
param price_scale: self explanatory by name, value to scale model values to; default unity scale
param M_min: min number of dwellings permitted
"""
self.M = int(M)
self.R = R
self.r_coord = np.zeros((1, 2)) # blank coordinate array to be filled during initialisation
self.u0_max = float(u0_max)
self.u0_wid = u0_wid
self.price_scale = price_scale
self.M_min = M_min
self.M_max = M_max
self.cent = cent
self.r_recs =np.array([])
""" establish some dictionaries for later (will search by index of element to find same term to compare
utility of specific characteristics of dwelling) """
# formate for dwelling characteristics, possible to extend
self.style = {'classical:modern': [-1,1]}
def construct(self):
"""
construct() generates dwellings, their location, characteristics and other general information.
Array data can be either generated or loaded from previous run.
field self.B: characteristic vector of dwellings [B_0, ...]
field self.r_coord: spatial location vector of dwellings [x, y, z, ...]
field self.r: general dwelling info [dwelling ID, on/off-market flag, general utility U_0]
"""
self.r_coord = dwell.coordinates(self.M) # coordinates r of dwellings
self.u_0 = dwell.utility_0(self.M) # general utility U_0(r) of dwellings
B = dwell.characteristics(self.M) # characteristic vector B(r) of dwellings
self.B = np.round(np.array(B*self.price_scale, dtype=float), 3)
if sim.case != '999':
self.B = np.array([self.B[:,0]]).T # restrict to B0
r = dwell.general(self.M)
self.r = np.concatenate((r, self.u_0), axis=1) # compile general information of dwelling [ID, on-market flag, U_0]
if sim.case == 'C':
dwell.B1_gen()
def utility_0(self, num):
"""
utility_0(num) generate general utility of dwellings, common to all households.
This function also generates the distribution of the general utility U0 of dwellings.
This method assigns either all null (ones, equivalently negligible) or via a distribution with n central peaks.
Central peaks defined by decimal location of maximal size of model (0.5 is center).
param num: length of general utility vector to generate, i.e. number of dwellings to generate U_0 for
return: general utility vector returned, size 1*num.
"""
centric = np.array(self.cent) * self.R # U0 centricity location
self.centric = centric
if np.size(centric)>0:
u_0 = np.ones(shape=(num,1), dtype=object) * self.price_scale
# remove specified centricity coordinate if it is in coordinate list then move to start
for x, cent in enumerate(centric):
loc = np.where(np.all(self.r_coord==cent, axis=1))[0]
if len(loc) > 0:
self.r_coord = np.delete(self.r_coord, loc, axis=0)
self.r_coord = np.insert(self.r_coord, x, cent, axis=0)
else:
self.r_coord[x] = cent
# check for duplicate coordinates, exit on error if duplicates
uniq = np.unique(self.r_coord, axis=0)
if len(uniq) != self.M:
print("""ERR: len(uniq) != self.M
error in setting U0 centricity -- shutting down""")
exit()
""" down-scale all other utilities with distance from the central point(s) """
# this generates a mapping of coordinates (1/4 integer approx.)
self.incs = self.R*4 + 1
dim = np.linspace(0, self.R, self.incs)
x_map, y_map = np.meshgrid(dim, dim)
u0_map = np.concatenate((np.array([x_map.flatten()]).T, np.array([y_map.flatten()]).T), axis=1)
pos = np.empty(x_map.shape + (2,))
pos[:, :, 0] = x_map
pos[:, :, 1] = y_map
# gaussian shape U0 distribution
euclid_cents = []
for x in range(len(centric)):
euclid_cents.append(np.linalg.norm(u0_map.T - np.array([centric[x]]).T, axis=0))
x = np.min(euclid_cents, axis=0)
u0 = self.u0_max*np.exp(-abs(x**2)/(self.u0_wid**2))
self.U0_store = np.reshape(u0, (self.incs,-1))
r_coord_ref = np.array(np.round(self.r_coord * 4), dtype=int) # cell reference for U0_map for coords
for x in range(len(u_0)):
u_0[x] = u_0[x]* self.U0_store[r_coord_ref[x,0]][r_coord_ref[x,1]]
else:
u_0 = np.zeros(shape=(num,1), dtype=object)
self.u_0 = u_0
return np.array(u_0, dtype=object)
def characteristics(self, num):
"""
characteristics(num) generates an (n+1)*num size characteristic vector for num dwellings and n+1 characteristics;
characteristics can be sampled from initialized dictionary within __init__.
param num: length of characteristic vector to generate, i.e. no. dwellings to generate for
return: concatenated characteristic vector returned, size (n+1)*num matching household preference vector size.
"""
# B_0 = np.array(sorted(dwell.B0_sample(num)),dtype=float)
B_0 = np.zeros(shape=(num,1))
B_1 = 1 - 2*np.random.random_sample(size=(num, 1)) # style of building; classical (-1), modern (+1)
B_2 = np.random.choice(pop.q_bound['n_people'], size=(num, 1))/4 # number of bedrooms in house (1-4 to match size of households)
B = np.concatenate((B_0, B_1, B_2), axis=1) # compile all the dwelling characteristics
return np.round(np.array(B, dtype=float), 3)
def B0_spatial_sample(self, num, dr_coord):
"""
***NOT USED***
--- MAYBE USE THIS FUNCTION FOR SAMPLING CHARACTERISTICS IN DWELLING CREATION ??
"""
B0 = np.zeros(shape=(num,1))
age = 4
inc = 1
sz = self.R*inc + 1
locs = np.zeros(shape=(sz,sz))
w = np.zeros(shape=(sz,sz))
for x in np.where(self.r[:,1]<=age)[0]:
locs[int(np.round(self.r_coord[x,0])*inc)][int(np.round(self.r_coord[x,1])*inc)] += self.B[x,0]
w[int(np.round(self.r_coord[x,0])*inc)][int(np.round(self.r_coord[x,1])*inc)] += 1
locs /= w
locs[np.isnan(locs)] = 0
mean_grid = np.array(locs)
sig = 1
smooth_mean = gaussian_filter(mean_grid, sigma=sig)
# smooth_mean /= np.max(smooth_mean)
# smooth_mean *= np.max(self.B[np.where(self.r[:,1]<=age),0])
# if sim.step%4==0:
# X,Y = np.meshgrid(np.arange(0,dwell.R*2+1,1),np.arange(0,dwell.R*2+1,1))
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.plot_surface(X, Y, smooth_mean, cmap='viridis')
# ax.set_title('Dwelling B0 sampled from distribution \n(by integer location; smoothed gaussian filter, sigma={})'.format(sig))
# ax.set_xlim([-1,dwell.R*2+1])
# ax.set_ylim([-1,dwell.R*2+1])
# ax.invert_xaxis()
# plt.pause(0.1)
for x in range(len(B0)):
B0[x] = smooth_mean[int(np.round(dr_coord[x,0])*inc)][int(np.round(dr_coord[x,1])*inc)]
return B0
def B0_sample(self, num):
"""
***NOT USED***
-- included as example B0 setting method.
B0_sample(num) samples dwelling prices B0 from range [0.001, 0.999] using the existing
income distribution calcs.F_s as the probability distribution.
param num: number of dwellings to generate B0 for.
"""
B0_scale = np.linspace(1, 0.1, 999) # example B0 range
# sample B0 from income distribution calcs.F_s
B0_draw = np.random.choice(B0_scale, num, p=calcs.F_s)
B0 = np.array([B0_draw], dtype=float).T
return B0
def coordinates(self, num):
"""
coordinates(num) generates unique coordinates for 'num' number of dwellings.
This method also compares to the existing dwelling locations to ensure uniqueness.
param num: number of additional coordinates generate
return: concatenated coordinate vector returned, size 2*num
"""
print('generating unique dwelling locations')
dims = 2 # spatial dimensions; just use 2 as (X,Y) for now. 3 will include apartments but need to do ensure they're 'stacked' into a tower accordingly
if np.sum(self.r_coord) == 0: # check if new or adding to existing
d_r_coord = np.round(np.random.random_sample(size=(self.M, dims))*self.R, 1) # generate random 2D set of coordinates,
size_chk = num
else: # add to existing
d_r_coord = np.round(np.random.random_sample(size=(num, dims))*self.R, 1) # generate random 2D set of coordinates,
d_r_coord = np.concatenate((self.r_coord, d_r_coord))
size_chk = self.M + num
""" to insert custom coordinates of dwellings, add them here to specified index """
# d_r_coord[0] = [0, 0] # example insertion of coords (2D)
# check for duplicates of coordinates then resample duplicates
uniq, ind = np.unique(d_r_coord, axis=0, return_index=True)
unsorted = np.array(sorted(np.concatenate((np.array(uniq), np.array([ind]).T), axis=1), key=lambda x:x[2]))
uniq = np.delete(unsorted, -1, axis=1)
while True:
if len(uniq) == size_chk:
r_coord = uniq
break
else:
d_r_coord = np.round(np.random.random_sample(size=(size_chk-len(uniq), dims))*self.R, 1) # generate random 2D set of coordinates,
uniq, ind = np.unique(np.concatenate((uniq, d_r_coord)), axis=0, return_index=True)
unsorted = np.array(sorted(np.concatenate((np.array(uniq), np.array([ind]).T), axis=1), key=lambda x:x[2]))
uniq = np.delete(unsorted, -1, axis=1)
r_coord = r_coord[-num:]
return r_coord
def nearby_coords(self, nearby, num):
"""
nearby_coords(nearby) generates unique coordinates for 'num' number of dwellings,
at location nearby to previously transacted dwellings.
This method also compares to the existing dwelling locations to ensure uniqueness.
- effectively same function as 'coordinates()' but operates via distance to specific dwellings.
param num: number of additional coordinates generate
param nearby: nearby dwellings to find similar location
return: concatenated coordinate vector returned, size 2*num
"""
dims = 2 # spatial dimensions; just use 2 as (X,Y) for now. 3 will include apartments but need to do ensure they're 'stacked' into a tower accordingly
d_r_coord = np.round(np.random.random_sample(size=(num, dims))*self.R, 1) # generate random 2D set of coordinates,
d_r_coord = np.concatenate((self.r_coord, d_r_coord))
size_chk = self.M + num
# check for duplicates of coordinates then resample duplicates
uniq, ind = np.unique(d_r_coord, axis=0, return_index=True)
unsorted = np.array(sorted(np.concatenate((np.array(uniq), np.array([ind]).T), axis=1), key=lambda x:x[2]))
uniq = np.delete(unsorted, -1, axis=1)
exist_r_coord = self.r_coord[nearby] # existing coordinates
tmp = uniq[len(self.r_coord):]
dwell_1 = np.reshape(np.repeat(exist_r_coord, len(tmp), axis=1).T, (2,-1)).T
dwell_2 = np.reshape(np.repeat(tmp, len(exist_r_coord), axis=0).T, (2,-1)).T
euclids = np.reshape(np.linalg.norm(dwell_1.T - dwell_2.T, axis=0), (len(exist_r_coord), -1)).T
tmp = uniq[len(self.r_coord):]
uniq_tmp = tmp[np.unique(np.where(euclids<=sim.h*3)[0])]
uniq = np.concatenate((np.array(self.r_coord), np.array(uniq_tmp)),axis=0)
while True:
if len(uniq) == size_chk:
r_coord = uniq
break
else:
d_r_coord = np.round(np.random.random_sample(size=(size_chk-len(uniq), dims))*self.R, 1) # generate random 2D set of coordinates,
uniq, ind = np.unique(np.concatenate((uniq, d_r_coord)), axis=0, return_index=True)
unsorted = np.array(sorted(np.concatenate((np.array(uniq), np.array([ind]).T), axis=1), key=lambda x:x[2]))
uniq = np.delete(unsorted, -1, axis=1)
# chk distance
tmp = uniq[len(self.r_coord):]
dwell_1 = np.reshape(np.repeat(exist_r_coord, len(tmp), axis=1).T, (2,-1)).T
dwell_2 = np.reshape(np.repeat(tmp, len(exist_r_coord), axis=0).T, (2,-1)).T
euclids = np.reshape(np.linalg.norm(dwell_1.T - dwell_2.T, axis=0), (len(exist_r_coord), -1)).T
tmp = uniq[len(self.r_coord):]
uniq_tmp = tmp[np.unique(np.where(euclids<=sim.h*3)[0])]
uniq = np.concatenate((np.array(self.r_coord), np.array(uniq_tmp)),axis=0)
r_coord = r_coord[-num:]
return r_coord
def general(self, num):
"""
general(num) generates general dwelling information [dwelling ID, on/off-market flag]
param num: length of general info vector to generate
return: concatenated general info vector returned, size 2*num
"""
r_0 = np.linspace(0, num-1, num, dtype=int) # dwelling ID (trivial)
r_1 = np.ones(shape=(num, 1), dtype=int) # on-market flag of dwelling
r = np.concatenate((np.array([r_0]).T, r_1), axis=1) # compile all general dwelling information
return r
def utility_0_new(self, r_coord):
"""
utility_0_new(r_coord) samples dU_0 from the U_0 distribution of existing dwellings
param r_coord: input coordinates to sample from the existing U_0 mapping
return: output u_0 vector of input size(r_coord)
"""
r_coord_ref = np.array(np.round(r_coord * 4), dtype=int)
if np.size(self.centric) == 0:
u_0 = np.zeros((np.shape(r_coord)[0],1), dtype=object) * self.price_scale
else:
u_0 = np.ones((np.shape(r_coord)[0],1), dtype=object)# * self.price_scale
# sample from the generated U0 distribution
for x in range(len(r_coord)):
u_0[x] = u_0[x] * self.U0_store[r_coord_ref[x,0]][r_coord_ref[x,1]] * self.price_scale
return u_0
def dwell_shuffle(self):
"""
***NOT USED***
-- included as example of shuffling characteristic by another property.
dwell_shuffle() shuffles the number of bedrooms of a dwelling as according to the U0 value so as to represent reality where
inner-city is full of apartments/smaller dwellings and the size generally increases with distance from the center of the city.
"""
# U0 is chosen as a filter/means for sorting as it is a measure for distance from a central point.
u0 = np.array(sorted(enumerate(self.r[:,2]), key=lambda x:x[1]))[:,0]
B2_u0 = np.concatenate((np.array([sorted(self.B[:,2])]), np.array([u0])), axis=0).T
B2_u0 = np.array(sorted(B2_u0, key=lambda x:x[1])).T
self.B[:,2] = B2_u0[0]
def B1_gen(self):
"""
*** ONLY USED IN CASE C ***
B1_gen() generates B_1(r) values for dwelling characteristic vector
atm only has capacity for 2 centres, needs to be refactored.
"""
b1_max = self.price_scale*4
self.b1_cent_1 = np.array([[0.7, 0.7]]) * sim.R
self.b1_cent_2 = np.array([]) * sim.R
if len(self.b1_cent_2) ==0:
qq = np.array([self.b1_cent_1])
else:
qq = np.array([self.b1_cent_1, self.b1_cent_2])
self.incs = self.R*4 + 1
dim = np.linspace(0, self.R, self.incs)
x_map, y_map = np.meshgrid(dim, dim)
u0_map = np.concatenate((np.array([x_map.flatten()]).T, np.array([y_map.flatten()]).T), axis=1)
if np.size(self.b1_cent_1) > 0:
B1_1_dist = []
for x in range(len(self.b1_cent_1)):
B1_1_dist.append(np.linalg.norm(u0_map.T - np.array([self.b1_cent_1[x]]).T, axis=0))
x = np.min(B1_1_dist, axis=0)
B1_1_str = b1_max*np.exp(-abs(x**2)/(4**2))
else:
B1_1_str = []
if np.size(self.b1_cent_2) > 0:
B1_2_dist = []
for x in range(len(self.b1_cent_2)):
B1_2_dist.append(np.linalg.norm(u0_map.T - np.array([self.b1_cent_2[x]]).T, axis=0))
x = np.min(B1_2_dist, axis=0)
B1_2_str = -b1_max*np.exp(-abs(x**2)/(4**2))
else:
B1_2_str = []
# scale to +- b1_max limits
if np.size(self.b1_cent_1)>0 and np.size(self.b1_cent_2)>0:
s1_str = B1_1_str + B1_2_str
elif np.size(self.b1_cent_1)>0 and np.size(self.b1_cent_2)==0:
s1_str = B1_1_str
elif np.size(self.b1_cent_1)==0 and np.size(self.b1_cent_2)>0:
s1_str = B1_2_str
s1_str += abs(np.min(s1_str))
s1_str /= np.max(s1_str)
s1_str *= b1_max*2
s1_str -= b1_max
s1_str = np.reshape(s1_str, (self.incs,-1))
self.B1_dist_val = np.round(s1_str,3)
r_coord_ref = np.array(np.round(self.r_coord * 4), dtype=int)
B_1 = np.zeros(shape=(self.M,1))
# assign B1 to dwellings
for x in range(len(B_1)):
B_1[x] = self.B1_dist_val[r_coord_ref[x,0]][r_coord_ref[x,1]]
self.B = np.round(np.array(np.concatenate((self.B, B_1), axis=1),dtype=float),3)
def perturb(self):
"""
perturb() alters characteristics of dwellings; age is only characteristic/property that is altered for now.
Future I: could also adapt the characteristics of the occupied dwellings to that of the occupying household,
possibly at a cost to the household (mimicking renovation/extensions, requires investment model).
"""
self.r[np.where(self.r[:,1]!=0), 1] += 1 # increase age/period of uninhabitance
# dwell.update_unocc_local_B0()
def update_unocc_local_B0(self):
"""
***NOT USED***
-- included as example B0 update method.
update_unocc_local_B0() updates the dwelling price B0 of dwellings that have been unoccupied for a period of time
to the local max B0 of currently/recently occupied dwellings.
'local' dwellings are is determined via nearest 0.5km^2 coordinate grid then smoothed via gaussian filtering with
sigma=2.
"""
age = 4
inc = 1
sz = dwell.R*inc + 1
# check for dwelling unoccupied for > 1.5 yrs or >6 timesteps
un_occ = np.where(self.r[:,1]>age)
if np.size(un_occ) !=0:
locs = np.zeros(shape=(sz,sz))
w = np.zeros(shape=(sz,sz))
for x in np.where(self.r[:,1]<=age)[0]:
locs[int(np.round(dwell.r_coord[x,0])*inc)][int(np.round(dwell.r_coord[x,1])*inc)] += dwell.B[x,0]
w[int(np.round(dwell.r_coord[x,0])*inc)][int(np.round(dwell.r_coord[x,1])*inc)] += 1
locs /= w
locs[np.isnan(locs)] = 0
mean_grid = np.array(locs)
sig = 1
smooth_mean = gaussian_filter(mean_grid, sigma=sig)
smooth_mean /= np.max(smooth_mean)
smooth_mean *= np.max(dwell.B[np.where(self.r[:,1]<=age),0])
# if sim.step%4==0:
# X,Y = np.meshgrid(np.arange(0,dwell.R*2+1,1),np.arange(0,dwell.R*2+1,1))
# fig = plt.figure()
# ax = fig.add_subplot(111, projection='3d')
# ax.plot_surface(X, Y, smooth_mean, cmap='viridis')
# ax.set_title('Dwelling B0 sampled from distribution \n(by integer location; smoothed gaussian filter, sigma={})'.format(sig))
# ax.set_xlim([-1,dwell.R*2+1])
# ax.set_ylim([-1,dwell.R*2+1])
# ax.invert_xaxis()
# plt.pause(0.1)
for x in un_occ[0]:
self.B[un_occ,0] = smooth_mean[int(np.round(dwell.r_coord[x,0])*inc)][int(np.round(dwell.r_coord[x,1])*inc)]
def evolve(self):
"""
evolve() contains methods relating to manipulation of the total number of dwellings; evolution of supply/demand.
i.e. changing supply via increasing/decreasing the number of dwellings.
The method for increasing the number of dwellings calls functions that are called in the construct() function
during initilisation of dwellings, creates 'new' number of dwellings.
The method for creasing deletes an 'old' number of random dwellings that have been unoccupied for >n periods,
alternatively if purely random then any occupants will be set in-market.
Both methods re-adjust the dwelling IDs to correspond with the total number of dwellings in the model.
"""
""" DWELLING CREATION """
new = int(sim.beta*self.M) # no. dwellings to create
if self.M + new <= self.M_max:
pass
else:
new = self.M_max - self.M
if new > 0 and sim.step/4 > 21:
if hasattr(sim, 'new_min') == False:
sim.new_min = sim.step # timestep at which household creation begins
dwell.growth(new)
elif sim.beta!=0 and new == 0 and sim.step/4>21 and hasattr(sim, 'new_max') == False:
sim.new_max = sim.step # timestep at which household creation ceases
""" DWELLING DESTRUCTION """
if sim.step/4 > -1:
demo = int(sim.lamb*self.M) # no. dwellings to delete
old = np.where(self.r[:,1]>=8)[0] # delete dwellings off-market for more than 8 periods
if demo > 0 and np.size(old)>0 and self.M > self.M_min*pop.N:
dwell.destroy(demo, old)
def growth(self, new):
"""
growth() generates new dwellings to add to existing dwellings. Characteristics and all other info
is generated as per the construct() function.
New dwellings flagged as on-market.
In present version, new dwellings take on random characteristics & random location.
Paper refers to eq. 19 as method for generating new dwellings.
param new: input number of dwellings to create
"""
""" CREATE DWELLING BY EQ. 19 """
# duplicate recently transacted dwellings
r = dwell.r
# r_rec = np.where((r[:,1]!=0)&(r[:,1]<=4))[0]
# r_rec = np.where(r[:,1]==0)[0]
if len(self.r_recs)>2:
self.r_recs = np.array(self.r_recs[1:])
self.r_recs = np.concatenate((np.array(self.r_recs),np.array(calcs.rec_tran)),axis=0)
# print(self.r_recs)
r_rec = np.reshape(np.array(self.r_recs, dtype=int),(1,-1))[0]
# self.r_recs.append(np.array(calcs.rec_tran))
# generate coordinates nearby recently transacted
dr_coord = dwell.nearby_coords(r_rec, new)
# sample general utility from the existing distribution