-
Notifications
You must be signed in to change notification settings - Fork 0
/
NASA2LEGO.py
2255 lines (2024 loc) · 81.4 KB
/
NASA2LEGO.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
#!python3
## Tommy Carstensen, Aug-Sep2014, Apr-May2015
## Acknowledgments:
## Martin Haspelmath
## William Reno
## Friedrich Riha, Manj Sandhu, Joshua Randall, Mutua Matheka, Jane Walsh
## Wikimedia Foundation, Inc., Glottolog, Ethnologue
## Python Software Foundation
## Free Software Foundation
## GNU Project
## NASA Shuttle Radar Topography Mission (SRTM)
## NASA Socioeconomic Data and Applications Center (SEDAC)
## Felix 2001
## The LEGO company.
## todo: add transparent plats for:
## http://en.wikipedia.org/wiki/List_of_lakes_by_area
## 3) Lake Victoria
## 6) Lake Tanganyika
## 9) Lake Malawi
## 22) Turkana
## 28) Albert
## 29) Mweru
## Lake Chad
## Lake Tana / Blue Nile origin
## http://en.wikipedia.org/wiki/List_of_rivers_of_Africa
## http://en.wikipedia.org/wiki/Geography_of_Africa#Rivers
## !1) Nile River
## 2!) Congo River
## 3) Blue Nile
## 3!) Niger
## 3) Uele
## 3!) Zambezi
## 3) Kasai
## 4!) Senegal???
## 4!) Vaal/Orange
## 4) Benue!
## 5!) Volta River and tributaries: black, white, red
## 6) White Volta
## 6) Sassandra
## 6) Sanaga
## 6) Chari
## 6) Atbara
## 6!) Jubba
## 6) Ruvuma
## 6!) Okavango
## 6!) Limpopo
## http://en.wikipedia.org/wiki/Rufiji_River
d_mountains = {}
d_rivers = {
'Nile': (30, 10, 31, 6),
'Congo': (-6, -4, 12, 27),
'Niger': (13, 60*0.86, -3, -60*0.33),
'Zambezi': (-18, -34, 36, 28),
'Senegal': (15, 47, -16, -31),
'Vaal': (-29, -4, 23, 38),
'Volta': (5, 46, 0, -41),
'Jubba': (0, 0.2495*60, 42, 60*0.6307),
'Okavango': (-18, -57, 22, 29),
'Limpopo': (-25, -10, 33, 35),
'WhiteNile': (-2, -17, 29, 20),
'BlueNile': (12, 0, 37, 15),
'BlueNile': (15, 38, 32, 32),
'Rufiji': (-8, 0, 39, 20),
}
d_lakes = {
'Lake Victoria': (-1, 0, 33, 0),
'Lake Tanganyika': (-6, -30, 29, 50),
'Lake Malawi': (-12, -11, 34, 22),
'Lake Turkana': (3, 35, 36, 7),
'Lake Albert': (1, 41, 30, 55),
'Lake Mweru': (-9, 0, 28, 43),
'Lake Chad': (13, 0, 14, 0),
'Lake Tana': (12, 0, 37, 15),
}
## todo: Slope 30 1 x 1 x 2/3 for mountains or anything above an altitude threshold
## try 3000m or 2000m
## http://en.wikipedia.org/wiki/List_of_highest_mountain_peaks_of_Africa
## http://en.wikipedia.org/wiki/Geography_of_Africa#Plateau_region
## http://en.wikipedia.org/wiki/Geography_of_Africa#Mountains
## https://pypi.python.org/pypi/SRTM.py
## https://github.com/tkrajina/srtm.py
## Flags for: Yoruba, Igbo, Fula, Shona, Zulu
import numpy as np
import math
import fractions
import os
import collections
import csv
import json
import shapely
from shapely.geometry import Point
import itertools
import argparse
import matplotlib.pyplot as plt
##
d_len2dIDs = {
## plates
1: {
## width 1
1: {1: 3024, 2: 3023, 3: 3623, 4: 3710, 6: 3666, 8: 3460},
2: {1: 3023, 2: 3022, 3: 3021, 4: 3020, 6: 3795, 8: 3034},
},
## bricks
3: {
## width 1
1: {1: 3005, 2: 3004, 3: 3622, 4: 3010, 6: 3009, 8: 3008},
## width 2
2: {1: 3004, 2: 3003, 3: 3002, 4: 3001, 6: 2456, 8: 3007},
## 2: {1: 3004, 2: 3003, 3: 3002, 4: 3001, 6: 44237, 8: 93888},
},
}
d_dIDs2dim = {}
for h in d_len2dIDs:
for w in sorted(d_len2dIDs[h].keys()):
for l, ID in d_len2dIDs[h][w].items():
if ID in d_dIDs2dim.keys():
continue
d_dIDs2dim[ID] = {'dim0': w, 'dim1': l}
## square plates
d_dIDs_sq_plate = {
## 16: 91405, # 16x16 (GBP2.58) only marginally cheaper than 8x8 (GBP0.67)
8: 41539,
6: 3958, # 6x6 (GBP0.43) more expensive than 4x4 (GBP0.18) per area
4: 3031,
}
designID_baseplate = 4186
materialID_grey = 194
for k, v in d_dIDs_sq_plate.items():
d_dIDs2dim[v] = {'dim0': k, 'dim1': k}
d_dIDs2dim[3001] = {'dim0': 2, 'dim1': 4}
d_dIDs2dim[d_len2dIDs[3][2][6]] = {'dim0': 2, 'dim1': 6}
d_dIDs2dim[d_len2dIDs[3][2][8]] = {'dim0': 2, 'dim1': 8}
## Ubiquitous material IDs; i.e. 1x1 and 2x4 bricks available in PAB.
ubiquitous = {
1, # White
21, # Red
23, # Blue
24, # Yellow
26, # Black
28, # Green
5, # Tan
106, # Orange
194, # Stone Grey
199, # Stone Grey
192, # Reddish Brown
119, # Lime
## 222, # Light Purple / Light Pink
}
materialID_buried = 999
## Tuples are sorted from common to rare.
d_colorfamily2color = {
'red': (
21, # red
154, # new dark red
## 192, # reddish brown
), # Khoisan
'black':(26,), # IndoEuropean/Afrikaans
## Niger-Congo
'blue': (
23, 102, 140,
1, # White looks good with bright blue colors and is cheaper.
323, # Aqua / Unikitty Blue (1x1 plate out of stock, but got from BL)
## 322, # Medium Azure 322 (1x1 brick - 1x1 plate out of stock)
#### 321, # # Dark Azure 321 (1x2 plate - no 1x1 size)
),
## AfroAsiatic
'yellow-orange-brown': (
24, # yellow
5, # tan
106, # orange
192, # reddish brown
138, # dark tan
191, # flame orange
226, # cool yellow / bright light yellow
),
## Bantu
'green': (
28, # green
119, # lime
141, # earth green / dark green
330, # olive
326, # Spring Yellowish Green / Yellowish Green (only 1x1 plate available)
## 151, # / Sand Green (got 500 1x1 plates from BL, but otherwise NA)
),
'purple': (
222, # Light Purple / Bright Pink
124, # Bright Reddish Violet / Magenta
324, # Medium Lavender
## 268, # Medium Lilac
## 221, # Bright Purple / Dark Pink (discontinued in 2004)
## "The medium lilac element ID 4224857 is out of stock
## and we have no plans on bringing it back at this time."
), # NiloSaharan
'grey': (
194, # medium stone grey
199, # dark stone grey
), # Other...
## 'white': {1}, # buried
}
d_color2family = {
color: family for family, colors in d_colorfamily2color.items()
for color in colors}
d_max_len = {
## plates
1: {
## width 1
1: {
1: 12,
26: 10, 5: 10, 192: 10, 194: 10,
21: 8, 23: 8, 24: 8, 28: 8, 199: 8,
106: 6, 102: 6, 141: 6, 140: 6, 154: 6,
119: 4, 324: 4, 222: 4,
330: 2,
},
2: {
1: 12, 26: 12, 199: 12, 194: 12,
21: 10, 5: 10,
23: 8, 24: 8, 28: 8, 192: 8,
106: 6, 119: 6, 222: 6,
154: 4, 141: 4,
330: 1,
},
},
## bricks
3: {
## width 1
1: {
1: 8, 2: 3004, 3: 3622, 4: 3010, 6: 3009,
191: 4,
},
## width 2
2: {
1: 8,
191: 1, 303: 1, 324: 1,
},
},
}
## Not available in replacement parts.
d_NA = {
## plates
1: {
## width 1
1: {
8: {191, 221, 138, 330, 330, 138, 221, 191, 191, 326, 124,},
6: {330, 141, 221, 268, 323, 326, 151,},
4: {330, 221, 268, 323, 326, 151,},
3: {138, 330, 324, 138, 124, 221, 268, 323, 106, 102,},
2: {323, 326, 322,}, # Aqua, Medium Azure
## 1: {321}, # Dark Azure
1: {
322, # medium azure
## 323, # aqua / unikitty blue (got 500 1x1 plates from BL)
268, # medium lilac (dark purple)
221, # bright purple (dark pink)
321, # dark azure
151, # sand green
},
},
## width 2
2: {
8: {221, 268, 330, 326, 28,},
6: {221, 268, 326, 141, 124,},
## 3020
4: {221, 268, 323, 326, 222, 151, 222, 124,},
## 3021
3: {191, 124, 330, 221, 268, 323, 326, 154, 119, 102, 151, 326,},
2: {
221, 141, 330, 324, 221, 268, 323, 330, 326, 222, 138,
124, 151, 330, 124, 330, 140, 140, 330, 321,
},
1: {},
},
},
## bricks
3: {
## width 1
1: {
8: {
221, 268, 222, 124, 323, 322, 326, 119, 324, 102, 106,
140, 141,
28, # green available as replacement but 0.42GBP VS two 1x4 = 0.12GBP
},
6: {
191, 221, 140, 324, 221, 268, 140, 323, 324, 222, 151, 102,
323, 141, 326, 321,
119, # lime available as replacement but 0.38GBP
},
4: {268, 323, 326, 151,},
3: {
221, 268, 138, 124, 323, 322, 326, 141, 324, 140, 154, 191,
321,
},
2: {326,}, # Spring Yellowish Green / Yellowish Green (from 2015)
1: {
226, 326,
321, # dark azure
}, # Cool Yellow (226), Spring Yellowish Green (326)
},
## width 2
2: {
8: {221, 268, 330, 222, 138, 324, 323, 322, 28, 192, 28,},
6: {221, 330, 221, 268, 326, 106, 119, 124, 324,},
4: {140, 124,},
3: {191, 330, 221, 268, 324, 323, 322, 326,},
2: {
191, 330, 324, 323, 326, 141, 330, 151, 141, 330, 124, 321,
124, 330, 124,
},
1: {},
},
},
}
d_NA[1][2][1] = d_NA[1][1][2]
d_NA[3][2][1] = d_NA[3][1][2]
## Most common bricks:
## https://www.bricklink.com/catalogStats.asp?statID=C&itemType=P&inItemType=&catID=5
## Most common plates:
## TODO: FIRST LOOP 3 LAYERS (BRICK) AND THEN 1 LAYER (PLATES)
## I.E. REPLACE CONNECTED PLATES IN 3 LAYERS WITH CHEAPER 12x24 brick...
## e.g. function find_connected_buried
## https://www.bricklink.com/catalogItem.asp?P=30072
## https://service.lego.com/en-gb/replacementparts#WhatIndividualBrickBuy/30072
## 30072 out of producing since 2008 according to TLG
def main():
args = argparser()
## lcm = nrows2*n/fractions.gcd(nrows2,n)
## print(lcm,fractions.gcd(nrows2,n))
## print(90*8/fractions.gcd(90,8),fractions.gcd(90,8))
## print(8/fractions.gcd(90,8),90/fractions.gcd(90,8))
## print(nrows2/fractions.gcd(nrows2,n))
## stop
affix1 = 'lxfml/{0}_{1:d}x{1:d}_dens{2}'.format(
args.affix, args.n, args.density)
## 0-args.layers
if not os.path.isfile('{}.npy'.format(affix1)):
## slow
a_2D_density = asc2np(args, affix1)
else:
## fast
a_2D_density = np.load('{}.npy'.format(affix1))
## Normalise population density.
a_2D_density = normalize(a_2D_density, args)
## slow - convert ethnicity polygons from json file to numpy array
## i.e. assign a tentative materialID to each 2D point
a_2D_mIDs = json2array(args, a_2D_density)
## Do a manual fix of zero density in the Eastern Desert in Egypt.
a_2D_density = fix_zero_density_in_desert(
a_2D_density, a_2D_mIDs, args)
## Do this before finding buried plates.
a_2D_density, a_2D_mIDs = color_as_nearby(args, a_2D_density, a_2D_mIDs)
## fast
## Identify how many plates are buried at each grid position.
a_2D_buried = find_buried(args, a_2D_density, args.layers, a_2D_mIDs)
## slow
## 0-(args.layers-1)
a_3D_dIDs = find_connected_buried(
args, a_2D_buried, a_2D_density, a_2D_mIDs)
##
a_3D_dIDs, a_3D_mIDs, a_3D_angle = find_connected_exposed(
args, a_2D_density, a_2D_buried,
a_2D_mIDs, a_3D_dIDs)
## ## Add rivers and lakes.
## ncols, nrows, xllcorner, yllcorner, cellsize = read_gpw_header(
## '{}.asc'.format(args.affix))
## for key, coord in itertools.chain(d_rivers.items(), d_lakes.items()):
## _den = cellsize * max(nrows, ncols)
## lat = coord[0]+coord[1]/60
## lon = coord[2]+coord[3]/60
## row = int(round(args.n*(lat-yllcorner+cellsize*(ncols-nrows)/2)/_den-0.5, 0))
## col = int(round(args.n*(lon-xllcorner)/_den-0.5, 0))
## print(key, coord, lat, lon, row, col)
## assert a_3D_dIDs[a_2D_density[row][col]][row][col] == 0
## a_3D_dIDs[a_2D_density[row][col]][row][col] = 3024
## a_3D_mIDs[a_2D_density[row][col]][row][col] = 40
## slow
lxfml = '{}_y{:d}_{}.lxfml'.format(affix1, args.layers, args.norm)
numpy2lxfml(
args,
a_2D_density, lxfml, a_2D_mIDs, a_2D_buried,
a_3D_dIDs, a_3D_mIDs, a_3D_angle)
## print(pcount_max)
## print(np.amin(a_gpw))
## from collections import Counter
## print(Counter([float(x) for x in np.nditer(a_gpw)]))
return
def histogram2(a_2D_density, args):
path = 'density2_{}.png'.format(args.affix)
if os.path.isfile(path):
return
x = []
for row in range(args.n):
for col in range(args.n):
if a_2D_density[row][col] == 0:
continue
x += [a_2D_density[row][col]]
plt.xlabel('Normalised population density (arbitrary unit)')
plt.ylabel('Frequency')
n, bins, patches = plt.hist(
x, args.layers, normed=1, facecolor='g', alpha=0.75)
plt.savefig(path)
plt.close()
return
def histogram1(a_2D_density, args):
path = 'density1_{}.png'.format(args.affix)
if os.path.isfile(path):
return
x = []
for row in range(args.n):
for col in range(args.n):
if a_2D_density[row][col] == 0:
continue
x += [math.log(a_2D_density[row][col])]
plt.xlabel('Natural logarithm of population density (arbitrary unit)')
plt.ylabel('Frequency')
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.savefig(path)
plt.close()
return
def fix_zero_density_in_desert(a_2D_density, a_2D_mIDs, args):
## Make sure bricks are present
## for areas covered by language family polygons.
## Creates low density at coast.
## So only do this for the Eastern Desert of Egypt.
## https://en.wikipedia.org/wiki/List_of_tripoints
## https://en.wikipedia.org/wiki/Geography_of_Egypt#Extreme_points
## https://en.wikipedia.org/wiki/22nd_parallel_north
## https://en.wikipedia.org/wiki/Bir_Tawil
## Egypt, Sudan, Libya tripoint
tripoint_SW_lat = 22
tripoint_SW_lon = 25
## Egypt, Palestine/Gaza, Israel tripoint
tripoint_NE_lat = 31.216667
tripoint_NE_lon = 34.266667
## https://en.wikipedia.org/wiki/List_of_countries_by_easternmost_point
easternmost_lon = 35.75
ncols, nrows, xllcorner, yllcorner, cellsize = read_gpw_header(
'{}.asc'.format(args.affix))
## Loop North to South.
for row in range(a_2D_density.shape[0]):
dy = cellsize*(row+0.5)*max(nrows, ncols)/args.n
dy -= cellsize*(ncols-nrows)/2
latitude = -yllcorner-dy
## Loop West to East.
for col in range(a_2D_density.shape[1]):
dx = cellsize*(col+0.5)*max(nrows, ncols)/args.n
longitude = xllcorner+dx
## Language polygon, but no population density.
if all([
a_2D_mIDs[row][col] > 0,
a_2D_density[row][col] == 0]):
## todo: generate map with and without!!!
if all([
latitude > tripoint_SW_lat,
longitude > tripoint_SW_lon,
latitude < tripoint_NE_lat,
longitude < easternmost_lon,
]):
if args.verbose:
print('fix desert', latitude, longitude, row, col)
a_2D_density[row][col] = 1
else:
print('tmp skip', row, col, latitude, longitude)
continue
return a_2D_density
def color_as_nearby(args, a_2D_density, a_2D_mIDs):
assert a_2D_density.shape == a_2D_mIDs.shape
ncols, nrows, xllcorner, yllcorner, cellsize = read_gpw_header(
'{}.asc'.format(args.affix))
## http://en.wikipedia.org/wiki/List_of_countries_by_southernmost_point
## http://en.wikipedia.org/wiki/List_of_countries_by_westernmost_point
Yemen_South = 12+7/60 # 12.66
Yemen_West = 41+42/60 # 43.12 # 43.42
Yemen_South1 = 12+(33.75-0.01)/60
Yemen_West1 = 43+(18.75-0.01)/60
Yemen_South2 = 13+(41.25-0.01)/60
Yemen_West2 = 42+(33.75-0.01)/60
Israel_South = 29.5
Israel_West = 34+17/60
Gaza_West = 34+15/60
## http://en.wikipedia.org/wiki/Extreme_points_of_Spain
Spain_South = 36+0/60
Spain_East = -4.75 # -(3+19/60)
## http://en.wikipedia.org/wiki/List_of_countries_by_easternmost_point
SaudiArabia_South = 16+5/60
SaudiArabia_South = 17+(3.75-0.01)/60
SaudiArabia_East = 40+(41.25-0.01)/60
## Sudan_East = 38+35/60
## http://en.wikipedia.org/wiki/Sharm_el-Sheikh
Sharm_elSheikh_lon = 34+19/60 # Suez Canal East boundary
# http://en.wikipedia.org/wiki/Ras_Muhammad_National_Park
Sinai_South_lat = 27+43/60 # Gulf of Aqaba South boundary
Sinai_South_lon = 34+15/60 # Gulf of Aqaba West boundary
Egypt_South = 22
## http://en.wikipedia.org/wiki/Suez
Suez_lat = 29+58/60 # Suez Canal North Boundary
Suez_lon = 32+33/60 # Suez Canal West Boundary
## http://en.wikipedia.org/wiki/Safaga
Safaga_lat = 26+44/60 # Suez Canal South boundary
## Canary Islands
## http://en.wikipedia.org/wiki/Roque_del_Este
Canary_Islands_lon = -13-20/60
## Strait of Sicily
Libya_N_lat = 33+10/60
Tunisia_E_lon = 11+35/60
## Setting zero density if no color is not a good solution,
## because lakes will randomly appear and disappear,
## because the polygons are poorly defined.
dist = 3
for x in range(dist, a_2D_density.shape[0]-dist):
row = x
lat = -cellsize*(row+0.5)*max(nrows, ncols)/args.n-yllcorner
lat += cellsize*(ncols-nrows)/2
for z in range(dist, a_2D_density.shape[1]-dist):
col = z
lon = cellsize*(col+0.5)*max(nrows, ncols)/args.n+xllcorner
## Popuation density is zero.
if a_2D_density[x][z] == 0:
continue
## Point is in language polygon.
if a_2D_mIDs[x][z] > 0:
continue
## If not densely populated and not covered by language polygon
## then delete. Because probably near coast or lake.
## Including this deletion does not cause problems in Egypt.
## todo: generate map with and without!!!
if a_2D_density[x][z] == 1:
## if args.verbose:
## print(
## 'near zero density (e.g. outside Africa and coast)',
## x, z, lat, lon)
a_2D_density[x][z] = 0
continue
## if lat > Yemen_South and lon > Israel_West:
## dist = 1
## else:
## dist = 2
## Count nearby materialIDs.
cnt = collections.Counter(
a_2D_mIDs[x+dx][z+dz]
for dx in range(-dist, dist+1) for dz in range(-dist, dist+1)
)
## Assign greater weight to most nearby.
cnt += collections.Counter(
a_2D_mIDs[x+dx][z+dz]
for dx in range(-1, 1+1) for dz in range(-1, 1+1)
for i in range(dist**2)
)
del cnt[0]
## No nearby polygons/colors.
if len(cnt) == 0:
continue
## No bricks in Yemen.
## if lat > Yemen_South and lon > Yemen_West:
## if args.verbose:
## print('Yemen',x,z,lat,lon)
## a_2D_mIDs[x][z] = 221
## continue
## Do not connect colors/polygons across the Red Sea.
if lat >= Yemen_South and lon >= Israel_West and a_2D_density[x+1][z] == 0:
a_2D_density[x][z] = 0
continue
if lat >= Yemen_South1 and lon >= Yemen_West1:
if args.verbose:
print('Yemen1',x,z,lat,lon)
a_2D_density[x][z] = 0
continue
if lat >= Yemen_South2 and lon >= Yemen_West2:
if args.verbose:
print('Yemen2',x,z,lat,lon)
a_2D_density[x][z] = 0
continue
## No bricks in Israel and Gaza.
if lat > Israel_South and lon > Gaza_West:
if args.verbose:
print('Israel',x,z,lat,lon)
a_2D_density[x][z] = 0
continue
## No bricks in Saudi Arabia across the Red Sea.
if lat > SaudiArabia_South and lon > SaudiArabia_East:
if args.verbose:
print('Saudi',x,z,lat,lon)
## a_2D_mIDs[x][z] = 221
a_2D_density[x][z] = 0
continue
## No bricks in Saudi Arabia across the Gulf of Aqaba.
if all([
lat > Sinai_South_lat,
lon > Sinai_South_lon,
a_2D_density[x][z] < args.layers/3]):
## a_2D_mIDs[x][z] = 102 # medium blue
a_2D_density[x][z] = 0
continue
## No bricks in Saudi Arabia across the Gulf of Aqaba.
if all([
lat > Egypt_South,
lon > Gaza_West,
any([a_2D_density[x][z-1] == 0, a_2D_density[x][z-2] == 0])]):
## a_2D_mIDs[x][z] = 221
a_2D_density[x][z] = 0
continue
## No Bricks in Andalusia.
if lat > Spain_South and lon < Spain_East:
## a_2D_mIDs[x][z] = 221
a_2D_density[x][z] = 0
continue
## No Bricks in Andalusia.
if lat > Spain_South and a_2D_density[x+1][z] == 0:
## a_2D_mIDs[x][z] = 221
a_2D_density[x][z] = 0
continue
## Clear bricks in the Suez canal:
if all([
lat > Safaga_lat,
lat < Suez_lat,
lon > Suez_lon,
## lon < Sinai_South_lon,
lon < Sharm_elSheikh_lon,
a_2D_density[x][z] < args.layers/3]):
## a_2D_mIDs[x][z] = 221
a_2D_density[x][z] = 0
continue
## ## Clear brick(s) in the Red Sea south of the Sinai peninsula.
## if latitutde > Safaga_lat and lat
## Skip Canary Islands
if lon < Canary_Islands_lon and a_2D_mIDs[x][z+1] == 0:
a_2D_density[x][z] = 0
continue
## No bricks in the strait of Sicily.
if lat > Libya_N_lat and lon > Tunisia_E_lon:
a_2D_density[x][z] = 0
continue
## Set materialID to most frequently occuring nearby materialID.
a_2D_mIDs[x][z] = cnt.most_common(1)[0][0]
## a_2D_mIDs[x][z] = 5
## print(cnt.most_common(1)[0][0])
return a_2D_density, a_2D_mIDs
def argparser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--affix', default='afds00g',
choices=['afp00ag', 'afp00g', 'afds00ag', 'afds00g'])
parser.add_argument(
'--plate_size', default=48, type=int, choices=[16, 32, 48],
help='Size of base plates to build on.')
parser.add_argument(
'--plate_cnt', default=5, type=int,
help='Number of base plates along one dimension.')
parser.add_argument(
'--zero', help='add zero values to average?', action='store_true')
parser.add_argument(
'--verbose', help='Be verbose?', action='store_true')
parser.add_argument(
'--density', help='Take max or mean of density grid?', choices=['max', 'mean'], default='max')
parser.add_argument('--layers', default=27, type=int)
parser.add_argument('--norm', default='log', choices=[
'log10', 'log2', 'unity', 'log']) # unity is feature scaling
parser.add_argument('--colors', required=True)
args = parser.parse_args()
# script fast if multiple of 2160
args.n = n = nrows = ncols = args.plate_cnt*args.plate_size
assert args.layers % 3 == 0
return args
def asc2np(args, affix1):
a_gpw = read_gpw('{}.asc'.format(args.affix))
nrows2, ncols2 = np.shape(a_gpw)
assert np.shape(a_gpw)[0] > args.n
den = args.n/fractions.gcd(ncols2, args.n)
num = int(ncols2/fractions.gcd(ncols2, args.n))
a_2D_density = np.zeros((args.n, args.n))
a_2D_density_cnt = np.zeros((args.n, args.n))
print('converting NASA array to LEGO array')
for x1 in range(args.n):
print('gpw2LEGO', x1, args.n)
for y1 in range(args.n):
l = []
for x2 in range(num):
for y2 in range(num):
x3 = int((x1*num+x2)/den)
y3 = int((y1*num+y2)/den)
## a_2D_density[x1][y1] += a_gpw[x3][y3]
## a_2D_density[x1][y1] += a_gpw[x3][y3]
l.append(a_gpw[x3][y3])
if a_gpw[x3][y3] > 0:
a_2D_density_cnt[x1][y1] += 1
if l.count(0) >= 0 and sum(l) > 0:
if y1 == 65 and x1 > 95:
print(x1, y1, l.count(0), 'mean', sum(l)/len(l), 'max', max(l), sum(l), sum(sorted(l)[1:-1]), l)
a_2D_density[x1][y1] = max(l)
np.save(affix1, a_2D_density)
del a_gpw
del a_2D_density_cnt
return a_2D_density
def find_connected_exposed(
args, a_2D_density, a_2D_buried,
a_2D_mIDs, a_3D_dIDs):
print('find connected exposed plates and remaining buried plates')
a_3D_mIDs = np.zeros(np.shape(a_3D_dIDs), int)
a_3D_angle = np.zeros(np.shape(a_3D_dIDs), int)
gap = 'x'
## Use symbol for buried bricks instead of materialID,
## because surface exposed bricks/plates might have same color as
## buried bricks/plates.
buried = 'o'
for layer in reversed(range(args.layers)):
## build plates horizontally and vertically in each layer
if layer % 2 == 0:
irow = 0
jrow = 1
icol = 1
jcol = 0
pass
else:
irow = 1
jrow = 0
icol = 0
jcol = 1
pass
if layer % 3 == 2:
h = 3 # bricks
layer_insert = layer-2
layer_remove = (layer, layer-1)
max_len = 8 # 1x8 (3008) available in few colors
else:
h = 1 # plates
layer_insert = layer
layer_remove = ()
max_len = 8
## loop baseplates from North to South
for row1 in range(args.n//args.plate_size):
## loop baseplates from West to East
for col1 in range(args.n//args.plate_size):
for i in range(args.plate_size):
seq = []
for j in range(args.plate_size):
row = row1*args.plate_size + i*irow+j*jrow
col = col1*args.plate_size + i*icol+j*jcol
## Ocean or lake (or desert).
## Or position is above structure.
if layer >= a_2D_density[row][col]:
seq += [gap]
## Already filled.
elif a_3D_dIDs[layer][row][col] != 0:
seq += [gap]
## Buried.
elif layer < a_2D_buried[row][col]:
seq += [buried]
## Not inside Felix2001 GeoJSON polygon
## e.g. Spain and Saudi Arabia
elif a_2D_mIDs[row][col] == 0:
seq += [gap]
else:
seq += [int(a_2D_mIDs[row][col])]
## Continue loop over j.
continue
## No bricks along line.
if seq == args.plate_size*[gap]:
continue
## Same color for entire sequence.
if seq == args.plate_size*[seq[0]]:
pass
else:
seq = find_consecutive(args, seq, h, gap=gap, buried=buried)
append_designID_materialID_main(
args, seq, layer, i, irow, jrow, icol, jcol,
max_len, row1, col1,
a_3D_dIDs, a_3D_mIDs, a_3D_angle,
h, layer_insert, layer_remove,
gap, buried)
## Continue loop over i.
continue
## Continue col1 loop.
continue
## Continue row1 loop.
continue
## Continue layer loop.
continue
return a_3D_dIDs, a_3D_mIDs, a_3D_angle
def append_designID_materialID_main(
args, seq, layer, i, irow, jrow, icol, jcol, max_len, row1, col1,
a_3D_dIDs, a_3D_mIDs, a_3D_angle,
h, layer_insert, layer_remove, gap, buried):
width = 1
pos = 0
for materialID, g in itertools.groupby(seq):
## Get length of iterator.
len_group = len(list(g))
if materialID == gap:
pos += len_group
continue
## Get materialID of buried bricks/plates.
if materialID == buried:
materialID = materialID_buried
## 1x1 brick not available, but 1x1 plate available.
if h == 3 and materialID in d_NA[h][1][1] and materialID not in d_NA[1][1][1]:
## 1x1 plate if 1x1 brick not available
## e.g. cool yellow and spring yellowish green / unikitty green
h_group = 1
layer_ins = layer
layer_rem = ()
## 1x1 plate not available, but 1x1 brick available.
elif layer >= 1 and materialID in d_NA[h][1][1] and not materialID in d_NA[3][1][1]:
## 1x1 brick if 1x1 plate not available
## e.g. medium azure, medium lilac, dark pink, sand green
h_group = 3
layer_ins = layer-2
layer_rem = (layer, layer-1)
## 1x1 plate and 1x1 brick available.
else:
h_group = h
layer_ins = layer_insert
layer_rem = layer_remove
## What is the longest length of this color and size?
try:
max_len = min(8, d_max_len[h_group][width][materialID])
except KeyError:
for max_len in (8, 6, 4, 3, 2, 1):
if materialID in d_NA[h_group][width][max_len]:
continue
break
## How many plates of max length will fit?
## 1st call of sub routine.
for k in range(len_group//max_len):
for length in (max_len,):
designID = d_len2dIDs[h_group][width][length]
pos = append_designID_materialID_sub(
layer, designID, materialID,
a_3D_dIDs, a_3D_mIDs, a_3D_angle,
pos, i, irow, jrow, icol, jcol, length, width,
row1, col1, args,
layer_insert=layer_ins, layer_remove=layer_rem,
h=h_group)
## if a_3D_dIDs[3][127][113] == 3022 or a_3D_mIDs[3][127][113] == 330:
## stop3
## How much space left after filling with plates of max length?
mod = len_group % max_len
## No space left.
if mod == 0:
continue
assert max_len <= 8
if mod == 7:
if not any([
materialID in d_NA[h_group][width][4],
materialID in d_NA[h_group][width][3],
]):
lengths = (4, 3)
elif not materialID in d_NA[h_group][width][6]:
lengths = (6, 1)
elif not materialID in d_NA[h_group][width][4]:
lengths = (4, 2, 1)
elif not materialID in d_NA[h_group][width][3]:
lengths = (3, 2, 2)
else:
lengths = (2, 2, 2, 1)
elif mod == 5:
if not any([
materialID in d_NA[h_group][width][3],
materialID in d_NA[h_group][width][2],
]):
lengths = (3, 2)
elif not materialID in d_NA[h_group][width][4]:
lengths = (4, 1)
elif not materialID in d_NA[h_group][width][2]:
lengths = (2, 2, 1)
else:
lengths = (1, 1, 1, 1, 1)
else:
if mod > 1 and materialID in d_NA[h_group][width][mod]:
## 2, 4, 6
if mod not in (1, 3):
assert mod % 2 == 0
if not materialID in d_NA[h_group][width][mod]:
lengths = int(mod / 2) * (2,)
else:
lengths = int(mod / 1) * (1,)
## 1, 3
else:
lengths = mod * (1,)
else:
lengths = (mod,)
## 2nd call of sub routine.
for length in lengths:
designID = d_len2dIDs[h_group][width][length]
pos = append_designID_materialID_sub(
layer, designID, materialID,
a_3D_dIDs, a_3D_mIDs, a_3D_angle,
pos, i, irow, jrow, icol, jcol, length, width,
row1, col1, args,
layer_ins, layer_rem, h_group)
## if a_3D_dIDs[3][127][113] == 3022 or a_3D_mIDs[3][127][113] == 330:
## print(max_len, mod, lengths, length)
## stop2
## Continue loop over materialID groups.
continue
## if a_3D_dIDs[3][127][113] == 3022 or a_3D_mIDs[3][127][113] == 330:
## stop1
## if a_3D_dIDs[6][103][105] == 3007 or a_3D_mIDs[6][103][105] == 28: