-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
363 lines (325 loc) · 11.4 KB
/
index.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
const fs = require('fs').promises
const _ = require('lodash')
const Papa = require('papaparse')
const moment = require('moment')
const GeoJsonGeometriesLookup = require('geojson-geometries-lookup');
function removeSpuh (arr) {
const newArr = []
for (var i in arr) {
// TODO Mixed results comparing MyEBirdData and Audio and Video data
if (arr[i]['Scientific Name'] &&
!arr[i]['Scientific Name'].includes('sp.') &&
!arr[i]['Scientific Name'].includes(' x ') && // Get rid of hybrids
!arr[i]['Scientific Name'].includes('Domestic type') && // Get rid of Domestic types
!arr[i]['Scientific Name'].split(' ').slice(0, 2).join(' ').includes('/') // No Genus-level splits
// !arr[i]['Scientific Name'].includes('[') &&
// !arr[i]['Scientific Name'].match(/.* .* .*/g) &&
// !arr[i]['Scientific Name'].includes('/')
) {
// Remove subspecies only entries
const specie = arr[i]
specie['Scientific Name'] = specie['Scientific Name'].split(' ').slice(0, 2).join(' ')
newArr.push(arr[i])
} else {
// Use this to find excluded entries
// console.log(arr[i]['Scientific Name'])
}
}
return _.uniq(newArr)
}
async function getData (input) {
let data = await fs.readFile(input, 'utf8')
data = Papa.parse(data, { header: true })
return removeSpuh(data.data)
}
function parseDateformat (timespan) {
let dateFormat
if (timespan === 'year') {
dateFormat = 'YYYY'
} else if (timespan === 'month') {
dateFormat = 'YYYY-MM'
} else if (timespan === 'day') {
dateFormat = 'YYYY-MM-DD'
} else if (timespan) {
throw new Error('Unable to parse timespan. Must be: year, month, or day.')
}
return dateFormat
}
function momentFormat (dateStr) {
if (dateStr.includes('-')) {
return 'YYYY-MM-DD'
} else if (dateStr.includes('/')) {
return 'MM/DD/YYYY'
} else {
throw new Error('Invalid Date String')
}
}
function createPeriodArray (data) {
const periodArray = []
for (const period in data) {
periodArray.push({
Date: period,
SpeciesTotal: removeSpuh(_.uniqBy(data[period], 'Scientific Name')).length,
Species: removeSpuh(_.uniqBy(data[period], 'Scientific Name'))
})
}
return _.sortBy(periodArray, 'SpeciesTotal').reverse()
}
function locationFilter (list, opts) {
// TODO Make State and Country and County and Town work
if (!opts.state) {
return list
}
return list.filter(x => {
// TODO Add a mapping from Vermont to US-VT, for all states and provinces
if (x["State/Province"] === 'US-VT') {
x.State = 'Vermont'
}
if (x.State) {
return x.State === opts.state
}
})
}
function dateFilter (list, opts) {
// TODO Make month and day work
if (!opts.year) {
return list
}
return list.filter(x => {
return moment(x.Date, momentFormat(x.Date)).format('YYYY') === opts.year
})
}
function orderByDate (arr) {
return _.orderBy(arr, (e) => moment(e.Date, momentFormat(e.Date)).format())
}
async function biggestTime (timespan, opts) {
const dateFormat = parseDateformat(timespan)
const data = await getData(opts.input)
const dataByDate = {}
// Sort by the amount of unique entries per day
data.forEach((e) => {
const period = moment(e.Date, momentFormat(e.Date)).format(dateFormat)
if (!dataByDate[period]) {
dataByDate[period] = [e]
} else {
dataByDate[period].push(e)
}
})
return createPeriodArray(dataByDate)[0]
}
async function firstTimes (timespan, opts) {
const dateFormat = parseDateformat(timespan)
const data = orderByDate(await getData(opts.input)) // Sort by the date, instead
const dataByDate = {}
const speciesIndex = {}
// Sort by the amount of unique entries per day
data.forEach((e) => {
const period = moment(e.Date, momentFormat(e.Date)).format(dateFormat)
if (!speciesIndex[e['Scientific Name']]) {
if (!dataByDate[period]) {
dataByDate[period] = [e]
} else {
dataByDate[period].push(e)
}
// TODO Use scientific name
speciesIndex[e['Scientific Name']] = e.Date
}
})
return createPeriodArray(dataByDate)[0]
}
async function firstTimeList (opts) {
const dateFormat = parseDateformat('day')
const data = orderByDate(dateFilter(locationFilter(await getData(opts.input), opts), opts))
const dataByDate = {}
const speciesIndex = {}
data = countUniqueSpecies(data)
let i = 1
// TODO Doesn't work for MyEBirdData for some reason
_.sortBy(createPeriodArray(dataByDate), 'Date').forEach((e) => {
e.Species.forEach((specie) => {
console.log(`${i} | ${specie['Common Name']} - ${specie['Scientific Name']} | ${(specie.County) ? specie.County + ', ' : ''}${specie['State/Province']} | ${e.Date}`)
i++
})
})
}
// Sort by the amount of unique entries per day
function countUniqueSpecies (data, dateFormat) {
const speciesIndex = {}
const dataByDate = {}
data.forEach((e) => {
const period = moment(e.Date, momentFormat(e.Date)).format(dateFormat)
const specie = e['Scientific Name']
if (!speciesIndex[specie]) {
if (!dataByDate[period]) {
dataByDate[period] = [e]
} else {
dataByDate[period].push(e)
}
speciesIndex[specie] = e.Date
}
})
return dataByDate
}
function getAllTowns (geojson) {
const towns = []
geojson.features.forEach((t) => {
towns.push({
town: t.properties.TOWNNAMEMC
})
})
return towns
}
/* node cli.js count -i=MyEBirdData.csv --town="Fayston" --state=Vermont
As this is set up, it will currently return only the first time I saw species in each town provided, in Vermont */
async function towns (opts) {
const geojson = JSON.parse(await fs.readFile('VT_Data__Town_Boundaries.geojson', 'utf8'))
const glookup = new GeoJsonGeometriesLookup(geojson)
opts.state = 'Vermont'
const dateFormat = parseDateformat('day')
let data = orderByDate(locationFilter(await getData(opts.input), opts), opts)
data.forEach(d => {
let point = {type: "Point", coordinates: [d.Longitude, d.Latitude]}
let town = glookup.getContainers(point)
if (town.features[0].properties.TOWNNAMEMC) {
d.Town = town.features[0].properties.TOWNNAMEMC
}
})
if (opts.all) {
const towns = getAllTowns(geojson)
towns.forEach(t => {
let i = 0
t.species = []
t.speciesByDate = countUniqueSpecies(data.filter(x => x.Town === t.town), dateFormat)
_.sortBy(createPeriodArray(t.speciesByDate), 'Date').forEach((e) => {
e.Species.forEach((specie) => {
t.species.push(specie['Common Name'])
i++
})
})
t.speciesTotal = i
})
fs.writeFile('vt_town_counts.json', JSON.stringify(towns), 'utf8')
} else if (opts.town) {
data = countUniqueSpecies(data.filter(x => x.Town === opts.town), dateFormat)
let i = 1
// TODO Doesn't work for MyEBirdData for some reason
_.sortBy(createPeriodArray(data), 'Date').forEach((e) => {
e.Species.forEach((specie) => {
console.log(`${i} | ${specie['Common Name']} - ${specie['Scientific Name']} | ${opts.town}, ${(specie.County) ? specie.County + ', ' : ''}${specie['State']} | ${e.Date}`)
i++
})
})
}
}
/* node cli.js count -i=MyEBirdData.csv --town="Fayston" --state=Vermont
As this is set up, it will currently return only the first time I saw species in each town provided, in Vermont */
async function regions (opts) {
const geojson = JSON.parse(await fs.readFile('Polygon_VT_Biophysical_Regions.json', 'utf8'))
const glookup = new GeoJsonGeometriesLookup(geojson)
opts.state = 'Vermont'
const dateFormat = parseDateformat('day')
let data = orderByDate(locationFilter(await getData(opts.input), opts), opts)
data.forEach(d => {
let point = {type: "Point", coordinates: [d.Longitude, d.Latitude]}
let region = glookup.getContainers(point)
// Move it just below the border. This is likely to be the main issue with this map.
if (!region.features[0]) {
point = {type: "Point", coordinates: [d.Longitude, 45-(Math.abs(parseFloat(d.Latitude))-45).toString()]}
region = glookup.getContainers(point)
}
d.Region = region.features[0].properties.name
})
function getRegions (geojson) {
const regions = []
geojson.features.forEach((r) => regions.push({ region: r.properties.name }))
return regions
}
const regions = getRegions(geojson)
regions.forEach(r => {
let i = 0
r.species = []
r.speciesByDate = countUniqueSpecies(data.filter(x => x.Region === r.region), dateFormat)
_.sortBy(createPeriodArray(r.speciesByDate), 'Date').forEach((e) => {
e.Species.forEach((specie) => {
r.species.push(specie['Common Name'])
i++
})
})
r.speciesTotal = i
console.log(`Region: ${r.region}. Species count: ${r.speciesTotal}.`)
})
// fs.writeFile('vt_region_counts.json', JSON.stringify(regions), 'utf8')
}
async function quadBirds (opts) {
if (!opts.year) {
opts.year = moment().format('YYYY')
}
const files = opts.input.split(',')
let data = []
await Promise.all(files.map(async (file) => {
const contents = await getData(file)
data = data.concat(contents)
}))
data = orderByDate(dateFilter(locationFilter(data, opts), opts))
const speciesIndex = {}
let completionDates = []
// Sort by the amount of unique entries per day
data.forEach((e) => {
const specie = e['Scientific Name']
if (!speciesIndex[specie]) {
speciesIndex[specie] = {
seen: undefined,
audio: undefined,
photo: undefined,
species: e
}
}
if (e['Submission ID'] && !speciesIndex[specie].seen) {
if (moment(e.Date, momentFormat(e.Date)).format('YYYY') === opts.year) {
speciesIndex[specie].seen = moment(e.Date, momentFormat(e.Date)).format('YYYY-MM-DD')
}
}
if (e.Format === 'Photo' && !speciesIndex[specie].photo) {
speciesIndex[specie].photo = moment(e.Date, momentFormat(e.Date)).format('YYYY-MM-DD')
}
if (e.Format === 'Audio' && !speciesIndex[specie].audio) {
speciesIndex[specie].audio = moment(e.Date, momentFormat(e.Date)).format('YYYY-MM-DD')
}
if (!speciesIndex[specie].completed &&
speciesIndex[specie].audio &&
speciesIndex[specie].photo &&
speciesIndex[specie].seen) {
if (moment(speciesIndex[specie].audio, momentFormat(speciesIndex[specie].audio)).isBefore(speciesIndex[specie].photo, momentFormat(speciesIndex[specie].audio))) {
speciesIndex[specie].completed = speciesIndex[specie].photo
} else {
speciesIndex[specie].completed = speciesIndex[specie].audio
}
completionDates.push({ Date: speciesIndex[specie].completed, species: speciesIndex[specie].species })
}
})
completionDates = orderByDate(completionDates)
if (opts.list) {
for (const species in completionDates) {
console.log(`${completionDates[species].Date}: ${completionDates[species].species['Common Name']}.`)
}
}
console.log(`You saw, photographed, and recorded audio for a total of ${completionDates.length} species in ${opts.year}.`)
}
async function today (opts) {
// I want to know:
// - Was today a big day?
// - Did I get new world birds today?
// - Did I get new country birds today?
// - Did I get new state birds today?
// - Did I get new county birds today?
// - Did I get new photo birds today?
// - Did I get new audio birds today?
}
module.exports = {
firstTimes,
biggestTime,
firstTimeList,
quadBirds,
towns,
regions
}