-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmkdistmaps.js
1517 lines (1404 loc) · 56.4 KB
/
mkdistmaps.js
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
#!/usr/bin/env node
// mkdistmaps
// For each new release, update in package.json and create a new tag in GitHub - used in version string
// ls -m | sed ':a;N;$!ba;s/\n//g' | sed 's/ //g' >../files.txt
// Remove .geojson and move All_species,All_records, to the start
import fs from 'fs'
import { glob } from 'glob'
import path from 'path'
import csv from 'fast-csv'
import PImage from 'pureimage'
import { execSync } from 'child_process'
import moment from 'moment'
import rgbHex from 'rgb-hex'
import * as geotools2em from './geotools2em.js' // http://www.nearby.org.uk/tests/GeoTools2.html
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
let config = false
let SCALE = false
let usesGB = false
let usesIE = false
const dtStart = new Date()
const makeAllMapName = 'All records'
const makeAllSpeciesMapName = 'All species'
const GBletters1 = [
{ l: 'S', e: 0, n: 0 },
{ l: 'N', e: 0, n: 500 },
{ l: 'H', e: 0, n: 1000 },
{ l: 'T', e: 500, n: 0 }
]
const GBletters2 = [
{ l: 'A', e: 0, n: 400 },
{ l: 'B', e: 100, n: 400 },
{ l: 'C', e: 200, n: 400 },
{ l: 'D', e: 300, n: 400 },
{ l: 'E', e: 400, n: 400 },
{ l: 'F', e: 0, n: 300 },
{ l: 'G', e: 100, n: 300 },
{ l: 'H', e: 200, n: 300 },
{ l: 'J', e: 300, n: 300 },
{ l: 'K', e: 400, n: 300 },
{ l: 'L', e: 0, n: 200 },
{ l: 'M', e: 100, n: 200 },
{ l: 'N', e: 200, n: 200 },
{ l: 'O', e: 300, n: 200 },
{ l: 'P', e: 400, n: 200 },
{ l: 'Q', e: 0, n: 100 },
{ l: 'R', e: 100, n: 100 },
{ l: 'S', e: 200, n: 100 },
{ l: 'T', e: 300, n: 100 },
{ l: 'U', e: 400, n: 100 },
{ l: 'V', e: 0, n: 0 },
{ l: 'W', e: 100, n: 0 },
{ l: 'X', e: 200, n: 0 },
{ l: 'Y', e: 300, n: 0 },
{ l: 'Z', e: 400, n: 0 }
]
const IEletters = [
{ l: 'A', e: 0, n: 400 },
{ l: 'B', e: 100, n: 400 },
{ l: 'C', e: 200, n: 400 },
{ l: 'D', e: 300, n: 400 },
{ l: 'E', e: 400, n: 400 },
{ l: 'F', e: 0, n: 300 },
{ l: 'G', e: 100, n: 300 },
{ l: 'H', e: 200, n: 300 },
{ l: 'J', e: 300, n: 300 },
{ l: 'K', e: 400, n: 300 },
{ l: 'L', e: 0, n: 200 },
{ l: 'M', e: 100, n: 200 },
{ l: 'N', e: 200, n: 200 },
{ l: 'O', e: 300, n: 200 },
{ l: 'P', e: 400, n: 200 },
{ l: 'Q', e: 0, n: 100 },
{ l: 'R', e: 100, n: 100 },
{ l: 'S', e: 200, n: 100 },
{ l: 'T', e: 300, n: 100 },
{ l: 'U', e: 400, n: 100 },
{ l: 'V', e: 0, n: 0 },
{ l: 'W', e: 100, n: 0 },
{ l: 'X', e: 200, n: 0 },
{ l: 'Y', e: 300, n: 0 },
{ l: 'Z', e: 400, n: 0 }
]
const tetradletters = [
{ l: 'A', e: 0, n: 0 },
{ l: 'B', e: 0, n: 200 },
{ l: 'C', e: 0, n: 400 },
{ l: 'D', e: 0, n: 600 },
{ l: 'E', e: 0, n: 800 },
{ l: 'F', e: 200, n: 0 },
{ l: 'G', e: 200, n: 200 },
{ l: 'H', e: 200, n: 400 },
{ l: 'I', e: 200, n: 600 },
{ l: 'J', e: 200, n: 800 },
{ l: 'K', e: 400, n: 0 },
{ l: 'L', e: 400, n: 200 },
{ l: 'M', e: 400, n: 400 },
{ l: 'N', e: 400, n: 600 },
{ l: 'P', e: 400, n: 800 },
{ l: 'Q', e: 600, n: 0 },
{ l: 'R', e: 600, n: 200 },
{ l: 'S', e: 600, n: 400 },
{ l: 'T', e: 600, n: 600 },
{ l: 'U', e: 600, n: 800 },
{ l: 'V', e: 800, n: 0 },
{ l: 'W', e: 800, n: 200 },
{ l: 'X', e: 800, n: 400 },
{ l: 'Y', e: 800, n: 600 },
{ l: 'Z', e: 800, n: 800 }
]
const BOXSIZES = {
MONAD: 1,
TETRAD: 2,
HECTAD: 10,
ALL: 0
}
const monadSize = 1000
const tetradSize = 2000
const quadrantSize = 5000
const hectadSize = 10000
const hectadSCALE = {
smallBoxSize: hectadSize,
gridreffigs: 2
}
const tetradSCALE = {
smallBoxSize: tetradSize,
gridreffigs: 4
}
const monadSCALE = {
smallBoxSize: monadSize,
gridreffigs: 4
}
const translateFrom = []
const translateTo = []
const taxonLookup = []
let taxonLookupName = false
let taxonLookupExtra = false
let taxonLookupCurrent = false
const propertiesLookup = []
let propertiesLookupName = false
const speciesNotMatchedToProperties = []
// Get version from last git commit
const gitdescr = execSync('git describe --tags --long')
let version = 'mkdistmaps ' + gitdescr.toString('utf8', 0, gitdescr.length - 1) + ' - run at ' + moment().format('Do MMMM YYYY, h:mm:ss a')
/// ////////////////////////////////////////////////////////////////////////////////////
// run: called when run from command line
export async function run (argv) {
let rv = 1
try {
// Display usage
if (argv.length <= 2) {
console.error('usage: node mkdistmaps.js <config.json>')
return 0
}
console.log(version)
// Load config file and remove UTF-8 BOF and any comments starting with //
let configtext = fs.readFileSync(path.resolve(__dirname, argv[2]), { encoding: 'utf8' })
if (configtext.charCodeAt(0) === 65279) { // Remove UTF-8 start character
configtext = configtext.slice(1)
}
while (true) {
const dslashpos = configtext.indexOf('//')
if (dslashpos === -1) break
const endlinepos = configtext.indexOf('\n', dslashpos)
if (endlinepos === -1) {
configtext = configtext.substring(0, dslashpos)
break
}
configtext = configtext.substring(0, dslashpos) + configtext.substring(endlinepos)
}
// console.log(configtext)
try {
config = JSON.parse(configtext)
} catch (e) {
console.error('config file not in JSON format')
return 0
}
console.log(config)
if (typeof config === 'object' && 'versionoverride' in config) {
version = config.versionoverride
}
// Make output folder if need be
fs.mkdirSync(path.join(__dirname, config.outputFolder), { recursive: true })
// Set scale factor for hectad or monad
if (typeof config === 'object' && 'boxSize' in config) {
const boxsize = config.boxSize.toLowerCase()
if (boxsize === 'all') config.boxSize = BOXSIZES.ALL
else if (boxsize === 'monad') config.boxSize = BOXSIZES.MONAD
else if (boxsize === 'tetrad') config.boxSize = BOXSIZES.TETRAD
else if (boxsize === 'hectad') config.boxSize = BOXSIZES.HECTAD
else {
console.error('unrecognised config.boxSize', config.boxSize)
return 0
}
} else if (typeof config === 'object' && 'useMonadsNotHectads' in config) {
config.boxSize = config.useMonadsNotHectads ? BOXSIZES.MONAD : BOXSIZES.HECTAD
} else {
console.log('Using default: map to hectad')
config.boxSize = BOXSIZES.HECTAD
}
switch (config.boxSize) {
case BOXSIZES.ALL:
case BOXSIZES.MONAD: SCALE = monadSCALE; break
case BOXSIZES.TETRAD: SCALE = tetradSCALE; break
case BOXSIZES.HECTAD: SCALE = hectadSCALE; break
}
// SCALE = (config.boxSize === BOXSIZES.HECTAD) ? hectadSCALE : ((config.boxSize === BOXSIZES.TETRAD) ? tetradSCALE : monadSCALE)
// Default makeGenusMaps to false
if (!(typeof config === 'object' && 'makeGenusMaps' in config)) {
config.makeGenusMaps = false
}
// Default outputtype to 'map'
if (!(typeof config === 'object' && 'outputtype' in config)) {
config.outputtype = 'map'
}
// Default maptype to 'date'
if (!(typeof config === 'object' && 'maptype' in config)) {
config.maptype = 'date'
}
// Default makeAllMap to false
if (!(typeof config === 'object' && 'makeAllMap' in config)) {
config.makeAllMap = false
}
// Default geojsonprecision to false
if (!(typeof config === 'object' && 'geojsonprecision' in config)) {
config.geojsonprecision = false
}
// Default taxon to false
if (!(typeof config === 'object' && 'taxon' in config)) {
config.taxon = false
}
// Default onlysaveifinproperties to false
if (!(typeof config === 'object' && 'onlysaveifinproperties' in config)) {
config.onlysaveifinproperties = false
}
// Default saveallproperties to false
if (!(typeof config === 'object' && 'saveallproperties' in config)) {
config.saveallproperties = false
}
// Default saveSpacesAs to false
if (!(typeof config === 'object' && 'saveSpacesAs' in config)) {
config.saveSpacesAs = false
}
// If maptype is count and makeAllMap then make "All species" map
config.makeAllSpeciesMap = config.maptype === 'count' && config.makeAllMap
// Set default datecolours if need be
if (!(typeof config === 'object' && 'datecolours' in config)) {
console.log('Using default datecolours')
config.datecolours = [
{ minyear: 0, maxyear: 1959, colour: 'rgba(255,255,0, 1)', legend: 'pre-1960' }, // Yellow
{ minyear: 1960, maxyear: 1999, colour: 'rgba(0,0,255, 1)', legend: '1960-1999' }, // Blue
{ minyear: 2000, maxyear: 2019, colour: 'rgba(255,0,0, 1)', legend: '2000-2019' }, // Red
{ minyear: 2020, maxyear: 2039, colour: 'rgba(0,255,0, 1)', legend: '2020-2039' } // Green
]
}
// Set default countcolours if need be
if (!(typeof config === 'object' && 'countcolours' in config)) {
console.log('Using default countcolours')
config.countcolours = [
{ min: 1, max: '1%', colour: 'rgba(0,255,0, 1)', legend: '' }, // Green
{ min: '1%', max: '10%', colour: 'rgba(0,0,255, 1)', legend: '' }, // Blue
{ min: '10%', max: '50%', colour: 'rgba(0,0,0, 1)', legend: '' }, // Black
{ min: '50%', max: '100%', colour: 'rgba(255,0,0, 1)', legend: '' } // Red
]
}
if (!config.recordset) {
console.error('No recordset config given')
return 0
}
// Set default DateFormats if need be
if (!config.recordset.DateFormats) {
console.log('Using default DateFormats')
config.recordset.DateFormats = ['DD/MM/YYYY', 'YYYY']
}
// Set default CSV encoding if need be
if (!config.recordset.encoding) {
config.recordset.encoding = 'utf8'
}
// delimiter must be a single character
if (!config.recordset.delimiter) {
config.recordset.delimiter = ','
}
if (!config.font_colour) {
console.log('Using default font_colour')
config.font_colour = '#000000'
}
if (!config.basemap) {
console.error('No basemap config given')
return 0
}
if (!config.basemap.file) {
console.error('No basemap file given')
return 0
}
config.basemap.filelc = config.basemap.file.toLowerCase()
config.basemap.isPNG = config.basemap.filelc.indexOf('.png') !== -1
config.basemap.isJPG = (config.basemap.filelc.indexOf('.jpg') !== -1) || (config.basemap.filelc.indexOf('.jpeg') !== -1)
if (!config.basemap.isPNG && !config.basemap.isJPG) {
console.error('Basemap file must be PNG or JPG -', config.basemap.file)
return 0
}
if (!fs.existsSync(config.basemap.file)) {
console.error('Basemap file does not exist -', config.basemap.file)
return 0
}
if (!config.basemap.title_x) config.basemap.title_x = 10
if (!config.basemap.title_y) config.basemap.title_y = 30
if (!config.basemap.title_y_inc) config.basemap.title_y_inc = 25
if (!config.basemap.title_fontsize) config.basemap.title_fontsize = '24pt'
if (!config.basemap.legend_x) config.basemap.legend_x = 10
if (!config.basemap.legend_x) config.basemap.legend_x = 10
// config.basemap.legend_y later defaulted to half map height
if (!config.basemap.legend_inc) config.basemap.legend_inc = 15
if (!config.basemap.legend_fontsize) config.basemap.legend_fontsize = '12pt'
if (!config.basemap.hectad_fontsize) config.basemap.hectad_fontsize = '12pt'
/// //////////////
if (config.recordset.translate) {
const opts = config.recordset.translate.split(',')
if (opts.length !== 3) {
console.error('recordset.translate must have 3 fields')
return 0
}
const translatecsv = opts[0]
const oldnamecol = opts[1]
const newnamecol = opts[2]
if (!fs.existsSync(translatecsv)) {
console.error('recordset.translate CSV does not exist -', translatecsv)
return 0
}
console.log('Reading: ', translatecsv)
const readTranslate = new Promise((resolve, reject) => {
fs.createReadStream(path.resolve(__dirname, translatecsv), { encoding: config.recordset.encoding })
.pipe(csv.parse({ headers: true }))
.on('data', row => {
const from = row[oldnamecol]
const to = row[newnamecol]
if (from.length > 0 && to.length > 0 && (from !== to)) {
translateFrom.push(from)
translateTo.push(to)
}
})
.on('end', function (rowCount) {
resolve()
})
})
await readTranslate
}
/// //////////////
// Read optional taxon lookups
if (config.taxon && ('csv' in config.taxon) && ('lookup' in config.taxon) && ('extra' in config.taxon)) {
taxonLookupName = config.taxon.lookup
taxonLookupExtra = config.taxon.extra
taxonLookupCurrent = config.taxon.current
const readTaxons = new Promise((resolve, reject) => {
fs.createReadStream(path.resolve(__dirname, config.taxon.csv), { encoding: 'utf8' })
.pipe(csv.parse({ headers: true }))
.on('data', row => {
taxonLookup.push(row)
})
.on('end', function (rowCount) {
resolve()
})
})
await readTaxons
for (const taxon of taxonLookup) {
let extra = taxon[taxonLookupExtra].trim()
if (extra === '0') extra = ''
taxon[taxonLookupExtra] = extra
if (extra === 'LC') extra = ''
const lcpos = extra.indexOf('LC ')
if (lcpos !== -1) extra = extra.substring(0, lcpos) + extra.substring(lcpos + 3)
taxon[taxonLookupExtra + 'nolc'] = extra // without LC
if (taxon[taxonLookupName] === taxon[taxonLookupCurrent]) taxon[taxonLookupCurrent] = ''
}
console.log('Read taxon lookup: ', taxonLookup.length)
if (!taxonLookupName || !taxonLookupExtra || !taxonLookupCurrent) {
console.log('Incomplete taxon setup')
taxonLookup.length = 0 // Clear array
}
}
/// //////////////
// Read optional properties lookups
const englishlookups = []
let anyerrors = false
if (config.properties && ('csv' in config.properties) && ('lookup' in config.properties)) {
const englishlookup = 'englishlookup' in config.properties ? config.properties.englishlookup : false
propertiesLookupName = config.properties.lookup
const readProperties = new Promise((resolve, reject) => {
fs.createReadStream(path.resolve(__dirname, config.properties.csv), { encoding: 'utf8' })
.pipe(csv.parse({ headers: true }))
.on('data', row => {
if (propertiesLookupName in row) {
const taxon = row[propertiesLookupName].trim()
row[propertiesLookupName] = taxon
if (taxon) {
row.found = false
if (propertiesLookup.findIndex((r) => r[propertiesLookupName] === taxon) !== -1) {
console.error('Duplicate properties taxon', taxon)
anyerrors = true
return
}
propertiesLookup.push(row)
if (englishlookup) {
if (englishlookup in row) {
const english = row[englishlookup]
if (english && english.trim().length > 0) {
englishlookups.push({ english: english.trim(), taxon, found: false })
}
}
}
}
}
})
.on('end', function (rowCount) {
resolve()
})
})
await readProperties
if (anyerrors) {
console.log('Please fix these issues and try again')
return 0
}
}
/// //////////////
// Do everything! One CSV file at a time.
const headers = config.recordset.headers ? config.recordset.headers : true
const renameHeaders = config.recordset.renameHeaders ? config.recordset.renameHeaders : false
let totalrecords = 0
const processFiles = new Promise((resolve, reject) => {
async function doAll () {
const files = glob.sync(config.recordset.csv)
if (files.length === 0) {
console.error('NO FILE(S) FOUND FOR: ', config.recordset.csv)
rv = 0
} else {
const doFiles = new Promise((_resolve, _reject) => {
async function asyncDoFiles () {
// console.log('asyncDoFiles',files.length)
for (const file of Object.values(files)) {
console.log(file)
const processFile = new Promise((__resolve, __reject) => { // eslint-disable-line promise/param-names
const fileSpecieses = []
fs.createReadStream(path.resolve(__dirname, file), { encoding: config.recordset.encoding })
.pipe(csv.parse({ headers, renameHeaders, delimiter: config.recordset.delimiter }))
.on('error', error => console.error(error))
.on('data', row => { processLine(file, row, fileSpecieses) })
.on('end', function (rowCount) {
if (Object.keys(fileSpecieses).length === 0) {
errors.push(file + ' no species found')
}
console.log(file, 'species:', Object.keys(fileSpecieses).length)
totalrecords += rowCount
__resolve() // processFile
})
})
await processFile
console.log('DONE', file)
}
_resolve() // doFiles
}
asyncDoFiles()
})
await doFiles
console.log('COMPLETED READING DATA')
await importComplete(totalrecords)
}
resolve() // processFiles
}
doAll()
})
await processFiles
if (englishlookups.length > 0) {
englishlookups.sort((a, b) => a.english.localeCompare(b.english))
for (const [MapName] of Object.entries(speciesesGrids)) {
const el = englishlookups.find(el => el.taxon === MapName)
if (el) el.found = true
}
let allenglishlookups = ''
for (const el of englishlookups) {
if (el.found) allenglishlookups += el.english + ':' + el.taxon + ';'
}
console.log('allenglishlookups', allenglishlookups)
const saveFilename = 'english.txt'
const outpath = path.join(__dirname, config.outputFolder, saveFilename)
const writeEnglishLookups = new Promise((resolve, reject) => {
const stream = fs.createWriteStream(outpath)
stream.on('close', function (fd) {
resolve()
})
stream.on('open', function (fd) {
stream.write(allenglishlookups)
stream.end()
console.log('Written english to ', outpath)
})
})
await writeEnglishLookups
}
if (rv) console.log('SUCCESS')
return 1
} catch (e) {
console.error('run EXCEPTION', e)
return 2
}
}
/// ////////////////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////////////
const charcode0 = '0'.charCodeAt(0)
const charcode9 = '9'.charCodeAt(0)
// notNumeric: return true if any characters in string in given range are not numeric
function notNumeric (box, from, to) {
const str = box.substring(from, to)
for (let i = 0; i < str.length; i++) {
const ich = str.charCodeAt(i)
if (ich < charcode0 || ich > charcode9) {
errors.push('Spatial Reference duff characters: ' + box)
return true
}
}
return false
}
// getGRtype: return various attributes of the given 'box' grid reference
// A10, A10V, A1234, A12NE, NY10, NY10X, NY1234, NY57NE
function getGRtype (box) {
const rv = { isHectad: false, isQuadrant: false, isTetrad: false, isMonad: false, isIE: false, boxfull: box }
const len = box.length
const char2 = box.charCodeAt(1)
const char2isdigit = char2 >= charcode0 && char2 <= charcode9
const lastchar = box.charCodeAt(len - 1)
const lastcharisdigit = lastchar >= charcode0 && lastchar <= charcode9
if (!lastcharisdigit) {
if ((len === 5 && char2isdigit) || len === 6) {
const lasttwo = box.substring(len - 2)
if (lasttwo === 'NE' || lasttwo === 'NW' || lasttwo === 'SE' || lasttwo === 'SW') {
rv.isQuadrant = true
let bf = box.substring(0, len - 3)
bf += ((lasttwo === 'NE' || lasttwo === 'SE')) ? '5' : '0'
bf += box.substring(3, 4)
bf += ((lasttwo === 'NE' || lasttwo === 'NW')) ? '5' : '0'
rv.boxfull = bf
// console.log('getGRtype', box, bf)
return rv
} else throw new Error('Bad quadrant letters ' + lasttwo)
}
const tetradchar = box.substring(len - 1)
const boxbl = tetradletters.find(boxbl2 => { return boxbl2.l === tetradchar })
if (!boxbl) throw new Error('Tetrad letter not found ' + tetradchar)
rv.boxfull = box.substring(0, len - 2) + (boxbl.e / 100) + box.substring(len - 2, len - 1) + (boxbl.n / 100)
}
switch (box.length) {
case 3:
rv.isIE = true
rv.isHectad = true
break
case 4:
if (lastcharisdigit) {
rv.isHectad = true
} else {
rv.isIE = true
rv.isTetrad = true
}
break
case 5:
if (!lastcharisdigit) {
rv.isTetrad = true
} else {
rv.isMonad = true
rv.isIE = true
}
break
case 6:
rv.isMonad = true
break
default:
throw new Error('getGRtype duff box', box)
}
return rv
}
// updateSpeciesesGrids: Update the data for a species or genus
// 'Spatial Reference': 'NY30', Eastings: '330001', Northings: '500000',
// 'Spatial Reference': 'NY3703', Eastings: '337001', Northings: '503000',
// 'Spatial Reference': 'NY387034', Eastings: '338701', Northings: '503400',
// NY48311327 348311 513270
// NY50951510 Some 12 figure GRs appear as 10 figures
// NY7432046814
// J3438674590 334386 374590
// 17646.6931-370000 0-467252
const speciesesGrids = {} // gets a prop for each map generated with value object having per-map boxes etc
let speciesCount = 0
let genusCount = 0
let allCount = 0
const errors = []
let lineno = 0
let records = 0
let empties = 0
const boxes = {} // gets a prop for each square, eg A10, NY51, and SD23L or NC1234
let excluded = 0
let included = 0
function updateSpeciesesGrids(TaxonName, box, Year, DateOrRange, isGenus, fileSpecieses, inTotal, makeAllSpeciesMapTaxon, MoreInfo) {
// console.log('updateSpeciesesGrids', TaxonName, box, MoreInfo)
if (isGenus) TaxonName += ' -all'
let speciesGrids = speciesesGrids[TaxonName]
if (!speciesGrids) {
speciesGrids = { max: 0, speciesmax: 0, boxes: {} }
speciesGrids.boxes[box] = { count: 0, minyear: 3000, maxyear: 0, species: [], range: null }
speciesesGrids[TaxonName] = speciesGrids
if (inTotal) {
if (isGenus) genusCount++
else speciesCount++
} else {
allCount++
}
}
if (!speciesGrids.boxes[box]) {
speciesGrids.boxes[box] = { count: 0, minyear: 3000, maxyear: 0, species: [], moreinfo: false }
}
if (MoreInfo) {
if (!speciesGrids.boxes[box].moreinfo) speciesGrids.boxes[box].moreinfo = [MoreInfo]
else {
const found = speciesGrids.boxes[box].moreinfo.find(mi => mi == MoreInfo) // eslint-disable-line eqeqeq
if (!found) {
speciesGrids.boxes[box].moreinfo.push(MoreInfo)
}
}
}
speciesGrids.boxes[box].count++
if (speciesGrids.boxes[box].count > speciesGrids.max) {
speciesGrids.max = speciesGrids.boxes[box].count
}
if (Year > speciesGrids.boxes[box].maxyear) {
speciesGrids.boxes[box].maxyear = Year
}
if (Year < speciesGrids.boxes[box].minyear) {
speciesGrids.boxes[box].minyear = Year
}
if (DateOrRange && (DateOrRange.substring(4, 7) === ' - ')) {
speciesGrids.boxes[box].range = DateOrRange
}
// Now remember per-file counts
if (!fileSpecieses[TaxonName]) {
fileSpecieses[TaxonName] = 0
}
fileSpecieses[TaxonName]++
// Remember what species found in "All species" map boxes
if (makeAllSpeciesMapTaxon) {
if (!speciesGrids.boxes[box].species.includes(makeAllSpeciesMapTaxon)) {
speciesGrids.boxes[box].species.push(makeAllSpeciesMapTaxon)
const totalspecies = speciesGrids.boxes[box].species.length
speciesGrids.boxes[box].count = totalspecies
if (totalspecies > speciesGrids.speciesmax) {
speciesGrids.speciesmax = totalspecies
}
}
}
}
// processLine: Process a line of CSV data ie a single record
function processLine (file, row, fileSpecieses) {
// console.log(row)
lineno++
// Get GR (no spaces) and species name
if (!(config.recordset.GRCol in row)) {
errors.push('Grid reference not found in: ' + JSON.stringify(row))
return
}
const SpatialReference = row[config.recordset.GRCol].toUpperCase().replace(/ /g, '')
let TaxonName = row[config.recordset.TaxonCol].trim()
if (SpatialReference.length === 0 || TaxonName.length === 0 || TaxonName.substring(0, 1) === '#') {
empties++
// console.log("Empty", records, JSON.stringify(row))
return
}
if (translateFrom.length > 0) {
const fromix = translateFrom.indexOf(TaxonName)
if (fromix !== -1) {
TaxonName = translateTo[fromix]
}
}
function taxonmatchbasicwildcard (v) {
// console.log(TaxonName, v)
// console.log(TaxonName.substring(0, v.length - 1), v.substring(0, v.length - 1))
// console.log(TaxonName.substring(v.length - 1), v.substring(v.length - 1))
// exit
if (v.endsWith('*')) { if (TaxonName.substring(0, v.length - 1) === v.substring(0, v.length - 1)) return true }
if (v.startsWith('*')) { if (TaxonName.substring(v.length - 1) === v.substring(v.length - 1)) return true }
}
if (config.excludes) {
if (config.excludes.find(taxonmatchbasicwildcard)) {
excluded++
return
}
included++
}
if (config.includes) {
if (!config.includes.find(taxonmatchbasicwildcard)) {
excluded++
return
}
included++
}
records++
// Get other data fields
const EastingsExplicit = parseInt(row.Eastings)
const NorthingsExplicit = parseInt(row.Northings)
const ExplicitGiven = EastingsExplicit !== 0 || NorthingsExplicit !== 0
let ObsKey = row[config.recordset.ObsKeyCol]
const ObsDate = row[config.recordset.DateCol]
let Year = parseInt(row[config.recordset.YearCol])
let MoreInfo = false
if ('MoreInfo' in config.recordset) MoreInfo = row[config.recordset.MoreInfo]
if (MoreInfo && config.recordset.FixForBLS) {
if (MoreInfo == 'BLS Mapping Scheme: Britain 2009') MoreInfo = false // eslint-disable-line eqeqeq
else if (MoreInfo.startsWith('VC')) {
let ch6 = MoreInfo.charAt(5)
if (ch6 === 'a' || ch6 === 'c') MoreInfo = MoreInfo.substring(0, 5) + MoreInfo.substring(6) // Remove c from "VC 01c" - and same for a
ch6 = MoreInfo.charAt(5)
if (ch6 === 'a' || ch6 === 'c') MoreInfo = MoreInfo.substring(0, 5) + MoreInfo.substring(6) // Remove c from "VC 01c" - and same for a
}
}
// console.log('----------')
// console.log('SpatialReference', SpatialReference)
// console.log('EastingsExplicit', EastingsExplicit)
// console.log('NorthingsExplicit', NorthingsExplicit)
// console.log('TaxonName', TaxonName, TaxonName.length)
// console.log('MoreInfo', MoreInfo, MoreInfo.length)
// console.log('ObsDate', ObsDate)
if (!ObsKey) ObsKey = 'Line#' + lineno
// Decode Date or Year
let YearFound = Year
if (!YearFound || !config.recordset.YearCol) {
const ObsDate2 = moment(ObsDate, config.recordset.DateFormats)
if (ObsDate2.isValid()) {
YearFound = true
Year = ObsDate2.year()
}
}
if (!YearFound) {
errors.push(ObsKey + ' Date invalid:' + ObsDate + ' Year:' + Year)
return
}
let DateOrRange = null
if (config.recordset.DateOrRangeCol) {
DateOrRange = row[config.recordset.DateOrRangeCol] // May still be null
}
// From grid reference, work out Eastings and Northings and box name eg NY51 or NY5714
let Eastings = 0
let Northings = 0
let isGB = false
let isIE = false
let box = SpatialReference
const grfig = SCALE.gridreffigs / 2
if (box.length === 12) { // ALL-OK
if (notNumeric(box, 2)) return
Eastings += parseInt(box.substring(2, 7))
Northings += parseInt(box.substring(7))
box = box.substring(0, 2 + grfig) + box.substring(7, 7 + grfig)
isGB = true
} else if (box.length === 10) { // ALL-OK
if (notNumeric(box, 2)) return
Eastings += parseInt(box.substring(2, 6)) * 10
Northings += parseInt(box.substring(6)) * 10
box = box.substring(0, 2 + grfig) + box.substring(6, 6 + grfig)
isGB = true
} else if (box.length === 8) { // ALL-OK
if (notNumeric(box, 2)) return
Eastings += parseInt(box.substring(2, 5)) * 100
Northings += parseInt(box.substring(5)) * 100
box = box.substring(0, 2 + grfig) + box.substring(5, 5 + grfig)
isGB = true
} else if (box.length === 6) { // ALL-OK
const lasttwochars = box.substring(4, 6)
const quadrantnw = lasttwochars === 'NW'
const quadrantsw = lasttwochars === 'SW'
const quadrantse = lasttwochars === 'SE'
const quadrantne = lasttwochars === 'NE'
if (quadrantnw || quadrantsw || quadrantse || quadrantne) {
// console.log('lasttwochars', box, lasttwochars, quadrantnw, quadrantsw, quadrantse, quadrantne)
if (notNumeric(box, 2, 4)) return
Eastings += parseInt(box.substring(2, 3)) * 10000
Northings += parseInt(box.substring(3)) * 10000
if (quadrantne || quadrantse) Eastings += 5000
if (quadrantne || quadrantnw) Northings += 5000
// box = box.substring(0, 4) JUST LEAVE AS NY56SW
} else {
if (notNumeric(box, 2)) return
Eastings += parseInt(box.substring(2, 4)) * 1000
Northings += parseInt(box.substring(4)) * 1000
box = box.substring(0, 2 + grfig) + box.substring(4, 4 + grfig)
}
isGB = true
} else if (box.length === 4) { // ALL-OK-GB
const tetradchar = box.substring(3).toUpperCase()
if (tetradchar.match(/[A-Z]/)) {
if (tetradchar === 'O') { errors.push(ObsKey + ' duff tetrad letter: ' + tetradchar + ': ' + SpatialReference); return }
if (notNumeric(box, 1, 3)) return
Eastings += parseInt(box.substring(1, 2)) * 10000
Northings += parseInt(box.substring(2)) * 10000
const boxbl = tetradletters.find(boxbl2 => { return boxbl2.l === tetradchar })
if (!boxbl) { errors.push(ObsKey + ' duff tetrad letter: ' + tetradchar + ': ' + SpatialReference); return }
Eastings += boxbl.e * 10
Northings += boxbl.n * 10
isIE = true
if (config.boxSize !== BOXSIZES.TETRAD) { // If not showing tetrads then convert to show at hectad level
box = box.substring(0, 3)
Eastings = Math.floor(Eastings / 10000) * 10000
Northings = Math.floor(Northings / 10000) * 10000
}
} else {
if (notNumeric(box, 2)) return
Eastings += parseInt(box.substring(2, 3)) * 10000
Northings += parseInt(box.substring(3)) * 10000
isGB = true
}
} else if (box.length === 11) { // IRISH
if (notNumeric(box, 1)) return
Eastings += parseInt(box.substring(1, 6))
Northings += parseInt(box.substring(6))
box = box.substring(0, 1 + grfig) + box.substring(6, 6 + grfig)
isIE = true
} else if (box.length === 9) { // IRISH
if (notNumeric(box, 1)) return
Eastings += parseInt(box.substring(1, 5)) * 10
Northings += parseInt(box.substring(5)) * 10
box = box.substring(0, 1 + grfig) + box.substring(5, 5 + grfig)
isIE = true
} else if (box.length === 7) { // IRISH
if (notNumeric(box, 1)) return
Eastings += parseInt(box.substring(1, 4)) * 100
Northings += parseInt(box.substring(4)) * 100
box = box.substring(0, 1 + grfig) + box.substring(4, 4 + grfig)
isIE = true
} else if (box.length === 5) { // CHECK
const tetradchar = box.substring(4).toUpperCase()
if (tetradchar.match(/[A-Z]/)) {
if (tetradchar === 'O') { errors.push(ObsKey + ' duff tetrad letter: ' + tetradchar + ': ' + SpatialReference); return }
if (notNumeric(box, 2, 4)) return
Eastings += parseInt(box.substring(2, 3)) * 10000
Northings += parseInt(box.substring(3)) * 10000
const boxbl = tetradletters.find(boxbl2 => { return boxbl2.l === tetradchar })
if (!boxbl) { errors.push(ObsKey + ' duff tetrad letter: ' + tetradchar + ': ' + SpatialReference); return }
Eastings += boxbl.e * 10
Northings += boxbl.n * 10
isGB = true
if ((config.boxSize !== BOXSIZES.ALL) &&
(config.boxSize !== BOXSIZES.TETRAD)) { // If not showing tetrads then convert to show at hectad level
box = box.substring(0, 4)
Eastings = Math.floor(Eastings / 10000) * 10000
Northings = Math.floor(Northings / 10000) * 10000
}
} else {
if (notNumeric(box, 1)) return
Eastings += parseInt(box.substring(1, 3)) * 1000
Northings += parseInt(box.substring(3)) * 1000
box = box.substring(0, 1 + grfig) + box.substring(3, 3 + grfig)
isIE = true
}
} else if (box.length === 3) { // IRISH
if (notNumeric(box, 1)) return
Eastings += parseInt(box.substring(1, 2)) * 10000
Northings += parseInt(box.substring(2)) * 10000
isIE = true
} else {
errors.push(ObsKey + ' Spatial Reference duff length: ' + box.length + ': ' + SpatialReference)
return
}
if ((usesGB && isIE) || (usesIE && isGB)) {
errors.push(ObsKey + ' Cannot use GB and IE grid references: ' + SpatialReference)
return
}
if (isGB) usesGB = true
if (isIE) usesIE = true
// console.log('box', SpatialReference.padEnd(12), box.padEnd(12), Eastings.toString().padStart(5, '0'), Northings.toString().padStart(5, '0'))
const l1 = box.substring(0, 1)
if (isGB) {
for (const boxbl of GBletters1) {
if (boxbl.l === l1) {
Eastings += boxbl.e * 1000
Northings += boxbl.n * 1000
break
}
}
const l2 = box.substring(1, 2)
for (const boxbl of GBletters2) {
if (boxbl.l === l2) {
Eastings += boxbl.e * 1000
Northings += boxbl.n * 1000
break
}
}
} else {
for (const boxbl of IEletters) {
if (boxbl.l === l1) {
Eastings += boxbl.e * 1000
Northings += boxbl.n * 1000
break
}
}
}
if (config.boxSize === BOXSIZES.TETRAD) { // If a monad, convert to tetrad form if need be
const isMonad = (isGB && box.length === 6) || (isIE && box.length === 5)
// const isTetrad = (isGB && box.length === 5) || (isIE && box.length === 4)
if (isMonad) { // ie monad NY3329 or A1234
const ebit = (Eastings % 10000) / 1000
const nbit = (Northings % 10000) / 1000
let tetradletter = Math.floor(nbit / 2)
if (ebit < 2) tetradletter += 0
else if (ebit < 4) tetradletter += 5
else if (ebit < 6) tetradletter += 10
else if (ebit < 8) tetradletter += 15
else tetradletter += 20
tetradletter = tetradletters[tetradletter].l
if (isGB) {
box = box.substring(0, 3) + box.substring(4, 5) + tetradletter
} else {
box = box.substring(0, 2) + box.substring(3, 4) + tetradletter
}
}
}
// console.log(SpatialReference, box, Eastings, Northings, EastingsExplicit, NorthingsExplicit)
if (ExplicitGiven) {
if ((Math.abs(Eastings - EastingsExplicit) > 2) || (Math.abs(Northings - NorthingsExplicit) > 2)) {
errors.push(ObsKey + ' Explicit grid ref discrepancy: ' + SpatialReference + ' ExpE:' + EastingsExplicit + ' ExpN:' + NorthingsExplicit + ' E:' + Eastings + ' N:' + Northings)
return
}
}
// Save box name and location
if (!boxes[box]) {
const boxloc = {
e: Math.floor(Eastings / 1000),
n: Math.floor(Northings / 1000)
}
if (config.boxSize === BOXSIZES.HECTAD) {
boxloc.e = Math.floor(boxloc.e / 10) * 10
boxloc.n = Math.floor(boxloc.n / 10) * 10
}
if (config.boxSize === BOXSIZES.TETRAD) {