-
Notifications
You must be signed in to change notification settings - Fork 4
/
taxamatch.js
394 lines (382 loc) · 11.3 KB
/
taxamatch.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
/**
* Match scientific names.
*
* @module
*/
const FuzzySet = require('fuzzyset.js')
const names = require('./names')
const PHONETIZE = {
start: [
['e', /^(ae|ea|oe)/],
['j', /^dj/],
['mac', /^mc/],
['n', /^(cn|gn|kn|mn)/],
['q', /^qu/],
['r', /^wr/],
['s', /^(ps|ts)/],
['t', /^(ct|pt)/],
['u', /^eu/],
['z', /^(cz|x)/]
],
body: [
['', /h/g],
['i', /(ae|oe)/g],
['a', /(ia|oi)/g],
['s', /sc/g],
['a', /o/g],
['c', /k/g],
['i', /[euy]/g],
['s', /z/g]
],
ending: [
// -is (includes -us, -ys, -es), -im (was -um), -as (-os)
['a', /(is|im|as)$/]
]
}
/**
* Normalize a scientific name component.
*
* Converts to lowercase and removes dashes.
* Expects a latinized string.
*
* @param {string} s - Single word string.
* @returns {string}
* @private
* @example
* normalize('Leœptura') // 'leoeptura'
* normalize('Ærenea') // 'aerenea'
* normalize('Fallén') // 'fallen'
* normalize('Choriozopella') // 'choriozopella'
* normalize('trägårdhi') // 'tragardhi'
* normalize('rosa-sinensis') // 'rosasinensis'
*/
function normalize(s) {
return s.toLowerCase().replace(/-/g, '')
}
/**
* Phonetize a scientific name component.
*
* Expects a normalized string (see {@link normalize}).
* Implements the phonetic normalization from the Taxamatch algorithm by Tony Reese
* (http://www.cmar.csiro.au/datacentre/taxamatch.htm).
*
* @param {string} s - Single word string.
* @param {boolean} ending - Whether to normalize ending.
* Recommended for species and infraspecies epithets.
* @returns {string}
* @private
* @example
* phonetize('betula') // 'bitila'
* phonetize('leoeptura') // 'liptira'
* phonetize('laetifica', true) // 'litifica'
* phonetize('hydnellum') // 'hidnilim'
* phonetize('scrobiculatum', true) // 'scrabicilata'
* phonetize('zonatum', true) // 'zanata'
* phonetize('plantagi') === phonetize('plantagy') // true
* phonetize('xaaaaantheriiiiii') === phonetize('zaaaantheryyyyy') // true
* phonetize('majorum', true) === phonetize('majoris', true) // true
*/
function phonetize(s, ending = false) {
PHONETIZE.start.forEach(v => {
s = s.replace(v[1], v[0])
})
PHONETIZE.body.forEach(v => {
s = s[0] + s.slice(1).replace(v[1], v[0])
})
// Remove repating characters
s = s.replace(/([a-z])(?=\1)/g, '')
// Phonetize ending
if (ending && s.length > 4) {
PHONETIZE.ending.forEach(v => {
s = s.replace(v[1], v[0])
})
}
return s
}
/**
* Class for matching scientific names to a taxonomic dictionary.
*
* Currently supports exact, fuzzy, and phonetic matching on:
* - genus
* - species
* - first infraspecies epithet and rank
*
* @param {object[]} taxa - Taxonomic dictionary. Each taxon must have a unique id and
* `genus`, and may have `species` and `infraspecies` [{ rank, epithet }, ...].
* @param {string} [id='id'] - Key in `taxa` to use as unique object identifier.
* @example
* taxa = [
* { id: 0, genus: 'Malus' },
* { id: 1, genus: 'Malus', species: 'pumila' },
* { id: 2, genus: 'Malus', species: 'pumila', infraspecies: [{ rank: 'var.', epithet: 'asiatica' }] }
* ]
* matcher = new Matcher(taxa)
* matcher.match({ genus: 'Malus' })
* matcher.match({ genus: 'Malis' })
* matcher.match({ genus: 'Malus', species: 'pumila' })
* matcher.match({ genus: 'Malus', species: 'pimila' })
* matcher.match({ genus: 'Mala', species: 'pimila' })
* matcher.match({ genus: 'Malus', species: 'pumila', infraspecies: [{ epithet: 'asiatica'}] })
* matcher.match({ genus: 'Malus', species: 'pumila', infraspecies: [{ rank: 'f.', epithet: 'asiatica'}] })
* matcher.match({ genus: 'Malus', species: 'pumila', infraspecies: [{ rank: 'var.', epithet: 'asiatica'}] })
* matcher.match({ genus: 'Malis', species: 'pimila', infraspecies: [{ rank: 'var.', epithet: 'asiatica'}] })
* matcher.match({ genus: 'malus', species: 'pu-mila' })
*/
class Matcher {
constructor(taxa, id = 'id') {
this.taxa = taxa
this.normalized = {}
this.normalized.tree = taxa.reduce((obj, t) => {
let value = normalize(t.genus)
if (!(value in obj)) {
obj[value] = { '': { genus: t.genus } }
}
let node = obj[value]
if (t.species) {
value = normalize(t.species)
if (!(value in node)) {
node[value] = { '': { genus: t.genus, species: t.species } }
}
} else {
node[''] = t
return obj
}
node = node[value]
if (t.infraspecies && t.infraspecies[0]) {
value = normalize(t.infraspecies[0].epithet)
if (!(value in node)) {
node[value] = {}
}
node = node[value]
node[''] = t
if (t.infraspecies[0].rank) {
node[t.infraspecies[0].rank] = t
}
} else {
node[''] = t
return obj
}
return obj
}, {})
this.normalized.fuzzyGenus = FuzzySet(Object.keys(this.normalized.tree))
this.phonetized = {}
this.phonetized.tree = taxa.reduce((obj, t) => {
let value = phonetize(normalize(t.genus))
if (!(value in obj)) {
obj[value] = { '': [{ genus: t.genus }] }
}
let node = obj[value]
if (t.species) {
value = phonetize(normalize(t.species), true)
if (!(value in node)) {
node[value] = { '': [{ genus: t.genus, species: t.species }] }
}
} else {
if (id in node[''][0]) {
node[''] = [t]
} else {
node[''].push(t)
}
return obj
}
node = node[value]
if (t.infraspecies && t.infraspecies[0]) {
value = phonetize(normalize(t.infraspecies[0].epithet), true)
if (!(value in node)) {
node[value] = {}
}
node = node[value]
if (node['']) {
node[''].push(t)
} else {
node[''] = [t]
}
if (t.infraspecies[0].rank) {
node[t.infraspecies[0].rank] = [t]
}
} else {
if (id in node[''][0]) {
node[''] = [t]
} else {
node[''].push(t)
}
return obj
}
return obj
}, {})
this._fuzzyCache = new Map()
}
_getFuzzySet(obj, n = 3) {
if (!this._fuzzyCache.has(obj)) {
this._fuzzyCache.set(obj, FuzzySet(Object.keys(obj)))
if (this._fuzzyCache.size > n) {
this._fuzzyCache.delete(this._fuzzyCache.keys().next().value)
}
}
return this._fuzzyCache.get(obj)
}
_matchNode(key, node, set, scores = []) {
const results = []
if (key in node) {
results.push([node[key], [...scores, 1]])
} else {
const fuzzy = set.get(key)
if (fuzzy) {
for (let [score, match] of fuzzy) {
if (score < fuzzy[0][0]) {
break
}
results.push([node[match], [...scores, score]])
}
}
}
return results
}
_matchNormalized(name) {
const matches = []
let results
if (name.genus) {
results = this._matchNode(
normalize(name.genus), this.normalized.tree, this.normalized.fuzzyGenus)
} else {
return matches
}
if (name.species) {
results = results.reduce((obj, x) => {
const xi = this._matchNode(
normalize(name.species), x[0], this._getFuzzySet(x[0]), x[1])
if (xi.length) {
obj = obj.concat(xi)
} else {
matches.push({
incomplete: true, ...Math.min(...x[1]) < 1 && { fuzzy: x[1] }, taxon: x[0]['']
})
}
return obj
}, [])
} else {
results.forEach(x => {
matches.push({ ...Math.min(...x[1]) < 1 && { fuzzy: x[1] }, taxon: x[0][''] })
})
return matches
}
const infraspecies = (name.infraspecies && name.infraspecies[0]) || {}
if (infraspecies.epithet) {
results = results.reduce((obj, x) => {
const xi = this._matchNode(
normalize(infraspecies.epithet), x[0], this._getFuzzySet(x[0]), x[1])
if (xi.length) {
obj = obj.concat(xi)
} else {
matches.push({
incomplete: true, ...Math.min(...x[1]) < 1 && { fuzzy: x[1] }, taxon: x[0]['']
})
}
return obj
}, [])
if (infraspecies.rank) {
results = results.reduce((obj, x) => {
if (infraspecies.rank in x[0]) {
matches.push({
...Math.min(...x[1]) < 1 && { fuzzy: x[1] },
taxon: x[0][infraspecies.rank]
})
} else {
obj.push(x)
}
return obj
}, [])
}
}
results.forEach(x => {
matches.push({ ...Math.min(...x[1]) < 1 && { fuzzy: x[1] }, taxon: x[0][''] })
})
return matches
}
_matchPhonetized(name) {
let node = this.phonetized.tree
let value
// genus
if (name.genus) {
value = phonetize(normalize(name.genus))
if (value in node) {
node = node[value]
} else {
return
}
} else {
return
}
// species
if (name.species) {
value = phonetize(normalize(name.species), true)
if (value in node) {
node = node[value]
} else {
return { incomplete: true, phonetic: true, taxon: node[''] }
}
} else {
return { phonetic: true, taxon: node[''] }
}
// infraspecies
const infraspecies = (name.infraspecies && name.infraspecies[0]) || {}
if (infraspecies.epithet) {
value = phonetize(normalize(infraspecies.epithet), true)
if (value in node) {
node = node[value]
} else {
return { incomplete: true, phonetic: true, taxon: node[''] }
}
if (infraspecies.rank) {
if (infraspecies.rank in node) {
return { phonetic: true, taxon: node[infraspecies.rank] }
}
}
}
return { phonetic: true, taxon: node[''] }
}
/**
* Match scientific name to taxa.
*
* @param {names.ParsedScientificName} name - Scientific name.
* @returns {object[]} Taxon match(es) in the following order:
* - exact and complete match, or
* - complete phonetic match or fuzzy match(es)
* - incomplete exact, phonetic, or fuzzy match(es)
* Each match is in the following format:
* - {boolean} incomplete - Whether match is of a higher rank than the provided name.
* - {number[]} fuzzy - Similarity score (0-1) for each matched name component
* (in the order genus, species, infraspecies), if fuzzy.
* - {boolean} phonetic - Whether match is phonetic.
* - {object} taxon - Matched taxon.
*/
match(name) {
const matches = this._matchNormalized(name)
if (!matches[0] || matches[0].fuzzy || matches[0].incomplete) {
const phonetized = this._matchPhonetized(name)
if (phonetized) {
// Multiple taxa may have the same phonetic name
for (let taxon of phonetized.taxon) {
matches.push({ ...phonetized, taxon: taxon })
}
}
}
matches.sort((a, b) => {
return `${a.incomplete ? 1 : 0}${a.fuzzy ? 1 : 0}${a.phonetic ? 1 : 0}` -
`${b.incomplete ? 1 : 0}${b.fuzzy ? 1 : 0}${b.phonetic ? 1 : 0}`
})
// Remove matches included in more complete matches
const print = matches.map(x => names.printScientificName(x.taxon, { rank: false }))
return matches.filter((_, i) => {
for (let j = 0; j < i; j++) {
if (print[j].startsWith(print[i])) {
return false
}
}
return true
})
}
}
module.exports = {
Matcher
}