riverforecastsystem 0.0.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/dist/chunks/BEylIWPr.esm.js +1 -0
- package/dist/chunks/BRvWQp_t.esm.js +1 -0
- package/dist/chunks/BVsLaBME.esm.js +1 -0
- package/dist/chunks/CKUluXWP.esm.js +1 -0
- package/dist/chunks/Cb3cDH0t.esm.js +1 -0
- package/dist/chunks/Da0Flcf8.esm.js +1 -0
- package/dist/chunks/DpGLeScB.esm.js +1 -0
- package/dist/chunks/DvWHvDDD.esm.js +1 -0
- package/dist/chunks/pq2-5-mb.esm.js +1 -0
- package/dist/chunks/vJR8AuKC.esm.js +1 -0
- package/dist/index.esm.js +1 -0
- package/dist/v2/index.esm.js +1 -0
- package/dist/v3/discharge.esm.js +1 -0
- package/dist/v3/floodmaps.esm.js +1 -0
- package/dist/v3/hydrography.esm.js +1 -0
- package/dist/v3/index.esm.js +1 -0
- package/dist/v3/plots.esm.js +1 -0
- package/package.json +45 -10
- package/dist/chunks/CKkf73Fh.mjs +0 -1
- package/dist/chunks/CUbw7lj6.mjs +0 -1
- package/dist/chunks/CYqy14ta.mjs +0 -1
- package/dist/chunks/DAknFzIV.mjs +0 -1
- package/dist/index.mjs +0 -1
- package/src/index.js +0 -6
- package/src/v2/forecast.js +0 -77
- package/src/v2/index.js +0 -11
- package/src/v2/retrospective.js +0 -33
- package/src/v2/returnPeriods.js +0 -29
- package/src/v2/zarrFetchers.js +0 -61
package/LICENSE
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
The Clear BSD License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Riley Chad Hales PhD
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted (subject to the limitations in the disclaimer
|
|
8
|
+
below) provided that the following conditions are met:
|
|
9
|
+
|
|
10
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer.
|
|
12
|
+
|
|
13
|
+
* Redistributions in binary form must reproduce the above copyright
|
|
14
|
+
notice, this list of conditions and the following disclaimer in the
|
|
15
|
+
documentation and/or other materials provided with the distribution.
|
|
16
|
+
|
|
17
|
+
* Neither the name of the copyright holder nor the names of its
|
|
18
|
+
contributors may be used to endorse or promote products derived from this
|
|
19
|
+
software without specific prior written permission.
|
|
20
|
+
|
|
21
|
+
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
|
|
22
|
+
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
|
|
23
|
+
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
24
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
|
25
|
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
|
|
26
|
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
|
27
|
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
|
28
|
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
|
29
|
+
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
|
|
30
|
+
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
31
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
32
|
+
POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as e,g as r,u as o}from"./Da0Flcf8.esm.js";var s=Object.freeze({__proto__:null,configure:e,getConfig:r,urls:o});export{s as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as r,o as a}from"./CKUluXWP.esm.js";import{F as e}from"./pq2-5-mb.esm.js";const i="riverId",t="member",s="Q",n=async({zarrUrl:r,variable:i})=>{const t=new e(`${r}/${i}`);return await a.v3(t,{kind:"array"})},l=r=>Math.round(100*r)/100,o=async({zarrUrl:r,riverIndex:a,riverId:e})=>{if(void 0===a&&void 0===e)throw new Error("Either 'riverIndex' or 'riverId' must be provided.");return void 0===a?await m({zarrUrl:r,variable:i,value:e}):a},d=async({zarrUrl:r,riverIds:a})=>{const e=await u({zarrUrl:r,variable:i}),t=new Map;return e.forEach((r,a)=>t.set(Number(r),a)),a.map(r=>t.get(Number(r))??-1)},v=async({zarrUrl:a,variable:e,selection:i=null,round:t=!0})=>{const s=await n({zarrUrl:a,variable:e}),o=((r,a)=>{const e=a?.scale_factor,i=a?.add_offset,t=a?._FillValue;return void 0===e&&void 0===i&&void 0===t?r:r.map(r=>{const a=Number(r);return void 0!==t&&a===Number(t)?NaN:a*(e??1)+(i??0)})})([...(await r(s,i)).data],s.attrs);return t?(r=>r.map(l))(o):o},u=async({zarrUrl:r,variable:a})=>await v({zarrUrl:r,variable:a,selection:[null],round:!1}),m=async({zarrUrl:r,variable:a,value:e})=>(await u({zarrUrl:r,variable:a})).indexOf(e),c=async({zarrUrl:a})=>{const e=await n({zarrUrl:a,variable:"time"}),i=await r(e,[null]),t=e.attrs.units,s=new Date(t.split("since")[1].trim()),l={seconds:1,minutes:60,hours:3600,days:86400}[t.split("since")[0].trim()],o=s.getTime();return[...i.data].map(r=>new Date(o+Number(r)*l*1e3))};export{u as a,d as b,l as c,s as d,v as f,c as g,t as m,n as o,o as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={fromConfig(){throw new Error("riverforecastsystem excludes numcodecs/lz4: the v3 stores are written with blosc(zstd, shuffle) and blosc is the only numcodecs wasm build bundled. A store compressed with this codec cannot be read by this build.")}};export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class e extends Error{}class t extends e{_tag="NotFoundError";name="NotFoundError";path;found;constructor(e,t={}){super(`Not found: ${e}`,{cause:t.cause}),this.path=t.path,this.found=t.found}}class n extends e{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(e,t={}){super(e,{cause:t.cause}),this.path=t.path}}class r extends e{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(e){super(`Unknown codec: ${e}`),this.codec=e}}class a extends e{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(e){super([`Failed to ${e.direction} chunk`,e.codec&&`via codec "${e.codec}"`,e.chunkPath&&`at ${e.chunkPath}`].filter(Boolean).join(" "),{cause:e.cause}),this.direction=e.direction,this.codec=e.codec,this.chunkPath=e.chunkPath}}class s extends e{_tag="InvalidSelectionError";name="InvalidSelectionError"}class i extends e{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(e){super(`Unsupported: ${e}`),this.feature=e}}function o(e){return()=>{throw new i(`${e} encode`)}}class c{kind="array_to_array";constructor(e,t){if(e.keepbits<0)throw new n("keepbits must be zero or positive")}static fromConfig(e,t){return new c(e,t)}encode=o("bitround");decode(e){return e}}function u(e){return e instanceof ArrayBuffer||e instanceof SharedArrayBuffer}class d{#e;constructor(e,t,n){"number"==typeof e?this.#e=new Uint8Array(e):u(e)?this.#e=new Uint8Array(e,t,n):this.#e=new Uint8Array(Array.from(e,e=>e?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#e.byteOffset}get byteLength(){return this.#e.byteLength}get buffer(){return this.#e.buffer}get length(){return this.#e.length}get(e){let t=this.#e[e];return"number"==typeof t?0!==t:t}set(e,t){this.#e[e]=t?1:0}fill(e){this.#e.fill(e?1:0)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}class l{_data;chars;#t;constructor(e,t,n,r){if(this.chars=e,this.#t=new TextEncoder,"number"==typeof t)this._data=new Uint8Array(t*e);else if(u(t))r&&(r*=e),this._data=new Uint8Array(t,n,r);else{let n=Array.from(t);this._data=new Uint8Array(n.length*e);for(let e=0;e<n.length;e++)this.set(e,n[e])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(e){const t=new Uint8Array(this.buffer,this.byteOffset+this.chars*e,this.chars);return(new TextDecoder).decode(t).replace(/\x00/g,"")}set(e,t){const n=new Uint8Array(this.buffer,this.byteOffset+this.chars*e,this.chars);n.fill(0),n.set(this.#t.encode(t))}fill(e){const t=this.#t.encode(e);for(let e=0;e<this.length;e++)this._data.set(t,e*this.chars)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}class f{#n;chars;constructor(e,t,n,r){if(this.chars=e,"number"==typeof t)this.#n=new Int32Array(t*e);else if(u(t))r&&(r*=e),this.#n=new Int32Array(t,n,r);else{const n=t,r=new f(e,1);this.#n=new Int32Array(function*(){for(let e of n)r.set(0,e),yield*r.#n}())}}get BYTES_PER_ELEMENT(){return this.#n.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#n.byteLength}get byteOffset(){return this.#n.byteOffset}get buffer(){return this.#n.buffer}get length(){return this.#n.length/this.chars}get(e){const t=this.chars*e;let n="";for(let e=0;e<this.chars;e++)n+=String.fromCodePoint(this.#n[t+e]);return n.replace(/\u0000/g,"")}set(e,t){const n=this.chars*e,r=this.#n.subarray(n,n+this.chars);r.fill(0);for(let e=0;e<this.chars;e++)r[e]=t.codePointAt(e)??0}fill(e){this.set(0,e);let t=this.#n.subarray(0,this.chars);for(let e=1;e<this.length;e++)this.#n.set(t,e*this.chars)}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.get(e)}}function h(){if("undefined"==typeof SharedArrayBuffer)throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function y(e,t){return new SharedArrayBuffer(e)}function p(e){const t=(new TextDecoder).decode(e);try{return JSON.parse(t)}catch(e){throw new n("Failed to decode JSON",{cause:e})}}function g(e,t){const n=t/2,r=t-1;let a=0;for(let s=0;s<e.length;s+=t)for(let t=0;t<n;t+=1)a=e[s+t],e[s+t]=e[s+r-t],e[s+r-t]=a}function m(e){if("v2:object"===e)return globalThis.Array;let t=e.match(/v2:([US])(\d+)/);if(t){let[,e,n]=t;return("U"===e?f:l).bind(null,Number(n))}if("string"===e)return globalThis.Array;let r={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:d}[e];if(!r)throw new n(`Unknown or unsupported dataType: ${e}`);return r}function w(e,t){const n=e.length;"string"==typeof t&&(t="C"===t?Array.from({length:n},(e,t)=>t):Array.from({length:n},(e,t)=>n-1-t)),A(n===t.length,"Order length must match the number of dimensions.");let r=1,a=new Array(n);for(let n=t.length-1;n>=0;n--)a[t[n]]=r,r*=e[t[n]];return a}function b({name:e,configuration:t}){if("default"===e){const e=t?.separator??"/";return t=>["c",...t].join(e)}if("v2"===e){const e=t?.separator??".";return t=>t.join(e)||"0"}throw new n(`Unknown chunk key encoding: ${e}`)}function _(e){if("|O"===e)return{dataType:"v2:object"};let t=e.match(/^([<|>])(.*)$/);if(!t)throw new n(`Invalid dtype: ${e}`);let[,r,a]=t,s={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[a]??(a.startsWith("S")||a.startsWith("U")?`v2:${a}`:void 0);if(!s)throw new n(`Unsupported or unknown dtype: ${e}`);return"|"===r?{dataType:s}:{dataType:s,endian:"<"===r?"little":"big"}}function E(e){return!("fixedscaleoffset"!==e.id&&"numcodecs.fixedscaleoffset"!==e.id||"number"!=typeof e.scale||"number"!=typeof e.offset||void 0!==e.astype&&"string"!=typeof e.astype||void 0!==e.dtype&&"string"!=typeof e.dtype)}function T(e,t){if("number"!==t&&"bigint"!==t&&"boolean"!==t&&"object"!==t&&"string"!==t)return e===t;let n="bool"===e;if("boolean"===t)return n;let r=e.startsWith("v2:U")||e.startsWith("v2:S")||"string"===e;if("string"===t)return r;let a="int64"===e||"uint64"===e;if("bigint"===t)return a;let s="v2:object"===e;return"object"===t?s:!(r||a||n||s)}function k(e){return"sharding_indexed"===e?.name}function S(e){if(("uint64"===e.data_type||"int64"===e.data_type)&&null!=e.fill_value)return BigInt(e.fill_value);let t="float16"===e.data_type||"float32"===e.data_type||"float64"===e.data_type;if("string"==typeof e.fill_value&&t){let t={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(e.fill_value in t)return t[e.fill_value]}return e.fill_value}function v(e,...t){if(!t.some(t=>e instanceof t))throw e}function A(e,t=""){if(!e)throw new Error(t)}async function C(e,{format:t,signal:n}){let r;if(e instanceof ArrayBuffer)r=new Response(e);else{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);r=new Response(t.slice().buffer)}A(r.body,"Response does not contain body.");try{const e=new Response(r.body.pipeThrough(new DecompressionStream(t),{signal:n}));return await e.arrayBuffer()}catch{throw n?.throwIfAborted(),new Error(`Failed to decode ${t}`)}}const N=function(){const e=new Uint32Array([305419896]);return!(18===new Uint8Array(e.buffer,e.byteOffset,e.byteLength)[0])}();function B(e){return"BYTES_PER_ELEMENT"in e?e.BYTES_PER_ELEMENT:4}class M{kind="array_to_bytes";#r;#a;#s;#i;#o;constructor(e,t){this.#o=e?.endian,this.#a=m(t.dataType),this.#i=t.shape,this.#r=w(t.shape,"C");const n=new this.#a(0);this.#s=n.BYTES_PER_ELEMENT}static fromConfig(e,t){return new M(e,t)}encode(e){let t=new Uint8Array(e.data.buffer);return N&&"big"===this.#o&&g(t,B(this.#a)),t}computeEncodedSize(e){return e}decode(e){return N&&"big"===this.#o&&g(e,B(this.#a)),{data:new this.#a(e.buffer,e.byteOffset,e.byteLength/this.#s),shape:this.#i,stride:this.#r}}}const L={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},I={float16:2,float32:4,float64:8};function $(e){return e in I}function x(e){return"int64"===e||"uint64"===e}function U(e,t){if(x(e)){if("number"!=typeof t||!Number.isInteger(t))throw new n(`Expected an integer value for data type "${e}", got ${JSON.stringify(t)}`);return BigInt(t)}if("number"==typeof t){if(!$(e)&&!Number.isInteger(t))throw new n(`Expected an integer value for data type "${e}", got ${t}`);return t}if(!$(e))throw new n(`String-encoded scalar "${t}" is not valid for non-float data type "${e}"`);return t in L?L[t]:function(e,t){const n=BigInt(e),r=new ArrayBuffer(t),a=new DataView(r);if(2===t){if("function"!=typeof a.getFloat16)throw new i("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return a.setUint16(0,Number(n)),a.getFloat16(0)}return 4===t?(a.setUint32(0,Number(n)),a.getFloat32(0)):(a.setBigUint64(0,n),a.getFloat64(0))}(t,I[e])}const P=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),O={int8:[-128,127],uint8:[0,255],int16:[-32768,32767],uint16:[0,65535],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},R={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function F(e,t,n){return e.map(([e,r])=>({src:U(t,e),tgt:U(n,r)}))}function z(e){if(!Number.isFinite(e))return e;if(.5===Math.abs(e-Math.trunc(e))){const t=Math.floor(e),n=Math.ceil(e);return t%2==0?t:n}return Math.round(e)}function Y(e){return Math.sign(e)*Math.floor(Math.abs(e)+.5)}function V(e){switch(e){case"nearest-even":return z;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return Y}}function j(e,t,n){const r=t-e+1;switch(n){case"clamp":return n=>n<e?e:n>t?t:n;case"wrap":return n=>n>=e&&n<=t?n:((n-e)%r+r)%r+e;default:return n=>{if(n>=e&&n<=t)return n;throw new Error(`Value ${n} out of range [${e}, ${t}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function J(e,t,n){const r=t-e+1n;switch(n){case"clamp":return n=>n<e?e:n>t?t:n;case"wrap":return n=>n>=e&&n<=t?n:((n-e)%r+r)%r+e;default:return n=>{if(n>=e&&n<=t)return n;throw new Error(`Value ${n} out of range [${e}, ${t}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class D{kind="array_to_array";#c;#u;#d;#l;constructor(e,t,n,r,a,s){this.#c=t,this.#u=m(e),this.#d=W(t,e,n,r,a),this.#l=W(e,t,n,r,s)}getEncodedMeta(e){let t=e.fillValue;return null!=t&&(t=this.#l(t)),{...e,dataType:this.#c,fillValue:t}}static fromConfig(e,t){const r=t.dataType,a=e.data_type;if(!P.has(r))throw new n(`cast_value codec does not support array data type: ${r}`);if(!P.has(a))throw new n(`cast_value codec does not support encoded data type: ${a}`);const s=e.rounding??"nearest-even",i=e.scalar_map?.decode?F(e.scalar_map.decode,a,r):[],o=e.scalar_map?.encode?F(e.scalar_map.encode,r,a):[];return new D(r,a,s,e.out_of_range,i,o)}encode=o("cast_value");decode(e){const t=e.data,n=new this.#u(t.length);for(let e=0;e<t.length;e++)n[e]=this.#d(t[e]);return{data:n,shape:e.shape,stride:e.stride}}}function W(e,t,r,a,s){const i=$(e),o=x(e),c=$(t),u=x(t);let d;if(i&&c){if("nearest-even"!==r)throw new n(`cast_value float -> float only supports "nearest-even" rounding, got "${r}"`);d=e=>e}else if(!i||c||u)if(i&&u){const e=V(r),n=J(...R[t],a);d=t=>{if(!Number.isFinite(t))throw new Error(`Cannot cast ${t} to integer type without scalar_map`);return n(BigInt(e(t)))}}else if(i||o||!c)if(o&&c)d=e=>Number(e);else if(i||o||c||u)if(i||o||!u)if(!o||c||u){if(!o||!u)throw new Error(`Unhandled type combination: ${e} -> ${t}`);d=J(...R[t],a)}else{const e=j(...O[t],a);d=t=>e(Number(t))}else{const e=J(...R[t],a);d=t=>e(BigInt(t))}else d=j(...O[t],a);else d=e=>e;else{const e=V(r),n=j(...O[t],a);d=t=>{if(!Number.isFinite(t))throw new Error(`Cannot cast ${t} to integer type without scalar_map`);return n(e(t))}}if(0===s.length)return d;return e=>{const t=function(e,t){for(const n of t)if("number"==typeof n.src&&Number.isNaN(n.src)){if("number"==typeof e&&Number.isNaN(e))return n.tgt}else if(e===n.src)return n.tgt}(e,s);return void 0!==t?t:d(e)}}class q{kind="bytes_to_bytes";static fromConfig(){return new q}encode=o("crc32c");decode(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength-4)}computeEncodedSize(e){return e+4}}const G=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function K(e,t){const n=e.length;let r=0===n||1===t[n-1];for(let a=n-2;a>=0&&r;a--)r=t[a]===t[a+1]*e[a+1];if(r)return;let a=0===n||1===t[0];for(let r=1;r<n&&a;r++)a=t[r]===t[r-1]*e[r-1];if(!a)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(e)} stride=${JSON.stringify(t)}`)}class X{kind="array_to_array";#f;constructor(e){this.#f=e}static fromConfig(e,t){if(!G.has(t.dataType))throw new n(`Delta codec does not support data type: ${t.dataType}`);return new X(m(t.dataType))}encode(e){K(e.shape,e.stride);const t=e.data,n=new this.#f(t.length);n[0]=t[0];for(let e=1;e<t.length;e++)n[e]=t[e]-t[e-1];return{data:n,shape:e.shape,stride:e.stride}}decode(e){K(e.shape,e.stride);const t=e.data,n=new this.#f(t.length);n[0]=t[0];for(let e=1;e<t.length;e++)n[e]=n[e-1]+t[e];return{data:n,shape:e.shape,stride:e.stride}}}class Q{kind="bytes_to_bytes";static fromConfig(e){return new Q}encode=o("gzip");async decode(e){const t=await C(e,{format:"gzip"});return new Uint8Array(t)}}function H(e,t){return A(!Number.isNaN(t),"JsonCodec allow_nan is false but NaN was encountered during encoding."),A(t!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),A(t!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),t}function Z(e,t){return t instanceof Object&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t}class ee{configuration;kind="array_to_bytes";#h;#y;constructor(e={}){this.configuration=e;const{encoding:t="utf-8",skipkeys:n=!1,ensure_ascii:r=!0,check_circular:a=!0,allow_nan:s=!0,sort_keys:i=!0,indent:o,strict:c=!0}=e;let u=e.separators;u||(u=o?[", ",": "]:[",",":"]),this.#h={encoding:t,skipkeys:n,ensure_ascii:r,check_circular:a,allow_nan:s,indent:o,separators:u,sort_keys:i},this.#y={strict:c}}static fromConfig(e){return new ee(e)}encode(e){const{indent:t,encoding:n,ensure_ascii:r,check_circular:a,allow_nan:s,sort_keys:i}=this.#h;A("utf-8"===n,"JsonCodec does not yet support non-utf-8 encoding.");const o=[];A(a,"JsonCodec does not yet support skipping the check for circular references during encoding."),s||o.push(H),i&&o.push(Z);const c=Array.from(e.data);let u;c.push("|O"),c.push(e.shape),o.length&&(u=(e,t)=>{let n=t;for(let t of o)n=t(e,n);return n});let d=JSON.stringify(c,u,t);return r&&(d=d.replace(/[\u007F-\uFFFF]/g,e=>{const t=`0000${e.charCodeAt(0).toString(16)}`;return`\\u${t.substring(t.length-4)}`})),(new TextEncoder).encode(d)}decode(e){const{strict:t}=this.#y;A(t,"JsonCodec does not yet support non-strict decoding.");const n=p(e),r=n.pop();n.pop(),A(r,"0D not implemented for JsonCodec.");return{data:n,shape:r,stride:w(r,"C")}}}const te=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class ne{kind="array_to_array";#f;#p;#g;constructor(e,t,n){this.#p=e,this.#g=t,this.#f=n}static fromConfig(e,t){if(!te.has(t.dataType))throw new n(`scale_offset codec does not support data type: ${t.dataType}`);return new ne(U(t.dataType,e.scale??1),U(t.dataType,e.offset??0),m(t.dataType))}encode=o("scale_offset");decode(e){const t=e.data,n=new this.#f(t.length);for(let e=0;e<t.length;e++)n[e]=t[e]/this.#p+this.#g;return{data:n,shape:e.shape,stride:e.stride}}}class re{kind="bytes_to_bytes";#s;constructor(e,t){if(t){let e=new(m(t.dataType))(0);A("BYTES_PER_ELEMENT"in e,`Shuffle codec requires a fixed-size dtype, got "${t.dataType}"`),this.#s=e.BYTES_PER_ELEMENT}else this.#s=e.elementsize??4}static fromConfig(e,t){return new re(e,t)}encode(e){return function(e,t){let n=e.length,r=Math.floor(n/t),a=new Uint8Array(n);for(let n=0;n<t;n++)for(let s=0;s<r;s++)a[n*r+s]=e[s*t+n];return a}(e,this.#s)}decode(e){return function(e,t){let n=e.length,r=Math.floor(n/t),a=new Uint8Array(n);for(let n=0;n<t;n++)for(let s=0;s<r;s++)a[s*t+n]=e[n*r+s];return a}(e,this.#s)}}function ae(e){if(e instanceof d||e instanceof l||e instanceof f){return new Proxy(e,{get:(e,t)=>e.get(Number(t)),set:(e,t,n)=>(e.set(Number(t),n),!0)})}return e}function se(e,t){let n=function(e,t){let n;return n=e.data instanceof l||e.data instanceof f?new e.constructor(e.data.length,e.data.chars):new e.constructor(e.data.length),{data:n,shape:e.shape,stride:w(e.shape,t)}}(e,t),r=e.shape.length,a=e.data.length,s=Array(r).fill(0),i=ae(e.data),o=ae(n.data);for(let t=0;t<a;t++){let a=0;for(let e=0;e<r;e++)a+=s[e]*n.stride[e];o[a]=i[t],s[0]+=1;for(let t=0;t<r;t++)if(s[t]===e.shape[t]){if(t+1===r)break;s[t]=0,s[t+1]+=1}}return n}function ie(e,t){let n=function(e){return A(e.shape.length===e.stride.length,"Shape and stride must have the same length."),e.stride.map((e,t)=>({stride:e,index:t})).sort((e,t)=>t.stride-e.stride).map(e=>e.index)}(e);return A(n.length===t.length,"Orders must match"),n.every((e,n)=>e===t[n])}class oe{kind="array_to_array";#m;#w;constructor(e,t){let n=e.order??"C",r=t.shape.length,a=new Array(r),s=new Array(r);if("C"===n)for(let e=0;e<r;++e)a[e]=e,s[e]=e;else if("F"===n)for(let e=0;e<r;++e)a[e]=r-e-1,s[e]=r-e-1;else a=n,a.forEach((e,t)=>{A(void 0===s[e],`Invalid permutation: ${JSON.stringify(n)}`),s[e]=t});this.#m=a,this.#w=s}static fromConfig(e,t){return new oe(e,t)}encode(e){return ie(e,this.#w)?e:se(e,this.#w)}decode(e){return{data:e.data,shape:e.shape,stride:w(e.shape,this.#m)}}}class ce{kind="array_to_bytes";#i;#b;constructor(e){this.#i=e,this.#b=w(e,"C")}static fromConfig(e,t){return new ce(t.shape)}encode=o("vlen-utf8");decode(e){let t=new TextDecoder,n=new DataView(e.buffer),r=Array(n.getUint32(0,!0)),a=4;for(let s=0;s<r.length;s++){let i=n.getUint32(a,!0);a+=4,r[s]=t.decode(e.buffer.slice(a,a+i)),a+=i}return{data:r,shape:this.#i,stride:this.#b}}}class ue{kind="bytes_to_bytes";static fromConfig(e){return new ue}encode=o("zlib");async decode(e){const t=await C(e,{format:"deflate"});return new Uint8Array(t)}}const de=function(){let e=()=>import("numcodecs/blosc").then(e=>e.default),t=()=>import("./BVsLaBME.esm.js").then(e=>e.default),n=()=>import("./DpGLeScB.esm.js").then(e=>e.default),r=()=>Q,a=()=>ue;return(new Map).set("blosc",e).set("lz4",t).set("zstd",n).set("gzip",r).set("zlib",a).set("transpose",()=>oe).set("bytes",()=>M).set("crc32c",()=>q).set("vlen-utf8",()=>ce).set("json2",()=>ee).set("bitround",()=>c).set("cast_value",()=>D).set("scale_offset",()=>ne).set("numcodecs.blosc",e).set("numcodecs.lz4",t).set("numcodecs.zstd",n).set("numcodecs.gzip",r).set("numcodecs.zlib",a).set("numcodecs.vlen-utf8",()=>ce).set("numcodecs.shuffle",()=>re).set("numcodecs.delta",()=>X).set("numcodecs.bitround",()=>c).set("numcodecs.json2",()=>ee)}();function le(e){let t;function s(){return t||(t=async function(e){let t,a=e.codecs.map(async e=>{let t=await(de.get(e.name)?.());if(!t)throw new r(e.name);return{Codec:t,meta:e}}),s=[],i=[],o={...e};for await(let{Codec:e,meta:n}of a){let r=e.fromConfig(n.configuration,o);switch(r.kind){case"array_to_array":s.push({name:n.name,codec:r}),r.getEncodedMeta&&(o=r.getEncodedMeta(o));break;case"array_to_bytes":t={name:n.name,codec:r};break;default:i.push({name:n.name,codec:r})}}if(!t){if("v2:object"===(c=o).dataType||"string"===c.dataType)throw new n(`Cannot encode ${o.dataType} to bytes without a codec`);t={name:"bytes",codec:M.fromConfig({endian:"little"},o)}}var c;return{arrayToArray:s,arrayToBytes:t,bytesToBytes:i}}(e)),t}async function i(e,t,n){try{return await n()}catch(n){throw new a({direction:e,codec:t,cause:n})}}return{async encode(e){let t=await s();for(const{name:n,codec:r}of t.arrayToArray)e=await i("encode",n,()=>r.encode(e));let n=await i("encode",t.arrayToBytes.name,()=>t.arrayToBytes.codec.encode(e));for(const{name:e,codec:r}of t.bytesToBytes)n=await i("encode",e,()=>r.encode(n));return n},async decode(e){let t=await s();for(let n=t.bytesToBytes.length-1;n>=0;n--){const{name:r,codec:a}=t.bytesToBytes[n];e=await i("decode",r,()=>a.decode(e))}let n=await i("decode",t.arrayToBytes.name,()=>t.arrayToBytes.codec.decode(e));for(let e=t.arrayToArray.length-1;e>=0;e--){const{name:r,codec:a}=t.arrayToArray[e];n=await i("decode",r,()=>a.decode(n))}return n},async computeEncodedSize(e){let t=await s(),n=fe(t.arrayToBytes.name,t.arrayToBytes.codec,e);for(const{name:e,codec:r}of t.bytesToBytes)n=fe(e,r,n);return n}}}function fe(e,t,r){if(!t.computeEncodedSize)throw new n(`Codec "${e}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return t.computeEncodedSize(r)}const he=18446744073709551615n;function ye(e,t,n,r){if(!e.store.getRange)throw new i("sharding requires a store with getRange");let a=e.store.getRange.bind(e.store),s=t.map((e,t)=>e/r.chunk_shape[t]),o=le({dataType:"uint64",shape:[...s,2],codecs:r.index_codecs,fillValue:null}),c=16*s.reduce((e,t)=>e*t,1),u={};return async(t,r)=>{let i=t.map((e,t)=>Math.floor(e/s[t])),d=e.resolve(n(i)).path;d in u||(u[d]=(async()=>{let e=await o.computeEncodedSize(c),t=await a(d,{suffixLength:e},r);return t?await o.decode(t):null})().catch(e=>{throw delete u[d],e}));let l=await u[d];if(null===l)return;let{data:f,shape:h,stride:y}=l,p=t.map((e,t)=>e%h[t]).reduce((e,t,n)=>e+t*y[n],0),g=f[p],m=f[p+1];return g!==he||m!==he?a(d,{offset:Number(g),length:Number(m)},r):void 0}}class pe{store;path;constructor(e,t="/"){this.store=e,this.path=t}resolve(e){let t=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new pe(this.store,decodeURIComponent(new URL(e,t).pathname))}}function ge(e){return new pe(e??new Map)}class me extends pe{kind="group";#_;constructor(e,t,n){super(e,t),this.#_=n}get attrs(){return this.#_.attributes}}function we(e){const t=e.find(e=>"transpose"===e.name);return t?.configuration?.order??"C"}const be=Symbol("zarrita.context");let _e=class extends pe{kind="array";#_;[be];constructor(e,t,n){super(e,t),this.#_={...n,fill_value:S(n)},this[be]=function(e,t){let{configuration:n}=t.codecs.find(k)??{},r={encodeChunkKey:b(t.chunk_key_encoding),TypedArray:m(t.data_type),fillValue:t.fill_value};if(n){let a=we(n.codecs);return{...r,kind:"sharded",chunkShape:n.chunk_shape,codec:le({dataType:t.data_type,shape:n.chunk_shape,codecs:n.codecs,fillValue:t.fill_value}),getStrides:e=>w(e,a),getChunkBytes:ye(e,t.chunk_grid.configuration.chunk_shape,r.encodeChunkKey,n)}}let a=we(t.codecs);return{...r,kind:"regular",chunkShape:t.chunk_grid.configuration.chunk_shape,codec:le({dataType:t.data_type,shape:t.chunk_grid.configuration.chunk_shape,codecs:t.codecs,fillValue:t.fill_value}),getStrides:e=>w(e,a),async getChunkBytes(t,n){let a=r.encodeChunkKey(t),s=e.resolve(a).path;return e.store.get(s,n)}}}(this,this.#_)}get attrs(){return this.#_.attributes}get dimensionNames(){return this.#_.dimension_names}get fillValue(){return this.#_.fill_value}get shape(){return this.#_.shape}get chunks(){return this[be].chunkShape}get dtype(){return this.#_.data_type}async getChunk(e,t,n){n?.useSharedArrayBuffer&&h();let r=this[be],a=await r.getChunkBytes(e,t);if(!a){let e,t=r.chunkShape.reduce((e,t)=>e*t,1);if(n?.useSharedArrayBuffer){let n=new r.TypedArray(0);if("BYTES_PER_ELEMENT"in n){let a=y(t*n.BYTES_PER_ELEMENT);e=new r.TypedArray(a,0,t)}else console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),e=new r.TypedArray(t)}else e=new r.TypedArray(t);return e.fill(r.fillValue),{data:e,shape:r.chunkShape,stride:r.getStrides(r.chunkShape)}}return r.codec.decode(a)}is(e){return T(this.dtype,e)}};function Ee(e,...t){return function(e,t){let n=e;for(let e of t)n=n instanceof Promise?n.then(t=>e(t)):e(n);return n}(e,t)}async function Te(e){let t=e.store.arrayExtensions;if(!t?.length)return e;let n=Ee;return await n(e,...t)}let ke=function(){let e=new WeakMap;function t(t){let n=e.get(t)??{v2:0,v3:0};return e.set(t,n),n}return{increment(e,n){t(e)[n]+=1},versionMax(e){let n=t(e);return n.v3>n.v2?"v3":"v2"}}}();async function Se(e,r,a){let{path:s}=e.resolve(".zarray"),i=await e.store.get(s,{signal:a});if(!i)throw new t("v2 array",{path:s});return ke.increment(e.store,"v2"),Te(new _e(e.store,e.path,function(e,t={}){let r,a=[],s=_(e.dtype);"F"===e.order&&a.push({name:"transpose",configuration:{order:"F"}});for(let t of e.filters??[]){if("fixedscaleoffset"===t.id||"numcodecs.fixedscaleoffset"===t.id){if(!E(t))throw new n(`Invalid fixedscaleoffset filter: ${JSON.stringify(t)}`);a.push({name:"scale_offset",configuration:{scale:t.scale,offset:t.offset}});let r=t.astype??t.dtype;if(void 0!==r&&r!==e.dtype){let e=_(r).dataType;if(!T(e,"number")&&!T(e,"bigint"))throw new n(`fixedscaleoffset astype must be a numeric data type, got ${r}`);a.push({name:"cast_value",configuration:{data_type:e,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:r,...s}=t;a.push({name:`numcodecs.${r}`,configuration:s})}if("endian"in s&&"big"===s.endian&&a.push({name:"bytes",configuration:{endian:"big"}}),e.compressor){let{id:t,...n}=e.compressor;a.push({name:`numcodecs.${t}`,configuration:n})}return globalThis.Array.isArray(t._ARRAY_DIMENSIONS)&&(r=t._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:e.shape,data_type:s.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:e.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:e.dimension_separator??"."}},codecs:a,fill_value:e.fill_value,dimension_names:r,attributes:t}}(p(i),r)))}async function ve(e,n,r){let{path:a}=e.resolve(".zgroup"),s=await e.store.get(a,{signal:r});if(!s)throw new t("v2 group",{path:a});return ke.increment(e.store,"v2"),new me(e.store,e.path,function(e,t={}){return{zarr_format:3,node_type:"group",attributes:t}}(p(s),n))}async function Ae(e,r={}){let a="store"in e?e.store:e,s=ke.versionMax(a),i="v2"===s?Ae.v2:Ae.v3,o="v2"===s?Ae.v3:Ae.v2;return i(e,r).catch(a=>(v(a,t,n),o(e,r)))}function Ce(e){if(null==e)return null;if("bigint"==typeof e){if(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)throw new s(`Cannot safely convert ${e} to a number. Value exceeds Number.MAX_SAFE_INTEGER.`);return Number(e)}return e}function Ne(e,t,n=null){return void 0===t&&(t=e,e=null),{start:Ce(e),stop:Ce(t),step:Ce(n)}}function Be(e,t){e.length>t.length&&function(e,t){throw new s(`too many indicies for array; expected ${t.length}, got ${e.length}`)}(e,t)}function Me(e,t){return(e=Math.trunc(e))<0&&(e=t+e),(e>=t||e<0)&&function(e){throw new s(`index out of bounds for dimension with length ${e}`)}(t),e}Ae.v2=async function(e,r={}){let a="store"in e?e:new pe(e),{signal:s}=r,i={};return(r.attrs??1)&&(i=await async function(e,t){let n=await e.store.get(e.resolve(".zattrs").path,{signal:t});return n?p(n):{}}(a,s)),s?.throwIfAborted(),"array"===r.kind?Se(a,i,s):"group"===r.kind?ve(a,i,s):Se(a,i,s).catch(e=>(v(e,t,n),ve(a,i,s)))},Ae.v3=async function(e,n={}){let r="store"in e?e:new pe(e),a=await async function(e,n){let{store:r,path:a}=e.resolve("zarr.json"),s=await e.store.get(a,{signal:n});if(!s)throw new t("v3 array or group",{path:a});let i=p(s);return"array"===i.node_type&&(i.fill_value=S(i)),"array"===i.node_type?Te(new _e(r,e.path,i)):new me(r,e.path,i)}(r,n.signal);if(ke.increment(r.store,"v3"),void 0===n.kind)return a;if("array"===n.kind&&a instanceof _e)return a;if("group"===n.kind&&a instanceof me)return a;let s=a instanceof _e?"array":"group";throw new t(`${n.kind} at ${r.path}`,{path:r.path,found:s})};class Le{dimSel;dimLen;dimChunkLen;nitems;constructor({dimSel:e,dimLen:t,dimChunkLen:n}){e=Me(e,t),this.dimSel=e,this.dimLen=t,this.dimChunkLen=n,this.nitems=1}*[Symbol.iterator](){const e=Math.floor(this.dimSel/this.dimChunkLen),t=e*this.dimChunkLen,n=this.dimSel-t;yield{dimChunkIx:e,dimChunkSel:n}}}class Ie{start;stop;step;dimLen;dimChunkLen;nitems;nchunks;constructor({dimSel:e,dimLen:t,dimChunkLen:n}){const[r,a,i]=function({start:e,stop:t,step:n},r){if(0===n)throw new s("slice step cannot be zero");const a=(n=n??1)<0,[i,o]=a?[-1,r-1]:[0,r];return null===e?e=a?o:i:e<0?(e+=r)<i&&(e=i):e>o&&(e=o),null===t?t=a?i:o:t<0?(t+=r)<i&&(t=i):t>o&&(t=o),[e,t,n]}(e,t);this.start=r,this.stop=a,this.step=i,this.step<1&&function(){throw new s("only slices with step >= 1 are supported")}(),this.dimLen=t,this.dimChunkLen=n,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dimLen/this.dimChunkLen)}*[Symbol.iterator](){const e=Math.floor(this.start/this.dimChunkLen),t=Math.ceil(this.stop/this.dimChunkLen);for(const n of function*(e,t,n=1){void 0===t&&(t=e,e=0);for(let r=e;r<t;r+=n)yield r}(e,t)){const e=n*this.dimChunkLen,t=Math.min(this.dimLen,(n+1)*this.dimChunkLen),r=t-e;let a=0,s=0;if(this.start<e){const t=(e-this.start)%this.step;t&&(s+=this.step-t),a=Math.ceil((e-this.start)/this.step)}else s=this.start-e;const i=this.stop>t?r:this.stop-e,o=[s,i,this.step],c=[a,a+Math.ceil((i-s)/this.step),1];yield{dimChunkIx:n,dimChunkSel:o,dimOutSel:c}}}}class $e{dimIndexers;shape;constructor({selection:e,shape:t,chunkShape:n}){this.dimIndexers=function(e,t){let n=[];return null===e?n=t.map(e=>Ne(null)):Array.isArray(e)&&(n=e.map(e=>e??Ne(null))),Be(n,t),n}(e,t).map((e,r)=>new("number"==typeof e?Le:Ie)({dimSel:e,dimLen:t[r],dimChunkLen:n[r]})),this.shape=this.dimIndexers.filter(e=>e instanceof Ie).map(e=>e.nitems)}*[Symbol.iterator](){for(const e of function*(...e){if(0===e.length)return;const t=e.map(e=>e[Symbol.iterator]()),n=t.map(e=>e.next());if(n.some(e=>e.done))throw new Error("Input contains an empty iterator.");for(let r=0;;){if(n[r].done){if(t[r]=e[r][Symbol.iterator](),n[r]=t[r].next(),++r>=t.length)return}else yield n.map(({value:e})=>e),r=0;n[r]=t[r].next()}}(...this.dimIndexers)){const t=e.map(e=>e.dimChunkIx),n=e.map(e=>"dimOutSel"in e?{from:e.dimChunkSel,to:e.dimOutSel}:{from:e.dimChunkSel,to:null});yield{chunkCoords:t,mapping:n}}}}function xe(e,t){return"get"in e?e.get(t):e[t]}async function Ue(e,t,n,r){n.useSharedArrayBuffer&&h();let a=function(e){let t=e.signal,n=e.opts?.signal;return t&&n?AbortSignal.any([t,n]):t??n}(n),s=e[be];let i=new $e({selection:t,shape:e.shape,chunkShape:e.chunks});if(0===e.shape.length){let{data:t}=await e.getChunk([],{signal:a},{useSharedArrayBuffer:n.useSharedArrayBuffer});return xe(t,0)}let o,c=i.shape.reduce((e,t)=>e*t,1);if(n.useSharedArrayBuffer){let e=new s.TypedArray(0);if("BYTES_PER_ELEMENT"in e){let t=y(c*e.BYTES_PER_ELEMENT);o=new s.TypedArray(t,0,c)}else console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),o=new s.TypedArray(c)}else o=new s.TypedArray(c);let u=r.prepare(o,i.shape,s.getStrides(i.shape)),d=n.createQueue?.()??function(){const e=[];return{add:t=>e.push(t()),onIdle:()=>Promise.all(e)}}();for(const{chunkCoords:t,mapping:s}of i)d.add(async()=>{a?.throwIfAborted();let{data:i,shape:o,stride:c}=await e.getChunk(t,{signal:a},{useSharedArrayBuffer:n.useSharedArrayBuffer}),d=r.prepare(i,o,c);r.setFromChunk(u,d,s)});return await d.onIdle(),0===i.shape.length?xe(u.data,0):u}function Pe(e,t=0,n){let r=n??e.length-t;return{length:r,subarray:(n,a=r)=>Pe(e,t+n,a-n),set(n,r=0){for(let a=0;a<n.length;a++)e[t+r+a]=n.get(a)},get:n=>e[t+n]}}function Oe(e){return globalThis.Array.isArray(e.data)?{data:Pe(e.data),stride:e.stride,bytesPerElement:1}:{data:new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),stride:e.stride,bytesPerElement:e.data.BYTES_PER_ELEMENT}}const Re={prepare:(e,t,n)=>({data:e,shape:t,stride:n}),setScalar(e,t,n){let r=Oe(e);Ye(r,t,function(e,t){if(globalThis.Array.isArray(e.data))return Pe([t]);let n=new(function(e){return"chars"in e?e.constructor.bind(null,e.chars):e.constructor}(e.data))([t]);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}(e,n),r.bytesPerElement)},setFromChunk(e,t,n){let r=Oe(e);Ve(r,Oe(t),r.bytesPerElement,n)}};async function Fe(e,t=null,n={}){return Ue(e,t,n,Re)}function ze(e,t,n){return n<0&&t<e?Math.floor((e-t-1)/-n)+1:e<t?Math.floor((t-e-1)/n)+1:0}function Ye(e,t,n,r){if(0===t.length)return void e.data.set(n,0);const[a,...s]=t,[i,...o]=e.stride;if("number"==typeof a){return void Ye({data:e.data.subarray(i*a*r),stride:o},s,n,r)}const[c,u,d]=a,l=ze(c,u,d);if(0!==s.length)for(let t=0;t<l;t++){Ye({data:e.data.subarray(i*(c+d*t)*r),stride:o},s,n,r)}else for(let t=0;t<l;t++)e.data.set(n,i*(c+d*t)*r)}function Ve(e,t,n,r){const[a,...s]=r,[i,...o]=e.stride,[c,...u]=t.stride;if(null===a.from)return 0===s.length?void e.data.set(t.data.subarray(0,n),a.to*n):void Ve({data:e.data.subarray(i*a.to*n),stride:o},t,n,s);if(null===a.to){if(0===s.length){let r=a.from*n;return void e.data.set(t.data.subarray(r,r+n),0)}return void Ve(e,{data:t.data.subarray(c*a.from*n),stride:u},n,s)}const[d,l,f]=a.to,[h,y,p]=a.from,g=ze(d,l,f);if(0!==s.length)for(let r=0;r<g;r++)Ve({data:e.data.subarray(i*(d+r*f)*n),stride:o},{data:t.data.subarray(c*(h+r*p)*n),stride:u},n,s);else{if(1===f&&1===p&&1===i&&1===c){let r=h*n,a=g*n;return void e.data.set(t.data.subarray(r,r+a),d*n)}for(let r=0;r<g;r++){let a=c*(h+p*r)*n;e.data.set(t.data.subarray(a,a+n),i*(d+f*r)*n)}}}export{Fe as g,Ae as o,ge as r,Ne as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as r}from"./pq2-5-mb.esm.js";import{o as a,g as e}from"./CKUluXWP.esm.js";const i=async({zarrUrl:r,riverId:a,idx:e,idVariable:i})=>{if(void 0===e&&void 0===a)throw new Error("Either 'riverId' or 'idx' must be provided.");return void 0===e&&(e=await s({zarrUrl:r,variable:i,value:a})),e},l=async({zarrUrl:i,variable:l,selection:t=null})=>{const s=new r(`${i}/${l}`),o=await a.v2(s);return[...(await e(o,t)).data]},t=async({zarrUrl:r,variable:a})=>await l({zarrUrl:r,variable:a,selection:[null]}),s=async({zarrUrl:r,variable:a,value:e})=>(await t({zarrUrl:r,variable:a})).indexOf(e),o=async({zarrUrl:i})=>{const l=new r(`${i}/time`),t=await a.v2(l),s=await e(t,[null]),o=t.attrs.units,n=new Date(o.split("since")[1].trim()),d={seconds:1,minutes:60,hours:3600,days:86400}[o.split("since")[0].trim()],c=n.getTime();return[...s.data].map(r=>new Date(c+Number(r)*d*1e3))};async function n({baseUrl:r,date:a,riverId:e,idx:t}){if(!/^\d{8}$/.test(a))throw new Error(`Invalid date format: ${a}. Must be YYYYMMDD.`);const s=`${r||"http://geoglows-v2-forecasts.s3-website-us-west-2.amazonaws.com"}/${a}00.zarr`,n=await i({zarrUrl:s,riverId:e,idx:t,idVariable:"rivid"});let[d,c]=await Promise.all([o({zarrUrl:s}),l({zarrUrl:s,variable:"Qout",selection:[{start:0,stop:51,step:1},null,n]})]);const m=c.slice(0,d.length).map((r,a)=>isNaN(r)?-1:a).filter(r=>-1!==r),u=Array(51).fill(0).map((r,a)=>a*d.length);c=u.map(r=>c.slice(r,r+d.length)).map(r=>m.map(a=>r[a])),d=m.map(r=>d[r]);const v=(r=>{const a=r.length,e=r[0].length;let i={min:Array(e).fill(0),p20:Array(e).fill(0),p25:Array(e).fill(0),median:Array(e).fill(0),p75:Array(e).fill(0),p80:Array(e).fill(0),max:Array(e).fill(0),average:Array(e).fill(0)};return Array(e).fill(0).forEach((e,l)=>{const t=r.map(r=>r[l]).sort((r,a)=>r-a);i.min[l]=t[0],i.p20[l]=t[Math.floor(.2*a)],i.p25[l]=t[Math.floor(.25*a)],i.median[l]=t[Math.floor(.5*a)],i.p75[l]=t[Math.floor(.75*a)],i.p80[l]=t[Math.floor(.8*a)],i.max[l]=t[a-1],i.average[l]=t.reduce((r,a)=>r+a,0)/a}),i})(c);return{time:d,discharge:c,stats:v}}async function d({baseUrl:r,resolution:a="daily",riverId:e,idx:t}){if(!["hourly","daily","monthly","yearly"].includes(a))throw new Error(`Invalid resolution: ${a}. Must be one of 'hourly', 'daily', 'monthly', 'yearly'.`);["monthly","yearly"].includes(a)&&(a=`${a}-timeseries`);const s=`${r||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/${a}.zarr`,n=await i({zarrUrl:s,riverId:e,idx:t,idVariable:"river_id"}),[d,c]=await Promise.all([o({zarrUrl:s}),l({zarrUrl:s,variable:"Q",selection:[null,n]})]);return{time:d,discharge:c}}async function c({baseUrl:r,riverId:a,idx:e}){const s=`${r||"http://geoglows-v2.s3-us-west-2.amazonaws.com"}/retrospective/return-periods.zarr`,o=await i({zarrUrl:s,riverId:a,idx:e,idVariable:"river_id"}),[n,d]=await Promise.all([t({zarrUrl:s,variable:"return_period"}),l({zarrUrl:s,variable:"gumbel",selection:[null,o]})]);return n.reduce((r,a,e)=>(r[Number(a)]=Number(d[e]),r),{})}var m=Object.freeze({__proto__:null,forecast:n,retrospective:d,returnPeriods:c});export{c as a,n as f,d as r,m as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e="https://cdn.apps.geoglows.org/rfs-v3-sample-data",r={v3Base:""},s=e=>"string"==typeof e?e.trim().replace(/\/+$/,""):"",a=({v3Base:e}={})=>{void 0!==e&&(r.v3Base=s(e))},t=()=>r.v3Base||s(e),o=()=>({v3Base:t()}),i=({group:e}={})=>`${t()}/hydrography/group=${e}`,l=({group:e="0"}={})=>`${i({group:e})}/metadata.zarr`,d=["hourly","daily","monthly","yearly"],n=({resolution:e="hourly"}={})=>{if(!d.includes(e))throw new Error(`Invalid resolution: ${e}. Must be one of ${d.join(", ")}.`);return`${t()}/retrospective/${e}.zarr`},p=()=>`${t()}/retrospective/return-periods.zarr`,u=()=>`${t()}/retrospective/maximums.zarr`,m=({date:e})=>`${t()}/forecasts15/${(e=>{if(!/^\d{4}-?\d{2}-?\d{2}$/.test(e))throw new Error(`Invalid date format: ${e}. Must be YYYYMMDD or YYYY-MM-DD.`);const r=e.replace(/-/g,"");return`year=${r.slice(0,4)}/month=${r.slice(4,6)}/day=${r.slice(6,8)}`})(e)}`,$=({date:e})=>`${m({date:e})}/discharge.zarr`,f=()=>`${t()}/flood-maps`,y=()=>`${f()}/manifest.json`,c=()=>`${f()}/network_graph_fim.json`,h=Object.freeze(["timeseries","max-flow","time-to-peak","below-q95"]);var v=Object.freeze({__proto__:null,floodMapsBase:f,floodMapsManifest:y,floodMapsTileBoundaries:()=>`${f()}/tile_boundaries.pmtiles`,forecastDir:m,forecastZarr:$,hydrographyGroup:i,hydrographyMetadataZarr:l,maximumsZarr:u,retrospectiveZarr:n,returnPeriodsZarr:p,riverNetworkGraph:c,streamsPmtiles:()=>`${i({group:"0"})}/streams.pmtiles`,streamsStyles:({date:e,styleset:r})=>{if(!r)throw new Error("streamsStyles requires a styleset, consult stylesets for valid values");if(!h.includes(r))throw new Error(`Invalid styleset: ${r}. Must be one of ${h.join(", ")}.`);return`${m({date:e})}/maps/${r}/styles`},stylesets:h});export{p as a,f as b,a as c,y as d,c as e,$ as f,o as g,l as h,u as m,n as r,v as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={fromConfig(){throw new Error("riverforecastsystem excludes numcodecs/zstd: the v3 stores are written with blosc(zstd, shuffle) and blosc is the only numcodecs wasm build bundled. A store compressed with this codec cannot be read by this build.")}};export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a={"chart.cumulativeVolume":"Volumen anual acumulado","chart.dailyTimeseries":"Caudal diario retrospectivo · río {riverId}","chart.flowDurationCurve":"Curva de duración de caudales","chart.forecastHydrograph":"Pronóstico por conjuntos a 15 días · río {riverId}","chart.monthlyStatus":"Estado mensual del caudal","chart.rasterHydrograph":"Hidrograma ráster","chart.yearlyPeaks":"Caudal máximo anual","chart.yearlyVolumes":"Volúmenes anuales","axis.cumulativeVolume":"Volumen acumulado (Mm³)","axis.datetime":"Fecha y hora (UTC+00:00)","axis.dayOfPeak":"Día del pico","axis.dayOfYear":"Día del año","axis.discharge":"Caudal (m³/s)","axis.flow":"Caudal (m³/s)","axis.month":"Mes","axis.percentile":"Percentil (%)","axis.volume":"Volumen (m³ × 10⁶)","axis.year":"Año","tooltip.day":"día","series.allMonths":"Todos los meses","series.annualVolume":"Volumen anual","series.dailyMean":"Caudal medio diario","series.fiveYearAverage":"Media de 5 años","series.monthlyAverage":"Media mensual","series.ensembleMedian":"Mediana del conjunto","series.iqr":"RIC (25–75 %)","series.medianDay":"Día mediano","series.range":"Rango (mín–máx)","series.temporalOutlier":"Valor atípico temporal","label.returnPeriodYears":"{n} años","control.all":"Todo","control.resetZoom":"Restablecer zoom","control.yearsShort":"{n} a","control.zoomHint":"arrastra un recuadro para ampliar · mayús+arrastrar para desplazar",months:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"],status:["Alto","Sobre lo normal","Normal","Bajo lo normal","Bajo"]};export{a as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e,t){const s="string"==typeof e?new URL(e):e;s.pathname.endsWith("/")||(s.pathname+="/");const r=new URL(t.slice(1),s);return r.search=s.search,r}async function t(e){if(404!==e.status){if(200===e.status||206===e.status)return new Uint8Array(await e.arrayBuffer());throw new Error(`Unexpected response status ${e.status} ${e.statusText}`)}}class s{url;#e;#t;#s;constructor(e,t={}){this.url=e,this.#e=t.fetch??(e=>fetch(e)),this.#t=t.overrides??{},this.#s=t.useSuffixRequest??!1}#r(e,t){return new Request(e,(s=this.#t,r=t,{...s,...r,headers:{...s.headers,...r.headers}}));var s,r}async get(s,r={}){let i=e(this.url,s).href,h=this.#r(i,r);return t(await this.#e(h))}async getRange(s,r,i={}){let h,u=e(this.url,s);if("suffixLength"in r)h=await this.#i(u,r.suffixLength,i);else{let e={...i,headers:{...i.headers,Range:`bytes=${r.offset}-${r.offset+r.length-1}`}},t=this.#r(u,e);h=await this.#e(t)}return t(h)}async#i(e,t,s){if(this.#s){let r={...s,headers:{...s.headers,Range:`bytes=-${t}`}};return this.#e(this.#r(e,r))}let r=this.#r(e,{...s,method:"HEAD"}),i=await this.#e(r);if(!i.ok)return i;let h=i.headers.get("Content-Length"),u=Number(h),a=u-t,f={...s,headers:{...s.headers,Range:`bytes=${a}-${u-1}`}};return this.#e(this.#r(e,f))}}export{s as F};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={"chart.cumulativeVolume":"Volume annuel cumulé","chart.dailyTimeseries":"Débit journalier rétrospectif · rivière {riverId}","chart.flowDurationCurve":"Courbe des débits classés","chart.forecastHydrograph":"Prévision d'ensemble à 15 jours · rivière {riverId}","chart.monthlyStatus":"État mensuel du débit","chart.rasterHydrograph":"Hydrogramme raster","chart.yearlyPeaks":"Débit de pointe annuel","chart.yearlyVolumes":"Volumes annuels","axis.cumulativeVolume":"Volume cumulé (Mm³)","axis.datetime":"Date et heure (UTC+00:00)","axis.dayOfPeak":"Jour du pic","axis.dayOfYear":"Jour de l'année","axis.discharge":"Débit (m³/s)","axis.flow":"Débit (m³/s)","axis.month":"Mois","axis.percentile":"Centile (%)","axis.volume":"Volume (m³ × 10⁶)","axis.year":"Année","tooltip.day":"jour","series.allMonths":"Tous les mois","series.annualVolume":"Volume annuel","series.dailyMean":"Débit moyen journalier","series.fiveYearAverage":"Moyenne sur 5 ans","series.monthlyAverage":"Moyenne mensuelle","series.ensembleMedian":"Médiane d'ensemble","series.iqr":"EIQ (25–75 %)","series.medianDay":"Jour médian","series.range":"Plage (min–max)","series.temporalOutlier":"Valeur aberrante temporelle","label.returnPeriodYears":"{n} ans","control.all":"Tout","control.resetZoom":"Réinitialiser le zoom","control.yearsShort":"{n} a","control.zoomHint":"glisser un cadre pour zoomer · maj+glisser pour déplacer",months:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],status:["Élevé","Au-dessus de la normale","Normale","En dessous de la normale","Faible"]};export{e as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as s}from"./chunks/Cb3cDH0t.esm.js";import{v as m}from"./chunks/BEylIWPr.esm.js";import{u as o,g as r,c as e}from"./chunks/Da0Flcf8.esm.js";import"./chunks/pq2-5-mb.esm.js";import"./chunks/CKUluXWP.esm.js";const t={configure:e,getConfig:r,urls:o,v2:s,v3:m};export{e as configure,t as default,r as getConfig,o as urls,s as v2,m as v3};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{f as forecast,r as retrospective,a as returnPeriods}from"../chunks/Cb3cDH0t.esm.js";import"../chunks/pq2-5-mb.esm.js";import"../chunks/CKUluXWP.esm.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r,g as e,a,f as t,m as n,d as l,b as i,c as s,o}from"../chunks/BRvWQp_t.esm.js";import{f as c,r as u,a as d,m}from"../chunks/Da0Flcf8.esm.js";import{g as f,s as h}from"../chunks/CKUluXWP.esm.js";import"../chunks/pq2-5-mb.esm.js";function v(r){const e=r.length,a=r[0]?.length??0;let t={min:Array(a).fill(NaN),p20:Array(a).fill(NaN),p25:Array(a).fill(NaN),median:Array(a).fill(NaN),p75:Array(a).fill(NaN),p80:Array(a).fill(NaN),max:Array(a).fill(NaN),average:Array(a).fill(NaN),peak:NaN,memberCount:e};return Array(a).fill(0).forEach((e,a)=>{const n=r.map(r=>r[a]).sort((r,e)=>r-e),l=n.length;0!==l&&(t.min[a]=n[0],t.p20[a]=n[Math.floor(.2*l)],t.p25[a]=n[Math.floor(.25*l)],t.median[a]=n[Math.floor(.5*l)],t.p75[a]=n[Math.floor(.75*l)],t.p80[a]=n[Math.floor(.8*l)],t.max[a]=n[l-1],t.average[a]=n.reduce((r,e)=>r+e,0)/l)}),a>0&&(t.peak=t.median.reduce((r,e)=>e>r?e:r,-1/0)),t}async function g({date:i,riverIndex:s,riverId:o}){const u=c({date:i}),d=await r({zarrUrl:u,riverIndex:s,riverId:o});let[m,f,h]=await Promise.all([e({zarrUrl:u}),a({zarrUrl:u,variable:n}),t({zarrUrl:u,variable:l,selection:[null,null,d]})]);return h=f.map((r,e)=>h.slice(e*m.length,(e+1)*m.length)),{riverIndex:d,riverId:o,time:m,discharge:h,stats:v(h)}}function p(r){const e=r.length,a=r[0]?.length??0,t=Array(a).fill(NaN);let n=NaN;for(let e=0;e<a;e++){const a=r.map(r=>r[e]).sort((r,e)=>r-e),l=a.length;if(0===l)continue;const i=a[Math.floor(.5*l)];t[e]=i,i<=n||(n=i)}return{median:t,peak:n,memberCount:e}}const I=new Map,N=({zarrUrl:r})=>{let a=I.get(r);return a||(a=(async({zarrUrl:r})=>{const[a,t]=await Promise.all([o({zarrUrl:r,variable:l}),e({zarrUrl:r})]);return{discharge:a,time:t}})({zarrUrl:r}).catch(e=>{throw I.delete(r),e}),I.set(r,a)),a};async function y({date:r,riverIndices:e,riverIds:a,onProgress:t}){const n=c({date:r}),l=await N({zarrUrl:n}),o=new Map,u=[],d=e??a,m=e??await i({zarrUrl:n,riverIds:a}),v=new Map,g=l.discharge.chunks[2],I=l.discharge.shape[2];d.forEach((r,e)=>{const a=Number(m[e]);if(!Number.isInteger(a)||a<0||a>=I)return void u.push(r);const t=Math.floor(a/g),n=v.get(t);n?n.push([r,a]):v.set(t,[[r,a]])});let y=0;const z=d.length-u.length;for(const r of v.values()){const e=Math.min(...r.map(([,r])=>r)),a=Math.max(...r.map(([,r])=>r)),n=await f(l.discharge,[null,null,h(e,a+1)]),i=n.data,[c,u]=n.shape,[d,m,v]=n.stride;for(const[a,n]of r){const r=(n-e)*v,l=Array.from({length:c},(e,a)=>{const t=new Float64Array(u);for(let e=0;e<u;e++)t[e]=s(i[a*d+e*m+r]);return t});o.set(a,{riverIndex:n,...p(l)}),t?.(++y,z)}}return{date:r,time:l.time,forecasts:o,missing:u}}async function z({resolution:a="daily",riverIndex:n,riverId:i}){const s=u({resolution:a}),o=await r({zarrUrl:s,riverIndex:n,riverId:i}),[c,d]=await Promise.all([e({zarrUrl:s}),t({zarrUrl:s,variable:l,selection:[null,o]})]);return{riverIndex:o,time:c,discharge:d}}const U=["hourly","daily"];async function w({riverIndex:e,riverId:n,resolution:l="hourly"}){if(!U.includes(l))throw new Error(`Invalid resolution: ${l}. Must be one of ${U.join(", ")}.`);const i=d(),s=await r({zarrUrl:i,riverIndex:e,riverId:n}),[o,c]=await Promise.all([a({zarrUrl:i,variable:"recurrence_interval"}),t({zarrUrl:i,variable:`gumbel_${l}`,selection:[null,s]})]);return o.reduce((r,e,a)=>(r[Number(e)]=Number(c[a]),r),{})}async function b({riverIndex:a,riverId:n}){const i=m(),s=await r({zarrUrl:i,riverIndex:a,riverId:n}),[o,c]=await Promise.all([e({zarrUrl:i}),t({zarrUrl:i,variable:l,selection:[null,s]})]);return{riverIndex:s,time:o,discharge:c}}export{g as forecast,y as forecastsBulk,b as maximums,p as membersToMedian,v as membersToStats,z as retrospective,w as returnPeriods};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as t,d as e}from"../chunks/Da0Flcf8.esm.js";import{r,o as s,g as i,s as a}from"../chunks/CKUluXWP.esm.js";const n=async t=>{const e=await fetch(t);if(404!==e.status){if(!e.ok)throw new Error(`HTTP ${e.status} for ${t}`);return e.arrayBuffer()}};const o=t=>{const e=new Float32Array(t.length);for(let r=0;r<t.length;r++)e[r]=Math.fround(t[r]/1e3);return e},l=(t,e)=>{const r=new Int32Array(t.length);for(let s=0;s<t.length;s++)r[s]=t[s]+e;return r};function c(t,e){const r=t.get(e);if(void 0!==r)return t.delete(e),t.set(e,r),r}function h(t,e,r,s){for(t.set(e,r);t.size>s;)t.delete(t.keys().next().value);return r}class d{constructor(t,e,r,s){this.dataBase=t,this.fetcher=e,this.tilePath=r,this.riverTiles=s}dataBase;fetcher;tilePath;riverTiles;tiles=new Map;slices=new Map;activeTiles=new Set;static async open({fetcher:r=n,base:s=null}={}){const i=s??t(),a=await r(s?`${s}/manifest.json`:e());if(!a)throw new Error(`manifest.json not found under ${i}`);const o=JSON.parse((new TextDecoder).decode(a)),l=new Map;for(const[t,e]of Object.entries(o.tiles))l.set(t,e.path);return new d(i,r,l,new Map)}static async openTiles({tiles:e,fetcher:r=n,base:s=null}={}){const i=new d(s??t(),r,new Map(Object.entries(e)),new Map);for(const t of i.tilePath.keys()){const e=await i.tile(t);for(const r of e.riverIds){const e=i.riverTiles.get(r);e?e.push(t):i.riverTiles.set(r,[t])}}return i}coverage(){return Uint32Array.from(this.riverTiles.keys())}hasCoverage(t){return this.riverTiles.has(t)}async setActiveTiles(t){for(const e of t){if(this.activeTiles.has(e)||!this.tilePath.has(e))continue;let t;this.activeTiles.add(e);try{t=await this.tile(e)}catch(t){console.warn(`flood-maps: tile ${e} unavailable — ${t.message??t}`),this.activeTiles.delete(e),this.tiles.delete(e);continue}for(const r of t.riverIds){const t=this.riverTiles.get(r);t?t.includes(e)||t.push(e):this.riverTiles.set(r,[e])}}return this.coverage()}tile(t){let e=c(this.tiles,t);return e||(e=h(this.tiles,t,this.openTile(t),64)),e}async openTile(t){const e=this.tilePath.get(t);if(!e)throw new Error(`tile ${t} not in manifest`);const s=`${this.dataBase}/${e}`,i=await this.fetcher(`${s}/zarr.json`);if(!i)throw new Error(`zarr.json missing for ${t}`);const a=JSON.parse((new TextDecoder).decode(i)).attributes;if(!a.schemaVersion?.startsWith("tiles-1."))throw new Error(`${t}: unsupported store schema ${a.schemaVersion}`);const n=a.rivers?.comid;if(!n)throw new Error(`${t}: store attrs.rivers has no comid list`);const o=new Map;n.forEach((t,e)=>o.set(t,e));const l=r((c=s,h=this.fetcher,{async get(t){const e=await h(`${c}${t}`);return void 0===e?void 0:new Uint8Array(e)}}));var c,h;return{attrs:a,riverIds:n,rank:o,root:l,arrays:new Map}}array(t,e){let r=t.arrays.get(e);return r||(r=s.v3(t.root.resolve(e),{kind:"array"}),t.arrays.set(e,r)),r}async read1d(t,e,r,s){const n=await this.array(t,e);if(0===s)return new(n.shape.length,Uint8Array)(0);return(await i(n,[a(r,r+s)])).data}async read2d(t,e,r,s){if(0===s)return new Float32Array(0);const n=await this.array(t,e);return(await i(n,[a(r,r+s),null])).data}slice(t,e){const r=`${t}/${e}`;let s=c(this.slices,r);return s||(s=h(this.slices,r,this.loadSlice(t,e),512)),s}async loadSlice(t,e){const r=await this.tile(t),s=r.rank.get(e);if(void 0===s)throw new Error(`riverId ${e} not in tile ${t}`);const i=r.attrs.rivers,{gRow0:a,gCol0:n}=r.attrs.grid,c=i.visitStart[s],h=i.visitCount[s],d=i.pixStart[s],f=i.pixCount[s],w=i.relStart[s],u=i.relCount[s],[p,v,y,m,g,T,$,b,x,S,k,M,P]=await Promise.all([this.read1d(r,"streams/fsp_local",c,h),this.read1d(r,"streams/row",c,h),this.read1d(r,"streams/col",c,h),this.read1d(r,"streams/bed",c,h),this.read1d(r,"streams/q_baseflow",c,h),this.read2d(r,"streams/q",c,h),this.read2d(r,"streams/wse",c,h),this.read1d(r,"library/pix_row",d,f),this.read1d(r,"library/pix_col",d,f),this.read1d(r,"library/fill_mm",d,f),this.read1d(r,"library/rel_count",d,f),this.read1d(r,"library/fsp_local",w,u),this.read1d(r,"library/dtf_mm",w,u)]),j=i.runStarts[s],A=new Int32Array(j.length+1);return A.set(j),A[j.length]=h,{riverId:e,tile:t,nVisit:h,nFsp:i.fspCount[s],runStarts:A,fspLocal:p,row:l(v,a),col:l(y,n),bed:m,qBaseflow:g,q:T,wse:$,nPix:f,pixRow:l(b,a),pixCol:l(x,n),fill:o(S),relCount:k,relFspLocal:M,relDtf:o(P)}}async slicesFor(t){const e=[];for(const r of t)for(const t of this.riverTiles.get(r)??[])e.push(this.slice(t,r));return Promise.all(e)}}export{d as FloodMapsIndex,n as httpFetcher};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as t}from"../chunks/BRvWQp_t.esm.js";import{h as e,e as s}from"../chunks/Da0Flcf8.esm.js";import{g as a,s as n}from"../chunks/CKUluXWP.esm.js";import"../chunks/pq2-5-mb.esm.js";const r=async({variable:s,group:r,onProgress:o,signal:i,concurrency:h=8}={})=>{if(!s)throw new Error("fetchMetadataArray requires a variable");const c=await t({zarrUrl:e({group:r}),variable:s}),l=c.shape[0],d=c.chunks[0];if(!l||!d)throw new Error(`${s}: expected a chunked 1-D array, got shape ${c.shape}`);const u=()=>{if(i?.aborted)throw new DOMException(`Aborted while reading ${s}`,"AbortError")};u();const f=await a(c,[n(0,Math.min(d,l))]),p=new f.data.constructor(l);p.set(f.data,0);let w=Math.min(d,l);o?.({done:w,total:l});const g=[];for(let t=d;t<l;t+=d)g.push(t);let m=0;return await Promise.all(Array.from({length:Math.min(h,g.length)},async()=>{for(;m<g.length;){u();const t=g[m++],e=Math.min(t+d,l),{data:s}=await a(c,[n(t,e)]);p.set(s,t),w+=e-t,o?.({done:w,total:l})}})),u(),p},o=async({variables:s,index:r,group:o}={})=>{if(!s?.length)throw new Error("fetchMetadataAt requires at least one variable");if(!Number.isInteger(r)||r<0)throw new Error(`fetchMetadataAt requires a non-negative integer index, got ${r}`);const i=e({group:o}),h=await Promise.all(s.map(async e=>{const s=await t({zarrUrl:i,variable:e}),o=s.shape[0];if(r>=o)throw new Error(`${e}: index ${r} is past the end of the axis (${o})`);const{data:h}=await a(s,[n(r,r+1)]);return[e,Number(h[0])]}));return Object.fromEntries(h)};class i{terminal;downMap;upAdj;areaKm2;meta;constructor(t){this.terminal=t.schema.terminal_value,this.meta=t.meta,this.downMap=new Map,this.upAdj=new Map,this.areaKm2=new Map;for(const e of t.edges){const[t,s]=e;if(this.downMap.set(t,s),e.length>2&&e[2]>0&&this.areaKm2.set(t,e[2]),s!==this.terminal){let e=this.upAdj.get(s);e||this.upAdj.set(s,e=new Set),e.add(t)}}}has(t){return this.downMap.has(t)}upstreamOf(t){const e=new Set([t]),s=[t];for(let t=0;t<s.length;t++){const a=this.upAdj.get(s[t]);if(a)for(const t of a)e.has(t)||(e.add(t),s.push(t))}return e}downstreamOf(t){const e=new Set;let s=t;for(;this.downMap.has(s)&&!e.has(s);){e.add(s);const t=this.downMap.get(s);if(t===this.terminal)break;s=t}return e}upstreamClosure(t){const e=new Set;for(const s of t)for(const t of this.upstreamOf(s))e.add(t);return e}downstreamClosure(t){const e=new Set;for(const s of t)for(const t of this.downstreamOf(s))e.add(t);return e}upCounts=null;buildUpCounts(){if(this.upCounts)return this.upCounts;const t=new Map,e=new Map,s=[];for(const a of this.downMap.keys()){const n=this.upAdj.get(a)?.size??0;t.set(a,1),e.set(a,n),0===n&&s.push(a)}for(let a=0;a<s.length;a++){const n=s[a],r=this.downMap.get(n);if(void 0===r||r===this.terminal||!this.downMap.has(r))continue;t.set(r,(t.get(r)??1)+(t.get(n)??1));const o=(e.get(r)??1)-1;e.set(r,o),0===o&&s.push(r)}return this.upCounts=t,t}parentsByStem(t){const e=this.upAdj.get(t);if(!e||0===e.size)return[];const s=[...e];if(s.every(t=>this.areaKm2.has(t)))return s.sort((t,e)=>this.areaKm2.get(e)-this.areaKm2.get(t)||t-e);const a=this.buildUpCounts();return s.sort((t,e)=>(a.get(e)??0)-(a.get(t)??0)||t-e)}walkBranch(t,e,s){let a=t;for(let t=0;t<e&&!s.has(a);t++){s.add(a);const t=this.parentsByStem(a);if(0===t.length)break;a=t[0]}}aroundClick(t,e,s,a){const n=new Set;if(!this.downMap.has(t))return n;n.add(t);const r=[];let o=t;for(let t=0;t<e;t++){const t=this.parentsByStem(o);if(0===t.length)break;for(let e=1;e<t.length;e++)r.push(t[e]);if(n.has(t[0]))break;n.add(t[0]),o=t[0]}o=t;for(let t=0;t<s;t++){const t=this.downMap.get(o);if(void 0===t||t===this.terminal||!this.downMap.has(t)||n.has(t))break;for(const e of this.upAdj.get(t)??[])e!==o&&r.push(e);n.add(t),o=t}for(const t of r)this.walkBranch(t,a,n);return n}ranks=new Map;rankToOutlet(t){if(!this.downMap.has(t))return-1;const e=[];let s=t;for(;void 0===this.ranks.get(s);){e.push(s);const t=this.downMap.get(s);if(void 0===t||t===this.terminal||!this.downMap.has(t)){this.ranks.set(s,0);break}if(e.length>this.downMap.size){this.ranks.set(s,0);break}s=t}for(let t=e.length-1;t>=0;t--){const s=e[t];void 0===this.ranks.get(s)&&this.ranks.set(s,this.ranks.get(this.downMap.get(s))+1)}return this.ranks.get(t)}between(t){const e=[...new Set(t)],s=new Set(e);let a=e.filter(t=>this.downMap.has(t)).map(t=>({at:t,clicks:[t],trail:[t]}));if(a.length<2)return{corridor:s,junctions:[],detached:e};const n=a.length*this.downMap.size+1;for(let t=0;a.length>1&&t<n;t++){let t=a[0];for(const e of a)this.rankToOutlet(e.at)>this.rankToOutlet(t.at)&&(t=e);const e=this.downMap.get(t.at);if(void 0===e||e===this.terminal||!this.downMap.has(e))break;t.at=e,t.trail.push(e);const s=a.find(s=>s!==t&&s.at===e);s&&(s.clicks.push(...t.clicks),s.trail.push(...t.trail),s.junction=e,s.settled=s.trail.length,a=a.filter(e=>e!==t))}const r=[],o=e.filter(t=>!this.downMap.has(t));for(const t of a)if(t.clicks.length<2)o.push(t.clicks[0]);else{r.push(t.junction);for(const e of t.trail.slice(0,t.settled))s.add(e)}return{corridor:s,junctions:r,detached:o}}}async function h(t=s()){const e=await fetch(t);if(!e.ok)throw new Error(`river network graph fetch failed: ${e.status} ${t}`);return new i(await e.json())}export{i as RiverNetwork,r as fetchMetadataArray,o as fetchMetadataAt,h as loadRiverNetwork};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{c as configure,g as getConfig,u as urls}from"../chunks/Da0Flcf8.esm.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Chart as e,LineController as t,LineElement as a,PointElement as r,LinearScale as o,CategoryScale as i,TimeScale as n,Filler as l,Legend as s,Tooltip as d,Title as c,Decimation as m,ScatterController as u}from"chart.js";import"chartjs-adapter-date-fns";import p from"chartjs-plugin-zoom";import{MatrixController as h,MatrixElement as y}from"chartjs-chart-matrix";const g=Array.from({length:12},(e,t)=>String(t+1).padStart(2,"0")),b=[1,32,60,91,121,152,182,213,244,274,305,335],f=[0,13,28,72,87],x=["rgb(44, 125, 205)","rgb(142, 206, 238)","rgb(231, 226, 188)","rgb(255, 168, 133)","rgb(205, 35, 63)"],v=Array.from({length:51},(e,t)=>2*t),k=e=>[...v].reverse().map(t=>e[Math.floor(e.length*t/100)-(100===t?1:0)]);var C={"chart.cumulativeVolume":"Cumulative annual volume","chart.dailyTimeseries":"Retrospective daily discharge · river {riverId}","chart.flowDurationCurve":"Flow duration curve","chart.forecastHydrograph":"15-day ensemble forecast · river {riverId}","chart.monthlyStatus":"Monthly flow status","chart.rasterHydrograph":"Raster hydrograph","chart.yearlyPeaks":"Yearly peak discharge","chart.yearlyVolumes":"Yearly volumes","axis.cumulativeVolume":"Cumulative volume (Mm³)","axis.datetime":"Datetime (UTC+00:00)","axis.dayOfPeak":"Day of peak","axis.dayOfYear":"Day of year","axis.discharge":"Discharge (m³/s)","axis.flow":"Flow (m³/s)","axis.month":"Month","axis.percentile":"Percentile (%)","axis.volume":"Volume (m³ × 10⁶)","axis.year":"Year","tooltip.day":"day","series.allMonths":"All months","series.annualVolume":"Annual volume","series.dailyMean":"Daily mean discharge","series.fiveYearAverage":"5-year average","series.monthlyAverage":"Monthly average","series.ensembleMedian":"Ensemble median","series.iqr":"IQR (25–75%)","series.medianDay":"Median day","series.range":"Range (min–max)","series.temporalOutlier":"Temporal outlier","label.returnPeriodYears":"{n}-year","control.all":"All","control.resetZoom":"Reset zoom","control.yearsShort":"{n}y","control.zoomHint":"drag a box to zoom · shift-drag to pan",months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],status:["High","Above normal","Normal","Below normal","Low"]};const M={es:()=>import("../chunks/DvWHvDDD.esm.js"),fr:()=>import("../chunks/vJR8AuKC.esm.js")},A=new Map([["en",C]]);let w=C;async function R(e){const t=(e=>String(e??"en").trim().toLowerCase().split(/[-_]/)[0])(e),a=A.get(t);if(a)return w=a,w;const r=M[t];if(!r)return w=C,w;try{const e=await r(),a={...C,...e.default??e};A.set(t,a),w=a}catch{w=C}return w}const S=()=>["en",...Object.keys(M)],F=e=>w[e]??C[e]??e,W=(e,t={})=>String(F(e)).replace(/\{(\w+)\}/g,(e,a)=>a in t?String(t[a]):e);e.register(t,a,r,o,i,n,l,s,d,c),e.defaults.plugins.title.font={...e.defaults.plugins.title.font,size:18},e.defaults.plugins.legend.position="right",e.defaults.scale.title.font={size:14,weight:"bold"},e.defaults.plugins.legend.labels.usePointStyle=!0;const T=e.defaults.plugins.legend.labels.generateLabels;"function"==typeof T&&(e.defaults.plugins.legend.labels.generateLabels=e=>{const t=T(e);for(const a of t){const t=e.data.datasets[a.datasetIndex];t&&("scatter"!==t.type&&!1!==t.showLine&&(Boolean(t.fill)&&!1!==t.fill&&!t.borderWidth?a.pointStyle="rect":(a.pointStyle="line",a.strokeStyle=t.borderColor,a.lineWidth=t.borderWidth||2,a.lineDash=t.borderDash||[])))}return t});const D="#94a3b8",N="rgba(148,163,184,.12)",O="#e2e8f0";let Y=D,$=N,z=O;function j(e){const t=e??("undefined"==typeof document?null:document.documentElement);if(!t||"function"!=typeof getComputedStyle)return Y=D,$=N,void(z=O);const a=getComputedStyle(t),r=(e,t)=>a.getPropertyValue(e).trim()||t;Y=r("--rfs-chart-axis",D),$=r("--rfs-chart-grid",N),z=r("--rfs-chart-text",O)}const P=["#440154","#3b528b","#21918c","#5ec962","#fde725"],H=["#440154","#414487","#2a788e","#22a884","#7ad151","#bddf26","#fde725"],I=(e,t)=>e.replace("rgb(","rgba(").replace(")",`, ${t})`),U=(e,t={})=>({title:{display:!0,text:e,color:Y},ticks:{color:Y},grid:{color:$},...t}),E=(e,t=!0)=>({legend:{display:t,labels:{color:z,boxWidth:12,font:{size:11}}},title:{display:!0,text:e,color:z}}),V=()=>({type:"linear",min:.5,max:366.5,afterBuildTicks:e=>{e.ticks=b.map(e=>({value:e}))},ticks:{color:Y,callback:e=>F("months")[b.indexOf(Number(e))]??""},grid:{color:$}});function L(e){const t=document.createElement("div");t.className="chart-canvas";const a=document.createElement("canvas");return t.appendChild(a),e.appendChild(t),a}e.register(m,p);const Z=(e,t,a)=>{const r=new Date(e);return r.setFullYear(r.getFullYear()-t),Math.max(a,r.getTime())};function _(t,a){const r=(new Date).getUTCFullYear(),o=a.yearlyPeaks.filter(e=>e.year<r&&Number.isFinite(e.peak)),i=Math.min(...o.map(e=>e.year)),n=Math.max(...o.map(e=>e.year)),l=o.map(e=>e.peak),s=Math.min(...l),d=Math.max(...l),c=o.map(e=>2*Math.PI*(e.doy-1)/365),m=(e,t)=>Math.min(Math.abs(e-t),2*Math.PI-Math.abs(e-t)),u=c.reduce((e,t)=>{const a=c.reduce((e,a)=>e+m(a,t),0);return a<e.dist?{a:t,dist:a}:e},{a:0,dist:1/0}).a,p=Math.round(u/(2*Math.PI)*365)+1,h=c.map(e=>m(e,u)*(365/(2*Math.PI))),y=[...h].sort((e,t)=>e-t),g=y[Math.floor(.25*y.length)],b=y[Math.floor(.75*y.length)],f=b+1.5*(b-g),x=P.map((e,t)=>({type:"scatter",label:`bin ${t+1}`,backgroundColor:e,pointRadius:5,data:o.filter(e=>{return a=e.peak,Math.min(4,Math.max(0,Math.floor((a-s)/(d-s||1)*5)))===t;var a}).map(e=>({x:e.doy,y:e.year,peak:e.peak}))})),v={type:"scatter",label:F("series.temporalOutlier"),backgroundColor:"rgba(0,0,0,0)",borderColor:"#ef4444",borderWidth:2,pointRadius:8,data:o.filter((e,t)=>(e=>h[e]>f&&h[e]>30)(t)).map(e=>({x:e.doy,y:e.year}))},k={type:"line",label:F("series.medianDay"),borderColor:z,borderDash:[5,5],borderWidth:1,pointRadius:0,data:[{x:p,y:i-1},{x:p,y:n+1}]};return new e(L(t),{type:"scatter",data:{datasets:[...x,v,k]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,plugins:{...E(F("chart.yearlyPeaks")),tooltip:{callbacks:{label:e=>{const t=e.raw;return null!=t.peak?`${t.y}: ${t.peak.toFixed(1)} m³/s (day ${t.x})`:""}}}},scales:{x:{...V(),title:{display:!0,text:F("axis.dayOfPeak"),color:Y}},y:U(F("axis.year"),{min:i-1,max:n+1,ticks:{color:Y,stepSize:1,precision:0}})}}})}function X(t,a){let r=1/0,o=-1/0;for(const e of a.raster.z)for(const t of e)null!=t&&(t<r&&(r=t),t>o&&(o=t));const i=[];a.raster.z.forEach((e,t)=>e.forEach((e,r)=>{null!=e&&i.push({x:r+1,y:a.raster.years[t],v:e})}));const n=a.raster.years.length;return new e(L(t),{type:"matrix",data:{datasets:[{label:F("axis.discharge"),data:i,backgroundColor:e=>{return t=e.raw.v,H[Math.min(6,Math.max(0,Math.floor((t-r)/(o-r||1)*7)))];var t},borderWidth:0,width:e=>e.chart.chartArea?e.chart.chartArea.width/366:0,height:e=>e.chart.chartArea?e.chart.chartArea.height/n:0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,plugins:{...E(F("chart.rasterHydrograph"),!1),tooltip:{callbacks:{title:()=>"",label:e=>{const t=e.raw;return`${t.y} · ${F("tooltip.day")} ${t.x}: ${t.v.toFixed(1)} m³/s`}}}},scales:{x:{...V(),title:{display:!0,text:F("axis.dayOfYear"),color:Y}},y:U(F("axis.year"),{type:"linear",min:a.raster.years[0]-.5,max:a.raster.years[n-1]+.5,ticks:{color:Y,stepSize:5,precision:0}})}}})}e.register(u),e.register(h,y);const B=["rgb(254, 240, 1)","rgb(253, 154, 1)","rgb(255, 56, 5)","rgb(255, 0, 0)","rgb(128, 0, 106)","rgb(128, 0, 246)"],J=(e,t)=>B[Math.round(e*(B.length-1)/Math.max(1,t-1))],q=e=>null==e||""===e?NaN:Number(e);function K(e,t,a,r){if("lines"===r)return{fill:!1,borderColor:e.color,borderWidth:1.5,borderDash:[6,4],backgroundColor:void 0};const o=a[t+1],i=I(e.color,.3);return{fill:o?{target:{value:o.value},above:i,below:i}:{target:"end",above:i,below:i},borderColor:e.color,borderWidth:0,borderDash:[],backgroundColor:i}}function Q(e,{mode:t,firstX:a,lastX:r,hidden:o}){return e.map((i,n)=>({label:i.text,data:[{x:a,y:i.value},{x:r,y:i.value}],parsing:!1,hidden:o,rfsLevel:!0,order:10,pointRadius:0,pointHitRadius:0,tension:0,...K(i,n,e,t)}))}e.register(p);const G="rgb(56,189,248)",ee=(e,t)=>e.map((e,a)=>({x:e.getTime(),y:t[a]})).filter(e=>Number.isFinite(e.y));function te(t,a,{returnPeriods:r,levelsAs:o="boxes"}={}){const i=L(t),{riverId:n,time:l,stats:s}=a,d=l.length?l[0].getTime():0,c=l.length?l[l.length-1].getTime():d,m=function(e){if(!e)return[];const t=(Array.isArray(e)?e.map(e=>({label:e.label,value:q(e.value),color:e.color})):Object.entries(e).map(([e,t])=>({label:W("label.returnPeriodYears",{n:e}),value:q(t)}))).filter(e=>Number.isFinite(e.value)).sort((e,t)=>e.value-t.value);return t.map((e,a)=>{return{...e,color:e.color??J(a,t.length),text:`${e.label} · ${r=e.value,r>=100?r.toFixed(0):r>=10?r.toFixed(1):r.toFixed(2)}`};var r})}(r),u=((e,t)=>e.length>0&&Number.isFinite(t)&&t>=.9*e[0].value)(m,(s.median??[]).reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0));return new e(i,{type:"line",data:{datasets:[{label:F("series.range"),data:ee(l,s.max),parsing:!1,fill:"+1",backgroundColor:I(G,.12),borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:"_min",data:ee(l,s.min),parsing:!1,fill:!1,borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:F("series.iqr"),data:ee(l,s.p75),parsing:!1,fill:"+1",backgroundColor:I(G,.25),borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:"_p25",data:ee(l,s.p25),parsing:!1,fill:!1,borderWidth:0,pointRadius:0,pointHitRadius:0,tension:.2},{label:F("series.ensembleMedian"),data:ee(l,s.median),parsing:!1,fill:!1,borderColor:G,borderWidth:2,pointRadius:0,pointHitRadius:6,tension:.2},...Q(m,{mode:o,firstX:d,lastX:c,hidden:!u})]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",axis:"x",intersect:!1},plugins:{legend:{position:"right",labels:{color:z,boxWidth:12,font:{size:11},filter:e=>!e.text.startsWith("_")}},title:{display:!0,color:z,text:W("chart.forecastHydrograph",{riverId:n})},tooltip:{filter:e=>!e.dataset.rfsLevel,callbacks:{title:e=>new Date(e[0].parsed.x).toISOString().slice(0,16).replace("T"," ")+" UTC",label:e=>` ${e.dataset.label}: ${e.parsed.y.toFixed(2)} m³/s`}},zoom:{zoom:{drag:{enabled:!0,backgroundColor:I(G,.15),borderColor:I(G,.6),borderWidth:1},wheel:{enabled:!1},pinch:{enabled:!0},mode:"xy"},pan:{enabled:!0,mode:"xy",modifierKey:"shift"},limits:{x:{min:d,max:c}}}},scales:{x:{type:"time",time:{unit:"day",displayFormats:{day:"MMM d"}},min:d,max:c,title:{display:!0,text:F("axis.datetime"),color:Y},ticks:{color:Y,maxRotation:0},grid:{color:$}},y:{beginAtZero:!0,title:{display:!0,text:F("axis.discharge"),color:Y},grace:"5%",ticks:{color:Y},grid:{color:$}}}}})}let ae=[],re=[];const oe=e=>e.forEach(e=>e.destroy());function ie(){oe(ae),ae=[],oe(re),re=[]}function ne(){const e=[...ae,...re];if(0!==e.length){j(e[0].canvas);for(const t of e){for(const e of Object.values(t.options.scales??{}))e.title&&(e.title.color=Y),e.ticks&&(e.ticks.color=Y),e.grid&&(e.grid.color=$);const e=t.options.plugins??{};e.legend?.labels&&(e.legend.labels.color=z),e.title&&(e.title.color=z),t.update("none")}}}function le(e){const t=document.createElement("div");return t.className="plot-block",e.appendChild(t),t}async function se(t,a,{lang:r}={}){await R(r),oe(ae),ae=[],j(t),t.innerHTML="";const o=function(e){const{time:t,discharge:a}=e,r={};for(let e=0;e<t.length;e++){if(!Number.isFinite(a[e]))continue;const o=t[e].toISOString().slice(0,7);(r[o]??=[]).push(a[e])}const o=k([...a].filter(Number.isFinite).sort((e,t)=>e-t)),i=e=>Math.floor((e.getTime()-Date.UTC(e.getUTCFullYear(),0,0))/864e5),n={};for(let e=0;e<t.length;e++){const r=a[e];if(!Number.isFinite(r))continue;const o=t[e],l=o.getUTCFullYear();(!n[l]||r>n[l].peak)&&(n[l]={year:l,date:o,doy:i(o),peak:r})}const l=Object.values(n).sort((e,t)=>e.year-t.year),s={};for(const e of Object.keys(r))r[e].length<20?delete r[e]:s[e]=r[e].reduce((e,t)=>e+t,0)/r[e].length;const d=f.map(()=>[]),c=[],m={};for(const e of g){const t=Object.keys(r).filter(t=>t.endsWith(`-${e}`)).flatMap(e=>r[e]).sort((e,t)=>t-e);f.forEach((e,a)=>d[a].push(t[Math.floor(t.length*e/100)])),c.push({month:e,value:t.reduce((e,t)=>e+t,0)/t.length}),m[e]=k([...t].reverse())}const u=Array.from(new Set(Object.keys(r).map(e=>e.slice(0,4)))).sort(),p=[];for(const e of u){const t=Object.keys(s).filter(t=>t.startsWith(`${e}-`)).map(e=>s[e]);12===t.length&&p.push({year:+e,value:t.reduce((e,t)=>e+t,0)/12*31557600/1e6})}const h={};for(const{year:e,value:t}of p){const a=5*Math.floor(e/5);h[a]??={total:0,count:0},h[a].total+=t,h[a].count+=1}const y=Object.keys(h).map(Number).sort((e,t)=>e-t).map(e=>({period:e,average:h[e].total/h[e].count})),b=t[0].getUTCFullYear(),x=t[t.length-1].getUTCFullYear()+1-b,v=Array.from({length:x},(e,t)=>b+t),C=Array.from({length:x},()=>Array(366).fill(null));let M=b,A=0,w=-1;for(let e=0;e<t.length;e++){const r=t[e].getUTCFullYear();r!==M?(M=r,w=0,A+=1):w+=1,A<x&&w<366&&(C[A][w]=Number.isFinite(a[e])?a[e]:null)}const R={};for(let e=0;e<t.length;e++){const r=t[e],o=r.getUTCFullYear(),i=R[o]??={x:[],y:[]},n=i.y.length?i.y[i.y.length-1]:0;i.x.push(Date.UTC(2e3,r.getUTCMonth(),r.getUTCDate())),i.y.push(n+86400*(Number.isFinite(a[e])?a[e]:0))}return{fdc:o,monthlyFdc:m,monthlyAverages:c,monthlyStatus:d,monthlyAverageTimeseries:s,yearlyVolumes:p,fiveYearAverages:y,yearlyPeaks:l,raster:{years:v,z:C},cumulative:R}}(a);ae.push(function(t,a){const r=document.createElement("div");r.className="chart-tools",t.appendChild(r);const o=L(t),i=a.time.map((e,t)=>({x:e.getTime(),y:a.discharge[t]})).filter(e=>Number.isFinite(e.y)),n=i.length?i[0].x:0,l=i.length?i[i.length-1].x:n,s=new e(o,{type:"line",data:{datasets:[{label:F("series.dailyMean"),data:i,parsing:!1,borderColor:"#38bdf8",borderWidth:1,pointRadius:0,pointHitRadius:4,tension:0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{display:!1},title:{display:!0,text:W("chart.dailyTimeseries",{riverId:a.riverId}),color:z},decimation:{enabled:!0,algorithm:"lttb",samples:600},tooltip:{callbacks:{title:e=>new Date(e[0].parsed.x).toISOString().slice(0,10),label:e=>` ${e.parsed.y.toFixed(2)} m³/s`}},zoom:{zoom:{drag:{enabled:!0,backgroundColor:"rgba(56,189,248,.15)",borderColor:"rgba(56,189,248,.6)",borderWidth:1},wheel:{enabled:!1},pinch:{enabled:!0},mode:"xy"},pan:{enabled:!0,mode:"xy",modifierKey:"shift"},limits:{x:{min:n,max:l}}}},scales:{x:{type:"time",time:{unit:"year"},min:Z(l,10,n),max:l,title:{display:!0,text:F("axis.datetime"),color:Y},ticks:{color:Y,maxRotation:0},grid:{color:$}},y:{title:{display:!0,text:F("axis.discharge"),color:Y},beginAtZero:!0,ticks:{color:Y},grid:{color:$}}}}}),d=e=>{const t=s.options.scales.x;t.min="all"===e?n:Z(l,e,n),t.max=l,s.update("none")},c=(e,t)=>{const a=document.createElement("button");return a.className="chart-btn",a.textContent=e,a.addEventListener("click",t),a};r.append(c(W("control.yearsShort",{n:1}),()=>d(1)),c(W("control.yearsShort",{n:5}),()=>d(5)),c(W("control.yearsShort",{n:10}),()=>d(10)),c(W("control.yearsShort",{n:30}),()=>d(30)),c(F("control.all"),()=>d("all")),c(F("control.resetZoom"),()=>s.resetZoom()));const m=document.createElement("span");return m.className="chart-hint",m.textContent=F("control.zoomHint"),r.appendChild(m),s}(le(t),a),function(t,a){const r=F("status").map((e,t)=>({label:e,data:a.monthlyStatus[t],borderWidth:0,pointRadius:0,backgroundColor:I(x[t],.5),fill:t<F("status").length-1?"+1":"origin"})),o=Array.from(new Set(Object.keys(a.monthlyAverageTimeseries).map(e=>e.slice(0,4)))).sort().slice(-2).reverse().map((e,t)=>({label:`Year ${e}`,borderColor:0===t?z:"#64748b",borderWidth:0===t?2:1.5,borderDash:0===t?[]:[6,4],pointRadius:0,fill:!1,data:F("months").map((t,r)=>a.monthlyAverageTimeseries[`${e}-${String(r+1).padStart(2,"0")}`]??null)}));return new e(L(t),{type:"line",data:{labels:F("months"),datasets:[...r,{label:F("series.monthlyAverage"),data:a.monthlyAverages.map(e=>e.value),borderColor:"#009dff",borderWidth:2,borderDash:[6,4],pointRadius:0,fill:!1},...o]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:E(F("chart.monthlyStatus")),scales:{x:U(F("axis.month")),y:U(F("axis.flow"),{beginAtZero:!0})}}})}(le(t),o),function(t,a){const r=e=>v.map((t,a)=>({x:t,y:e[a]})),o=F("months").map((e,t)=>({label:e,data:r(a.monthlyFdc[String(t+1).padStart(2,"0")]),borderColor:H[t%H.length],borderWidth:1,pointRadius:0,hidden:!0}));return new e(L(t),{type:"line",data:{datasets:[{label:F("series.allMonths"),data:r(a.fdc),borderColor:"#38bdf8",borderWidth:2,pointRadius:0},...o]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,parsing:!1,interaction:{mode:"nearest",intersect:!1},plugins:E(F("chart.flowDurationCurve")),scales:{x:U(F("axis.percentile"),{type:"linear",min:0,max:100}),y:U(F("axis.flow"),{beginAtZero:!0})}}})}(le(t),o),function(t,a){const r=a.yearlyVolumes.map(e=>e.year);return new e(L(t),{type:"line",data:{labels:r,datasets:[{label:F("series.annualVolume"),data:a.yearlyVolumes.map(e=>e.value),borderColor:"#00a6ff",borderWidth:2,pointRadius:2,tension:0},{label:F("series.fiveYearAverage"),data:r.map(e=>{const t=a.fiveYearAverages.find(t=>t.period===5*Math.floor(e/5));return t?t.average:null}),borderColor:"#ef4444",borderWidth:2,pointRadius:0,stepped:!0}]},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,interaction:{mode:"index",intersect:!1},plugins:E(F("chart.yearlyVolumes")),scales:{x:U(F("axis.year")),y:U(F("axis.volume"),{beginAtZero:!0})}}})}(le(t),o),_(le(t),o),X(le(t),o),function(t,a){const r=(new Date).getUTCFullYear(),o=Object.entries(a.cumulative).map(([e,t])=>({year:+e,total:t.y[t.y.length-1]})).filter(e=>e.year<r).sort((e,t)=>e.total-t.total),i=o[0]?.year,n=o[o.length-1]?.year,l=o[Math.floor(o.length/2)]?.year,s={};null!=n&&(s[n]={color:"#3b82f6",name:`Wettest: ${n}`}),null!=i&&(s[i]={color:"#ef4444",name:`Driest: ${i}`}),null!=l&&(s[l]={color:"#22c55e",name:`Median: ${l}`});const d=Object.entries(a.cumulative).map(([e,t])=>{const a=s[+e];return{label:a?a.name:String(e),data:t.x.map((e,a)=>({x:e,y:t.y[a]/1e6})),borderColor:a?a.color:"rgba(148,163,184,.35)",borderWidth:a?2:.8,pointRadius:0,fill:!1,order:a?0:1,_hl:null!=a}});return new e(L(t),{type:"line",data:{datasets:d},options:{responsive:!0,maintainAspectRatio:!1,animation:!1,parsing:!1,interaction:{mode:"nearest",intersect:!1},plugins:{title:{display:!0,text:F("chart.cumulativeVolume"),color:z},legend:{display:!0,labels:{color:z,boxWidth:12,font:{size:11},filter:(e,t)=>!0===t.datasets[e.datasetIndex]._hl}}},scales:{x:U(F("axis.month"),{type:"time",time:{unit:"month",displayFormats:{month:"MMM"}}}),y:U(F("axis.cumulativeVolume"),{beginAtZero:!0})}}})}(le(t),o))}async function de(e,t,{lang:a,returnPeriods:r,levelsAs:o}={}){await R(a),oe(re),re=[],j(e),e.innerHTML="",re.push(te(le(e),t,{returnPeriods:r,levelsAs:o}))}export{S as availableLocales,ie as clearPlots,de as plotAllForecast,se as plotAllRetro,ne as restyleCharts,R as useLocale};
|
package/package.json
CHANGED
|
@@ -1,23 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "riverforecastsystem",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Client for reading GEOGLOWS RFS data from publicly archived Zarr data on S3.",
|
|
5
|
-
"license": "
|
|
5
|
+
"license": "BSD-3-Clause-Clear",
|
|
6
6
|
"author": "Riley Hales",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/river-forecast-system/js-riverforecastsystem.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/river-forecast-system/js-riverforecastsystem#readme",
|
|
12
|
+
"bugs": "https://github.com/river-forecast-system/js-riverforecastsystem/issues",
|
|
7
13
|
"type": "module",
|
|
8
14
|
"sideEffects": false,
|
|
15
|
+
"main": "dist/index.esm.js",
|
|
16
|
+
"module": "dist/index.esm.js",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": "./dist/index.esm.js",
|
|
19
|
+
"./v2": "./dist/v2/index.esm.js",
|
|
20
|
+
"./v3": "./dist/v3/index.esm.js",
|
|
21
|
+
"./v3/discharge": "./dist/v3/discharge.esm.js",
|
|
22
|
+
"./v3/floodmaps": "./dist/v3/floodmaps.esm.js",
|
|
23
|
+
"./v3/hydrography": "./dist/v3/hydrography.esm.js",
|
|
24
|
+
"./v3/plots": "./dist/v3/plots.esm.js"
|
|
25
|
+
},
|
|
9
26
|
"scripts": {
|
|
10
|
-
"test": "
|
|
11
|
-
"
|
|
12
|
-
"
|
|
27
|
+
"test": "vitest run",
|
|
28
|
+
"test:live": "node test/tests.js",
|
|
29
|
+
"build": "rm -rf dist && rollup -c rollup.config.js",
|
|
30
|
+
"prepare": "npm run build"
|
|
13
31
|
},
|
|
14
|
-
"
|
|
15
|
-
"
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"chart.js": "^4.5.1",
|
|
34
|
+
"chartjs-adapter-date-fns": "^3.0.0",
|
|
35
|
+
"chartjs-chart-matrix": "^3.0.5",
|
|
36
|
+
"chartjs-plugin-zoom": "^2.2.0",
|
|
37
|
+
"date-fns": "^4.4.0",
|
|
38
|
+
"numcodecs": "^0.3.2"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"chart.js": {"optional": true},
|
|
42
|
+
"chartjs-adapter-date-fns": {"optional": true},
|
|
43
|
+
"chartjs-chart-matrix": {"optional": true},
|
|
44
|
+
"chartjs-plugin-zoom": {"optional": true},
|
|
45
|
+
"date-fns": {"optional": true}
|
|
16
46
|
},
|
|
17
47
|
"devDependencies": {
|
|
18
48
|
"@rollup/plugin-commonjs": "^29.0.0",
|
|
19
49
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
20
|
-
"@rollup/plugin-terser": "^0.
|
|
21
|
-
"rollup": "
|
|
22
|
-
|
|
50
|
+
"@rollup/plugin-terser": "^1.0.0",
|
|
51
|
+
"rollup": "4.59.0",
|
|
52
|
+
"vitest": "^4.1.10",
|
|
53
|
+
"zarrita": "^0.7.3"
|
|
54
|
+
},
|
|
55
|
+
"files": [
|
|
56
|
+
"dist"
|
|
57
|
+
]
|
|
23
58
|
}
|