-
Notifications
You must be signed in to change notification settings - Fork 6
/
iNat_obs_counts_by_iconic_taxa.html
305 lines (295 loc) · 12 KB
/
iNat_obs_counts_by_iconic_taxa.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="iNaturalist Observation Counts by Iconic Taxa" />
<title>iNaturalist Observation Counts by Iconic Taxa</title>
<style>
body { font:10pt Sans-Serif; }
.tar { text-align:right; }
#main { width:100%; }
table, thead, tbody, tr, td { margin:0px; padding:3px; border-width:1px 0px;border-style:solid; border-color:lightgray; border-spacing:0px; border-collapse:collapse; }
thead tr { font-weight:600; background:green; color:white; }
tfoot tr { font-weight:600; background:black; color:white; }
tr { background:whitesmoke; }
tr:nth-child(even) {background-color:white }
.icon { height:48px; width:48px; border-radius:50%; }
img { margin:0px; padding:0px; border:0px; }
a { text-decoration:none; }
</style>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/d3-sankey@0"></script>
</head>
<body>
<script>
let winurlstr = window.location.href;
let winurlsearchstr = window.location.search;
let winurlexsearchstr = winurlstr.replace(winurlsearchstr,'');
var winurlparams = new URLSearchParams(winurlsearchstr.substring(1));
winurlparams.delete('per_page');
winurlparams.delete('only_id');
winurlparams.delete('verifiable');
winurlparams.delete('quality_grade');
winurlparams.delete('iconic_taxa');
function furl(url,txt=url) { return '<a href="'+url+'">'+txt+'</a>'; };
function famp(str) { return str.replace(/&/g,'&'); };
function fcomnum(n) { return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',') };
function fpct(d,p=1) {
x = d*100;
return x.toFixed(p);
};
function faddelem(etype,eparent,eclass=null,eid=null,ehtml=null) {
var eobj = document.createElement(etype);
if (eclass!==null) { eobj.classList = eclass };
if (eid!==null) { eobj.id = eid };
if (ehtml!==null) { eobj.innerHTML = ehtml };
eparent.appendChild(eobj);
return eobj;
};
function fsettdvalue(rlabel,clabel,val) {
document.getElementById(rlabel+'_'+clabel).innerHTML = val;
};
function fgetcount(url) {
return fetch(url)
.then((response) => {
if (!response.ok) { throw new Error(response.status+': '+response.statusText); };
return response.json();
})
.then((data) => { return data.total_results; })
.catch((err) => { console.error(err); });
};
var apiurl = 'https://api.inaturalist.org/v1/observations?per_page=0&only_id=true'+((winurlparams!='')?('&'+winurlparams):'');
var ary_it = [
{icon_taxa:"Mammalia",disp_name:"Mammals",icon:"🐒",color:"mediumblue"},
{icon_taxa:"Aves",disp_name:"Birds",icon:"🦅",color:"blue"},
{icon_taxa:"Reptilia",disp_name:"Reptiles",icon:"🐍",color:"darkblue"},
{icon_taxa:"Amphibia",disp_name:"Amphibians",icon:"🐸",color:"navy"},
{icon_taxa:"Actinopterygii",disp_name:"Ray-Finned Fish",icon:"🐠",color:"midnightblue"},
{icon_taxa:"Mollusca",disp_name:"Mollusks",icon:"🐌",color:"orangered"},
{icon_taxa:"Insecta",disp_name:"Insects",icon:"🐞",color:"red"},
{icon_taxa:"Arachnida",disp_name:"Arachnids",icon:"🕷",color:"crimson"},
{icon_taxa:"Animalia",disp_name:"Other Animals",icon:"🦀",color:"royalblue"},
{icon_taxa:"Plantae",disp_name:"Plants",icon:"🌱",color:"green"},
{icon_taxa:"Fungi",disp_name:"Fungi",icon:"🍄",color:"magenta"},
{icon_taxa:"Chromista",disp_name:"Chromista",color:"saddlebrown"},
{icon_taxa:"Protozoa",disp_name:"Protozoa",color:"purple"},
{icon_taxa:"unknown",disp_name:"Unknown",color:"gray"},
{icon_taxa:"All",disp_name:"All",icon:"🌐",color:"none"},
];
faddelem('h1',document.body,null,null,'iNaturalist Observation Counts by Iconic Taxa');
// create the basic structure of the table
var table = faddelem('table',document.body,null,'main');
var thead = faddelem('thead',table);
var hrow = faddelem('tr',thead);
faddelem('td',hrow,null,null,'Iconic Taxon');
faddelem('td',hrow);
faddelem('td',hrow,'tar',null,'Verifiable');
faddelem('td',hrow,'tar',null,'R Grade');
faddelem('td',hrow,'tar',null,'% RG of V');
faddelem('td',hrow,'tar',null,'Needs ID');
faddelem('td',hrow,'tar',null,'% NID of V');
faddelem('td',hrow,'tar',null,'All');
faddelem('td',hrow,'tar',null,'Diff All-V');
faddelem('td',hrow,'tar',null,'% V of All');
var tbody = faddelem('tbody',table);
var tfoot = faddelem('tfoot',table);
for (i=0;i<ary_it.length;i++) {
var str_it = ary_it[i].icon_taxa;
var str_dn = ary_it[i].disp_name;
var str_ic = ary_it[i].icon;
var trow = faddelem('tr',(str_it==='All'?tfoot:tbody));
faddelem('td',trow,null,str_it+'_it',str_dn);
faddelem('td',trow,null,str_it+'_ic',str_ic);
faddelem('td',trow,'tar',str_it+'_v');
faddelem('td',trow,'tar',str_it+'_rg');
faddelem('td',trow,'tar',str_it+'_rgv');
faddelem('td',trow,'tar',str_it+'_nid');
faddelem('td',trow,'tar',str_it+'_nidv');
faddelem('td',trow,'tar',str_it+'_all');
faddelem('td',trow,'tar',str_it+'_diff');
faddelem('td',trow,'tar',str_it+'_va');
};
faddelem('p',document.body,null,null,'Notes:<br />'
+'1. Unknown includes things like Bacteria.<br />'
+'2. Because these numbers may be retrieved at slightly different times, this may not represent a true snapshot at a single point in time.<br />'
+'3. This is the base query: '+furl(famp(apiurl))+'. (This page will accept most parameters from the iNaturalist API '+furl('https://api.inaturalist.org/v1/docs/#!/Observations/get_observations','Observation Search')+' endpoint.)<br />'
+'4. Due to API request limits, you will not want to run this page multiple times in quick succession. If it looks like only some data is pulling back, wait a minute or two before trying to pull data again.'
);
var data = [];
// pull data into table
// (this is separate from the creation of the table structure just in case there are failures while pulling data)
for (j=0;j<(ary_it.length-1);j++) { // note that this is using length-1 because it will purposely exclude 'All' from the iteration set.
var str_it = ary_it[j].icon_taxa
var p_it = '&iconic_taxa='+str_it;
var prom0 = Promise.resolve(str_it);
var prom1 = fgetcount(apiurl+p_it+'&verifiable=true');
var prom2 = fgetcount(apiurl+p_it+'&quality_grade=research');
var prom3 = fgetcount(apiurl+p_it);
Promise.all([prom0,prom1,prom2,prom3]).then(function(values) {
var it = values[0];
var v = values[1];
var rg = values[2];
var a = values[3];
var n = v-rg;
fsettdvalue(it,'v',fcomnum(v));
fsettdvalue(it,'rg',fcomnum(rg));
fsettdvalue(it,'rgv',fpct(rg/v));
fsettdvalue(it,'nid',fcomnum(n));
fsettdvalue(it,'nidv',fpct(n/v));
fsettdvalue(it,'all',fcomnum(a));
fsettdvalue(it,'diff',fcomnum(a-v));
fsettdvalue(it,'va',fpct(v/a));
data.push({taxon:fitdispname(it),category:'Verifiable',subcategory:'Research Grade',count:rg});
data.push({taxon:fitdispname(it),category:'Verifiable',subcategory:'Needs ID',count:n});
data.push({taxon:fitdispname(it),category:'Casual',subcategory:'Casual',count:(a-v)});
//if this is the last iteration in the set to finish, then it will also calculate totals and generate a Sankey diagram
if (data.length===(ary_it.length-1)*3) {
it = 'All';
v = 0;
rg = 0;
a = 0;
for (k=0;k<data.length;k++) {
var obj = data[k];
if (obj.subcategory==='Research Grade') {
rg = rg+obj.count;
v = v+obj.count;
};
if (obj.subcategory==='Needs ID') { v = v+obj.count; };
a = a+obj.count;
};
n = v-rg;
fsettdvalue(it,'v',fcomnum(v));
fsettdvalue(it,'rg',fcomnum(rg));
fsettdvalue(it,'rgv',fpct(rg/v));
fsettdvalue(it,'nid',fcomnum(n));
fsettdvalue(it,'nidv',fpct(n/v));
fsettdvalue(it,'all',fcomnum(a));
fsettdvalue(it,'diff',fcomnum(a-v));
fsettdvalue(it,'va',fpct(v/a));
faddelem('hr',document.body);
faddelem('h2',document.body,null,null,'Sankey Diagram');
data.sort(function(a, b) {
if(fitidx(a.taxon) < fitidx(b.taxon)) { return -1; }
if(fitidx(a.taxon) > fitidx(b.taxon)) { return 1; }
return 0;
});
fvisualize(data);
};
});
};
//return a color based on iconic taxon
function fitcolor(it) {
if (it==='All') { return 'none'; };
// if (p_color) { return p_color; };
var obj = ary_it.find(o=>o.disp_name===it);
return obj.color||'gray';
};
//return display name based on iconic taxon
function fitdispname(it) {
var obj = ary_it.find(o=>o.icon_taxa===it);
return obj.disp_name;
};
//return array index position based on iconic taxon
function fitidx(it) {
var idx = ary_it.findIndex(o=>o.disp_name===it);
return idx;
};
//this creates a Sankey diagram
//adapted from https://observablehq.com/@d3/parallel-sets
function fvisualize(data) {
data.columns = Object.keys(data[0]);
var width = window.innerWidth;
var height = 500;
var sankey = d3.sankey()
.nodeSort(null)
.linkSort(null)
.nodeWidth(5)
.nodePadding(12)
.extent([[0, 5], [width, height - 5]]);
var keys = data.columns.slice(0, -1);
var color = function(d) { return fitcolor(d); };
function fgraph() {
let index = -1;
const nodes = [];
const nodeByKey = new Map;
const indexByKey = new Map;
const links = [];
for (const k of keys) {
for (const d of data) {
const key = JSON.stringify([k, d[k]]);
if (nodeByKey.has(key)) continue;
const node = {name: d[k]};
nodes.push(node);
nodeByKey.set(key, node);
indexByKey.set(key, ++index);
};
};
for (let i = 1; i < keys.length; ++i) {
const a = keys[i - 1];
const b = keys[i];
const prefix = keys.slice(0, i + 1);
const linkByKey = new Map;
for (const d of data) {
const names = prefix.map(k => d[k]);
const key = JSON.stringify(names);
const value = d.count || 0;
let link = linkByKey.get(key);
if (link) { link.value += value; continue; }
link = {
source: indexByKey.get(JSON.stringify([a, d[a]])),
target: indexByKey.get(JSON.stringify([b, d[b]])),
names,
value
};
links.push(link);
linkByKey.set(key, link);
};
};
return {nodes, links};
};
var graph = fgraph();
const svg = d3.select("body")
.append("svg")
.attr("viewBox", [0, 0, width, height]);
const {nodes, links} = sankey({
nodes: graph.nodes.map(d => Object.assign({}, d)),
links: graph.links.map(d => Object.assign({}, d))
});
svg.append("g")
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("height", d => d.y1 - d.y0)
.attr("width", d => d.x1 - d.x0)
.append("title")
.text(d => `${d.name}\n${d.value.toLocaleString()}`);
svg.append("g")
.attr("fill", "none")
.selectAll("g")
.data(links)
.join("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", d => color(d.names[0]))
.attr("stroke-width", d => d.width)
.attr("opacity", 0.7)
.style("mix-blend-mode", "multiply")
.append("title")
.text(d => `${d.names.join(" → ")}\n${d.value.toLocaleString()}`);
svg.append("g")
.style("font", "10px sans-serif")
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
.text(d => d.name)
.append("tspan")
.text(d => ` ${d.value.toLocaleString()}`);
};
</script>
</body>
</html>